diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index e620dcb5da..b9ff0bce8b 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -65,4 +65,5 @@ dc5b3cb495002951c3a36c928c55108b0999bc3e 875f9eaad6a59abd70775c0b67a7f10d92128a5a 7a8a453746a8e4a845219948591fd17f4494a067 8b31d7deb09077bc0cce0ecf6de02c94db262a67 +4a7e1b6d9b12df211cf6fbec61cc8544e4c6bf9d diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1f1516ffc7..b3a3977ab4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -5,8 +5,14 @@ files: | (?x)^( src/Mod/AddonManager| + src/Tools| tests/src ) +exclude: | + (?x)^( + .*vcproj.*| + .*vcxproj.* + ) repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.2.0 @@ -16,11 +22,11 @@ repos: - id: check-yaml - id: check-added-large-files - id: mixed-line-ending - args: [--fix=lf] - repo: https://github.com/psf/black rev: 22.10.0 hooks: - id: black + args: ['--line-length', '100'] - repo: https://github.com/pre-commit/mirrors-clang-format rev: v15.0.7 hooks: diff --git a/src/Tools/ArchiveNameFromVersionHeader.py b/src/Tools/ArchiveNameFromVersionHeader.py index 6ed557d198..3232978cf6 100644 --- a/src/Tools/ArchiveNameFromVersionHeader.py +++ b/src/Tools/ArchiveNameFromVersionHeader.py @@ -3,28 +3,30 @@ # A convenience script to generate a deployment archive name of the form # FreeCAD_{Major Version Number}.{Minor Version Number}-{Git Revision Count}.{Git Short SHA}-{OS}-{Arch} # -import sys,getopt,platform +import sys, getopt, platform + def deserializeVersionHeader(path): version = {} try: - dat = open(path, 'r').readlines() + dat = open(path, "r").readlines() except IOError: - print('Unable to open ', path) + print("Unable to open ", path) raise for l in dat: tokens = l.split() - if len(tokens) > 1 and tokens[0].lower() == '#define': - version[tokens[1]] = tokens[2].replace('"',"") + if len(tokens) > 1 and tokens[0].lower() == "#define": + version[tokens[1]] = tokens[2].replace('"', "") return version + def main(): - OSAbbrev = {'Windows' : 'WIN', 'Darwin' : 'OSX'} + OSAbbrev = {"Windows": "WIN", "Darwin": "OSX"} SHA = None - if(len(sys.argv) < 2): + if len(sys.argv) < 2: sys.stderr.write("Usage: archiveNameFromVersion [--git-SHA=]\n") try: @@ -38,16 +40,19 @@ def main(): version = deserializeVersionHeader(sys.argv[1]) if SHA: - version['FCRepositoryHash'] = SHA + version["FCRepositoryHash"] = SHA + + print( + "FreeCAD_{Major}.{Minor}-{RevCount}.{GitShortSHA}-{OS}-{Arch}".format( + Major=version["FCVersionMajor"], + Minor=version["FCVersionMinor"], + RevCount=version["FCRevision"], + GitShortSHA=version["FCRepositoryHash"][0:7], + OS=OSAbbrev.get(platform.system(), "LIN"), + Arch=platform.machine(), + ) + ) - print('FreeCAD_{Major}.{Minor}-{RevCount}.{GitShortSHA}-{OS}-{Arch}'.format( - Major=version['FCVersionMajor'], - Minor=version['FCVersionMinor'], - RevCount=version['FCRevision'], - GitShortSHA=version['FCRepositoryHash'][0:7], - OS=OSAbbrev.get(platform.system(), 'LIN'), - Arch=platform.machine())) if __name__ == "__main__": main() - diff --git a/src/Tools/DownloadStatistics.py b/src/Tools/DownloadStatistics.py index 86dee09096..d335cb52de 100644 --- a/src/Tools/DownloadStatistics.py +++ b/src/Tools/DownloadStatistics.py @@ -1,8 +1,8 @@ import requests -r=requests.get('https://api.github.com/repos/FreeCAD/FreeCAD/releases') + +r = requests.get("https://api.github.com/repos/FreeCAD/FreeCAD/releases") myobj = r.json() for p in myobj: if "assets" in p: - for asset in p['assets']: - print (asset['name'] + ": " + str(asset['download_count']) + - " downloads") + for asset in p["assets"]: + print(asset["name"] + ": " + str(asset["download_count"]) + " downloads") diff --git a/src/Tools/FCFileTools.py b/src/Tools/FCFileTools.py index c0c4cd013c..2d5e061452 100644 --- a/src/Tools/FCFileTools.py +++ b/src/Tools/FCFileTools.py @@ -1,32 +1,32 @@ - - # shell and operating system import os, sys, re + verbose = 0 dcount = fcount = 0 maxfileload = 100000 blksize = 1024 * 8 + def cpfile(pathFrom, pathTo, maxfileload=maxfileload): """ copy file pathFrom to pathTo, byte for byte """ if os.path.getsize(pathFrom) <= maxfileload: - bytesFrom = open(pathFrom, 'rb').read() # read small file all at once - bytesTo = open(pathTo, 'wb') - bytesTo.write(bytesFrom) # need b mode on Windows - #bytesTo.close() - #bytesFrom.close() + bytesFrom = open(pathFrom, "rb").read() # read small file all at once + bytesTo = open(pathTo, "wb") + bytesTo.write(bytesFrom) # need b mode on Windows + # bytesTo.close() + # bytesFrom.close() else: - fileFrom = open(pathFrom, 'rb') # read big files in chunks - fileTo = open(pathTo, 'wb') # need b mode here too + fileFrom = open(pathFrom, "rb") # read big files in chunks + fileTo = open(pathTo, "wb") # need b mode here too while 1: - bytesFrom = fileFrom.read(blksize) # get one block, less at end - if not bytesFrom: break # empty after last chunk + bytesFrom = fileFrom.read(blksize) # get one block, less at end + if not bytesFrom: + break # empty after last chunk fileTo.write(bytesFrom) - #fileFrom.close() - #fileTo.close() - + # fileFrom.close() + # fileTo.close() def cpall(dirFrom, dirTo): @@ -34,28 +34,31 @@ def cpall(dirFrom, dirTo): copy contents of dirFrom and below to dirTo """ global dcount, fcount - for file in os.listdir(dirFrom): # for files/dirs here + for file in os.listdir(dirFrom): # for files/dirs here print(file) pathFrom = os.path.join(dirFrom, file) - pathTo = os.path.join(dirTo, file) # extend both paths - if not os.path.isdir(pathFrom): # copy simple files + pathTo = os.path.join(dirTo, file) # extend both paths + if not os.path.isdir(pathFrom): # copy simple files try: - if verbose > 1: print('copying ', pathFrom, ' to ', pathTo) + if verbose > 1: + print("copying ", pathFrom, " to ", pathTo) cpfile(pathFrom, pathTo) - fcount = fcount+1 + fcount = fcount + 1 except Exception: - print('Error copying ', pathFrom, ' to ', pathTo, ' -- skipped') + print("Error copying ", pathFrom, " to ", pathTo, " -- skipped") print(sys.exc_info()[0], sys.exc_info()[1]) else: - if verbose: print('copying dir ', pathFrom, ' to ', pathTo) + if verbose: + print("copying dir ", pathFrom, " to ", pathTo) try: - os.mkdir(pathTo) # make new subdir - cpall(pathFrom, pathTo) # recur into subdirs - dcount = dcount+1 + os.mkdir(pathTo) # make new subdir + cpall(pathFrom, pathTo) # recur into subdirs + dcount = dcount + 1 except Exception: - print('Error creating ', pathTo, ' -- skipped') + print("Error creating ", pathTo, " -- skipped") print(sys.exc_info()[0], sys.exc_info()[1]) + def SetUpFilter(MatchList): RegList = [] for regexp in MatchList: @@ -63,38 +66,42 @@ def SetUpFilter(MatchList): RegList.append(a) return RegList -def cpallWithFilter(dirFrom, dirTo,MatchList): + +def cpallWithFilter(dirFrom, dirTo, MatchList): """ copy contents of dirFrom and below to dirTo without match """ global dcount, fcount - for file in os.listdir(dirFrom): # for files/dirs here + for file in os.listdir(dirFrom): # for files/dirs here hitt = 0 for matchpat in MatchList: - if(re.match(matchpat,file)): - hitt = 1 - print('Refuse: '+file) + if re.match(matchpat, file): + hitt = 1 + print("Refuse: " + file) if hitt == 0: pathFrom = os.path.join(dirFrom, file) - pathTo = os.path.join(dirTo, file) # extend both paths - if not os.path.isdir(pathFrom): # copy simple files + pathTo = os.path.join(dirTo, file) # extend both paths + if not os.path.isdir(pathFrom): # copy simple files try: - if verbose > 1: print('copying ', pathFrom, ' to ', pathTo) + if verbose > 1: + print("copying ", pathFrom, " to ", pathTo) cpfile(pathFrom, pathTo) - fcount = fcount+1 + fcount = fcount + 1 except Exception: - print('Error copying ', pathFrom, ' to ', pathTo, ' -- skipped') + print("Error copying ", pathFrom, " to ", pathTo, " -- skipped") print(sys.exc_info()[0], sys.exc_info()[1]) else: - if verbose: print('copying dir ', pathFrom, ' to ', pathTo) + if verbose: + print("copying dir ", pathFrom, " to ", pathTo) try: - os.mkdir(pathTo) # make new subdir - cpallWithFilter(pathFrom, pathTo,MatchList) # recur into subdirs - dcount = dcount+1 + os.mkdir(pathTo) # make new subdir + cpallWithFilter(pathFrom, pathTo, MatchList) # recur into subdirs + dcount = dcount + 1 except Exception: - print('Error creating ', pathTo, ' -- skipped') + print("Error creating ", pathTo, " -- skipped") print(sys.exc_info()[0], sys.exc_info()[1]) + ################################################################ # Use: "python rmall.py directoryPath directoryPath..." # recursive directory tree deletion: removes all files and @@ -105,16 +112,16 @@ def cpallWithFilter(dirFrom, dirTo,MatchList): fcount = dcount = 0 -def rmall(dirPath): # delete dirPath and below + +def rmall(dirPath): # delete dirPath and below global fcount, dcount namesHere = os.listdir(dirPath) - for name in namesHere: # remove all contents first + for name in namesHere: # remove all contents first path = os.path.join(dirPath, name) - if not os.path.isdir(path): # remove simple files + if not os.path.isdir(path): # remove simple files os.remove(path) fcount = fcount + 1 - else: # recur to remove subdirs + else: # recur to remove subdirs rmall(path) - os.rmdir(dirPath) # remove now-empty dirPath + os.rmdir(dirPath) # remove now-empty dirPath dcount = dcount + 1 - diff --git a/src/Tools/InstallMsg.txt b/src/Tools/InstallMsg.txt index e766bec465..2850edf9d6 100644 --- a/src/Tools/InstallMsg.txt +++ b/src/Tools/InstallMsg.txt @@ -1 +1 @@ -FreeCAD is distributed under the Gnu General Public Licence. +FreeCAD is distributed under the Gnu General Public Licence. diff --git a/src/Tools/LicenseChecker.py b/src/Tools/LicenseChecker.py index 455b7c5bbd..a46cd7e5a8 100644 --- a/src/Tools/LicenseChecker.py +++ b/src/Tools/LicenseChecker.py @@ -6,43 +6,47 @@ import codecs, os -ext=[".cpp", ".cxx", ".cc", ".c", ".hpp", ".hxx", ".hh", ".h", ".inl", ".inc", ".py"] -flt=['__init__.py', '_rc.py', - 'coin_header_includes.h', - 'CxxDebug.hxx', - 'IndirectPythonInterface.hxx', - ('thumbs%sIExtractImage.h')%(os.path.sep), - #('src%sTools')%(os.path.sep), - ('src%sTools%sembedded')%(os.path.sep,os.path.sep), - ('App%skdl_cp')%(os.path.sep), - ('3rdParty%satlas')%(os.path.sep), - ('Mod%sGDML')%(os.path.sep), - ('boost%snumeric%sbindings')%(os.path.sep,os.path.sep), - ('salomesmesh%sinc')%(os.path.sep), - ('App%sCore%stritritest.h')%(os.path.sep,os.path.sep) - ] - # A note to tritritest.h - # tritritest.h has no licensing information, but Tomas Moller replied - # the following, when asked about it: - # - # The code is free to use for anyone and any projects, but I give no - # warranties. - # - # See: http://anonscm.debian.org/gitweb/?p=debian-science/packages/freecad.git;a=blob;f=debian/copyright -lic=['LGPL', - 'GNU Library', - 'GNU Lesser', - 'Permission to copy, use, modify', - 'Permission to use, copy, modify', - 'Distributed under the Boost Software License', - 'Redistribution and use in source and binary forms', - 'Redistribution and use in source and binary forms', - 'it under the same terms as Python itself', - 'As a special exception, you may create a larger work that contains', - 'Permission is hereby granted, free of charge, to any person obtaining', - 'Permission is granted to anyone to use this software', - 'This file was automatically generated by SWIG' - ] +ext = [".cpp", ".cxx", ".cc", ".c", ".hpp", ".hxx", ".hh", ".h", ".inl", ".inc", ".py"] +flt = [ + "__init__.py", + "_rc.py", + "coin_header_includes.h", + "CxxDebug.hxx", + "IndirectPythonInterface.hxx", + ("thumbs%sIExtractImage.h") % (os.path.sep), + # ('src%sTools')%(os.path.sep), + ("src%sTools%sembedded") % (os.path.sep, os.path.sep), + ("App%skdl_cp") % (os.path.sep), + ("3rdParty%satlas") % (os.path.sep), + ("Mod%sGDML") % (os.path.sep), + ("boost%snumeric%sbindings") % (os.path.sep, os.path.sep), + ("salomesmesh%sinc") % (os.path.sep), + ("App%sCore%stritritest.h") % (os.path.sep, os.path.sep), +] +# A note to tritritest.h +# tritritest.h has no licensing information, but Tomas Moller replied +# the following, when asked about it: +# +# The code is free to use for anyone and any projects, but I give no +# warranties. +# +# See: http://anonscm.debian.org/gitweb/?p=debian-science/packages/freecad.git;a=blob;f=debian/copyright +lic = [ + "LGPL", + "GNU Library", + "GNU Lesser", + "Permission to copy, use, modify", + "Permission to use, copy, modify", + "Distributed under the Boost Software License", + "Redistribution and use in source and binary forms", + "Redistribution and use in source and binary forms", + "it under the same terms as Python itself", + "As a special exception, you may create a larger work that contains", + "Permission is hereby granted, free of charge, to any person obtaining", + "Permission is granted to anyone to use this software", + "This file was automatically generated by SWIG", +] + def startProcessing(): fn = os.path.realpath(__file__) @@ -53,15 +57,16 @@ def startProcessing(): global flt traverse(fn, ext, flt) + def traverse(path, ext, flt): - for r,d,f in os.walk(path): + for r, d, f in os.walk(path): for i in f: - fn = os.path.join(r,i) + fn = os.path.join(r, i) # filter out some file names stop = False for j in flt: if fn.find(j) >= 0: - stop=True + stop = True break if stop: continue @@ -71,8 +76,9 @@ def traverse(path, ext, flt): parsefile(fn) break + def parsefile(fn): - data = codecs.open(fn,'r','utf-8') + data = codecs.open(fn, "r", "utf-8") try: lines = data.readlines() data.close() @@ -83,9 +89,10 @@ def parsefile(fn): if i.find(j) >= 0: return - print ("Missing license text in file %s") % (fn) + print("Missing license text in file %s") % (fn) except Exception: pass + if __name__ == "__main__": startProcessing() diff --git a/src/Tools/MakeApp.py b/src/Tools/MakeApp.py index 93d9c791e0..974c12d9a9 100644 --- a/src/Tools/MakeApp.py +++ b/src/Tools/MakeApp.py @@ -3,34 +3,34 @@ # (c) 2003 Werner Mayer LGPL # Create a new application module -import os,sys +import os, sys import MakeAppTools -if(len(sys.argv) != 2): +if len(sys.argv) != 2: sys.stdout.write("Please enter a name for your application.\n") sys.exit() Application = sys.argv[1] # create directory ../Mod/ -if not os.path.isdir("../Mod/"+Application): - os.mkdir("../Mod/"+Application) +if not os.path.isdir("../Mod/" + Application): + os.mkdir("../Mod/" + Application) else: sys.stdout.write(Application + " already exists. Please enter another name.\n") sys.exit() # copying files from _TEMPLATE_ to ../Mod/ -sys.stdout.write("Copying files...") -MakeAppTools.copyTemplate("_TEMPLATE_","../Mod/"+Application,"_TEMPLATE_", Application) -sys.stdout.write("Ok\n") +sys.stdout.write("Copying files...") +MakeAppTools.copyTemplate("_TEMPLATE_", "../Mod/" + Application, "_TEMPLATE_", Application) +sys.stdout.write("Ok\n") # replace the _TEMPLATE_ string by sys.stdout.write("Modifying files...\n") -MakeAppTools.replaceTemplate("../Mod/" + Application,"_TEMPLATE_",Application) +MakeAppTools.replaceTemplate("../Mod/" + Application, "_TEMPLATE_", Application) # make the configure script executable -#os.chmod("../Mod/" + Application + "/configure", 0777); +# os.chmod("../Mod/" + Application + "/configure", 0777); sys.stdout.write("Modifying files done.\n") -sys.stdout.write(Application + " module created successfully.\n") +sys.stdout.write(Application + " module created successfully.\n") diff --git a/src/Tools/MakeAppTools.py b/src/Tools/MakeAppTools.py index d799b2bdb4..8f55c39808 100644 --- a/src/Tools/MakeAppTools.py +++ b/src/Tools/MakeAppTools.py @@ -1,7 +1,9 @@ -import os, sys, re,FCFileTools +import os, sys, re, FCFileTools + verbose = 0 dcount = fcount = 0 + def replaceTemplate(dirName, oldName, newName): """ modify contents from dirName and below, replace oldName by newName @@ -11,23 +13,23 @@ def replaceTemplate(dirName, oldName, newName): if not os.path.isdir(pathName): try: print(pathName) - origFile = open(pathName) # open file - lines = origFile.readlines() # read the file... - origFile.close() # ... and close it - output = open(pathName,"w") # open the file again + origFile = open(pathName) # open file + lines = origFile.readlines() # read the file... + origFile.close() # ... and close it + output = open(pathName, "w") # open the file again for line in lines: - if (line.find(oldName) != -1): # search for 'oldName' and replace it + if line.find(oldName) != -1: # search for 'oldName' and replace it line = line.replace(oldName, newName) - output.write(line) # write the modified line back - output.close # close the file + output.write(line) # write the modified line back + output.close # close the file except Exception: - print('Error modifying ', pathName, ' -- skipped') + print("Error modifying ", pathName, " -- skipped") print(sys.exc_info()[0], sys.exc_info()[1]) else: try: replaceTemplate(pathName, oldName, newName) except Exception: - print('Error changing to directory ', pathName, ' -- skipped') + print("Error changing to directory ", pathName, " -- skipped") print(sys.exc_info()[0], sys.exc_info()[1]) @@ -36,42 +38,46 @@ def copyTemplate(dirFrom, dirTo, oldName, newName, MatchFile, MatchDir): copy contents of dirFrom and below to dirTo """ global dcount, fcount - for file in os.listdir(dirFrom): # for files/dirs here + for file in os.listdir(dirFrom): # for files/dirs here print(file) pathFrom = os.path.join(dirFrom, file) - pathTo = os.path.join(dirTo, file) # extend both paths - if (pathTo.find(oldName) != -1): - pathTo = pathTo.replace(oldName, newName) # rename file if 'oldName' is found - if not os.path.isdir(pathFrom): # copy simple files + pathTo = os.path.join(dirTo, file) # extend both paths + if pathTo.find(oldName) != -1: + pathTo = pathTo.replace(oldName, newName) # rename file if 'oldName' is found + if not os.path.isdir(pathFrom): # copy simple files hit = 0 for matchpat in MatchFile: - if(re.match(matchpat,file)): + if re.match(matchpat, file): hit = 1 break if hit: - print('Ignore file '+file) + print("Ignore file " + file) continue try: - if verbose > 1: print('copying ', pathFrom, ' to ', pathTo) + if verbose > 1: + print("copying ", pathFrom, " to ", pathTo) FCFileTools.cpfile(pathFrom, pathTo) - fcount = fcount+1 + fcount = fcount + 1 except Exception: - print('Error copying ', pathFrom, ' to ', pathTo, ' -- skipped') + print("Error copying ", pathFrom, " to ", pathTo, " -- skipped") print(sys.exc_info()[0], sys.exc_info()[1]) else: hit = 0 for matchpat in MatchDir: - if(re.match(matchpat,file)): + if re.match(matchpat, file): hit = 1 break if hit: - print('Ignore directory '+file) + print("Ignore directory " + file) continue - if verbose: print('copying dir ', pathFrom, ' to ', pathTo) + if verbose: + print("copying dir ", pathFrom, " to ", pathTo) try: - os.mkdir(pathTo) # make new subdir - copyTemplate(pathFrom, pathTo, oldName, newName, MatchFile, MatchDir) # recurse into subdirs - dcount = dcount+1 + os.mkdir(pathTo) # make new subdir + copyTemplate( + pathFrom, pathTo, oldName, newName, MatchFile, MatchDir + ) # recurse into subdirs + dcount = dcount + 1 except Exception: - print('Error creating ', pathTo, ' -- skipped') + print("Error creating ", pathTo, " -- skipped") print(sys.exc_info()[0], sys.exc_info()[1]) diff --git a/src/Tools/MakeMacBundleRelocatable.py b/src/Tools/MakeMacBundleRelocatable.py index 37eb987e79..2d013bfedd 100755 --- a/src/Tools/MakeMacBundleRelocatable.py +++ b/src/Tools/MakeMacBundleRelocatable.py @@ -13,8 +13,11 @@ import logging # * We need to be able to add multiple rpaths in some libraries. # Assume any libraries in these paths don't need to be bundled -systemPaths = [ "/System/", "/usr/lib/", - "/Library/Frameworks/3DconnexionClient.framework/" ] +systemPaths = [ + "/System/", + "/usr/lib/", + "/Library/Frameworks/3DconnexionClient.framework/", +] # If a library is in these paths, but not systemPaths, a warning will be # issued and it will NOT be bundled. Generally, libraries installed by @@ -22,13 +25,16 @@ systemPaths = [ "/System/", "/usr/lib/", # that libraries found there aren't meant to be bundled. warnPaths = ["/Library/Frameworks/"] + class LibraryNotFound(Exception): pass + class Node: """ self.path should be an absolute path to self.name """ + def __init__(self, name, path="", children=None): self.name = name self.path = path @@ -36,16 +42,21 @@ class Node: children = list() self.children = children self._marked = False + def __eq__(self, other): if not isinstance(other, Node): return False return self.name == other.name + def __ne__(self, other): return not self.__eq__(other) + def __hash__(self): return hash(self.name) + def __str__(self): - return self.name + " path: " + self.path + " num children: " + str(len(self.children)) + return self.name + " path: " + self.path + " num children: " + str(len(self.children)) + class DepsGraph: graph = {} @@ -62,7 +73,7 @@ class DepsGraph: return None def visit(self, operation, op_args=[]): - """" + """ " Perform a depth first visit of the graph, calling operation on each node. """ @@ -84,15 +95,17 @@ class DepsGraph: def is_macho(path): - return b'Mach-O' in check_output(['file', path]) + return b"Mach-O" in check_output(["file", path]) -def get_token(txt, delimiter=' (', first=True): + +def get_token(txt, delimiter=" (", first=True): result = txt.decode().split(delimiter) if first: return result[0] else: return result + def is_system_lib(lib): for p in systemPaths: if lib.startswith(p): @@ -104,19 +117,21 @@ def is_system_lib(lib): return True return False + def get_path(name, search_paths): for path in search_paths: if os.path.isfile(os.path.join(path, name)): return path return None + def list_install_names(path_macho): output = check_output(["otool", "-L", path_macho]) lines = output.split(b"\t") libs = [] - #first line is the filename, and if it is a library, the second line - #is the install name of it + # first line is the filename, and if it is a library, the second line + # is the install name of it if path_macho.endswith(os.path.basename(get_token(lines[1]))): lines = lines[2:] else: @@ -128,6 +143,7 @@ def list_install_names(path_macho): libs.append(lib) return libs + def library_paths(install_names, search_paths): paths = [] for name in install_names: @@ -135,13 +151,14 @@ def library_paths(install_names, search_paths): lib_name = os.path.basename(name) if path == "" or name[0] == "@": - #not absolute -- we need to find the path of this lib + # not absolute -- we need to find the path of this lib path = get_path(lib_name, search_paths) paths.append(os.path.join(path, lib_name)) return paths + def create_dep_nodes(install_names, search_paths): """ Return a list of Node objects from the provided install names. @@ -151,13 +168,13 @@ def create_dep_nodes(install_names, search_paths): install_path = os.path.dirname(lib) lib_name = os.path.basename(lib) - #even if install_path is absolute, see if library can be found by - #searching search_paths, so that we have control over what library - #location to use + # even if install_path is absolute, see if library can be found by + # searching search_paths, so that we have control over what library + # location to use path = get_path(lib_name, search_paths) if install_path != "" and lib[0] != "@": - #we have an absolute path install name + # we have an absolute path install name if not path: path = install_path @@ -169,28 +186,30 @@ def create_dep_nodes(install_names, search_paths): return nodes + def paths_at_depth(prefix, paths, depth): filtered = [] for p in paths: - dirs = os.path.join(prefix, p).strip('/').split('/') + dirs = os.path.join(prefix, p).strip("/").split("/") if len(dirs) == depth: filtered.append(p) return filtered + def should_visit(prefix, path_filters, path): - s_path = path.strip('/').split('/') + s_path = path.strip("/").split("/") filters = [] - #we only want to use filters if they have the same parent as path + # we only want to use filters if they have the same parent as path for rel_pf in path_filters: pf = os.path.join(prefix, rel_pf) if os.path.split(pf)[0] == os.path.split(path)[0]: filters.append(pf) if not filters: - #no filter that applies to this path + # no filter that applies to this path return True for pf in filters: - s_filter = pf.strip('/').split('/') + s_filter = pf.strip("/").split("/") length = len(s_filter) matched = 0 for i in range(len(s_path)): @@ -201,28 +220,29 @@ def should_visit(prefix, path_filters, path): return False + def build_deps_graph(graph, bundle_path, dirs_filter=None, search_paths=[]): """ Walk bundle_path and build a graph of the encountered Mach-O binaries and there dependencies """ - #make a local copy since we add to it + # make a local copy since we add to it s_paths = list(search_paths) visited = {} for root, dirs, files in os.walk(bundle_path): if dirs_filter is not None: - dirs[:] = [d for d in dirs if should_visit(bundle_path, dirs_filter, - os.path.join(root, d))] + dirs[:] = [ + d for d in dirs if should_visit(bundle_path, dirs_filter, os.path.join(root, d)) + ] s_paths.insert(0, root) for f in files: fpath = os.path.join(root, f) ext = os.path.splitext(f)[1] - if ( (ext == "" and is_macho(fpath)) or - ext == ".so" or ext == ".dylib" ): + if (ext == "" and is_macho(fpath)) or ext == ".so" or ext == ".dylib": visited[fpath] = False stack = [] @@ -238,10 +258,10 @@ def build_deps_graph(graph, bundle_path, dirs_filter=None, search_paths=[]): graph.add_node(node) try: - deps = create_dep_nodes(list_install_names(k2), s_paths) + deps = create_dep_nodes(list_install_names(k2), s_paths) except Exception: - logging.error("Failed to resolve dependency in " + k2) - raise + logging.error("Failed to resolve dependency in " + k2) + raise for d in deps: if d.name not in node.children: @@ -253,23 +273,26 @@ def build_deps_graph(graph, bundle_path, dirs_filter=None, search_paths=[]): if not visited[dk]: stack.append(dk) + def in_bundle(lib, bundle_path): if lib.startswith(bundle_path): return True return False + def copy_into_bundle(graph, node, bundle_path): if not in_bundle(node.path, bundle_path): source = os.path.join(node.path, node.name) target = os.path.join(bundle_path, "lib", node.name) logging.info("Bundling {}".format(source)) - check_call([ "cp", "-L", source, target ]) + check_call(["cp", "-L", source, target]) node.path = os.path.dirname(target) - #fix permissions - check_call([ "chmod", "a+w", target ]) + # fix permissions + check_call(["chmod", "a+w", target]) + def get_rpaths(library): "Returns a list of rpaths specified within library" @@ -279,7 +302,7 @@ def get_rpaths(library): pathRegex = r"^path (.*) \(offset \d+\)$" expectingRpath = False rpaths = [] - for line in get_token(out, '\n', False): + for line in get_token(out, "\n", False): line = line.strip() if "cmd LC_RPATH" in line: @@ -294,45 +317,52 @@ def get_rpaths(library): return rpaths + def add_rpaths(graph, node, bundle_path): lib = os.path.join(node.path, node.name) if in_bundle(lib, bundle_path): - logging.debug(lib) + logging.debug(lib) - # Remove existing rpaths that could take precedence - for rpath in get_rpaths(lib): - logging.debug(" - rpath: " + rpath) - check_call(["install_name_tool", "-delete_rpath", rpath, lib]) + # Remove existing rpaths that could take precedence + for rpath in get_rpaths(lib): + logging.debug(" - rpath: " + rpath) + check_call(["install_name_tool", "-delete_rpath", rpath, lib]) - if node.children: - install_names = list_install_names(lib) - rpaths = [] + if node.children: + install_names = list_install_names(lib) + rpaths = [] + for install_name in install_names: + name = os.path.basename(install_name) + # change install names to use rpaths + logging.debug(" ~ rpath: " + name + " => @rpath/" + name) + check_call( + [ + "install_name_tool", + "-change", + install_name, + "@rpath/" + name, + lib, + ] + ) - for install_name in install_names: - name = os.path.basename(install_name) - #change install names to use rpaths - logging.debug(" ~ rpath: " + name + " => @rpath/" + name) - check_call([ "install_name_tool", "-change", - install_name, "@rpath/" + name, lib ]) + dep_node = node.children[node.children.index(name)] + rel_path = os.path.relpath(graph.get_node(dep_node).path, node.path) + rpath = "" + if rel_path == ".": + rpath = "@loader_path/" + else: + rpath = "@loader_path/" + rel_path + "/" + if rpath not in rpaths: + rpaths.append(rpath) - dep_node = node.children[node.children.index(name)] - rel_path = os.path.relpath(graph.get_node(dep_node).path, - node.path) - rpath = "" - if rel_path == ".": - rpath = "@loader_path/" - else: - rpath = "@loader_path/" + rel_path + "/" - if rpath not in rpaths: - rpaths.append(rpath) + for rpath in rpaths: + # Ensure that lib has rpath set + if not rpath in get_rpaths(lib): + logging.debug(" + rpath: " + rpath) + check_call(["install_name_tool", "-add_rpath", rpath, lib]) - for rpath in rpaths: - # Ensure that lib has rpath set - if not rpath in get_rpaths(lib): - logging.debug(" + rpath: " + rpath) - check_call([ "install_name_tool", "-add_rpath", rpath, lib ]) def change_libid(graph, node, bundle_path): lib = os.path.join(node.path, node.name) @@ -340,19 +370,22 @@ def change_libid(graph, node, bundle_path): logging.debug(lib) if in_bundle(lib, bundle_path): - logging.debug(" ~ id: " + node.name) - try: - check_call([ "install_name_tool", "-id", node.name, lib ]) - except Exception: - logging.warning("Failed to change bundle id {} in lib {}".format(node.name, lib)) + logging.debug(" ~ id: " + node.name) + try: + check_call(["install_name_tool", "-id", node.name, lib]) + except Exception: + logging.warning("Failed to change bundle id {} in lib {}".format(node.name, lib)) + def print_child(graph, node, path): logging.debug(" >" + str(node)) + def print_node(graph, node, path): logging.debug(node) graph.visit(print_child, [node]) + def main(): if len(sys.argv) < 2: print("Usage " + sys.argv[0] + " path [additional search paths]") @@ -364,15 +397,16 @@ def main(): dir_filter = ["MacOS", "lib", "Mod"] search_paths = [bundle_path + "/lib"] + sys.argv[2:] - #change to level to logging.DEBUG for diagnostic messages - logging.basicConfig(stream=sys.stdout, level=logging.INFO, - format="-- %(levelname)s: %(message)s" ) + # change to level to logging.DEBUG for diagnostic messages + logging.basicConfig( + stream=sys.stdout, level=logging.INFO, format="-- %(levelname)s: %(message)s" + ) logging.info("Analyzing bundle dependencies...") build_deps_graph(graph, bundle_path, dir_filter, search_paths) if logging.getLogger().getEffectiveLevel() == logging.DEBUG: - graph.visit(print_node, [bundle_path]) + graph.visit(print_node, [bundle_path]) logging.info("Copying external dependencies to bundle...") graph.visit(copy_into_bundle, [bundle_path]) @@ -385,5 +419,6 @@ def main(): logging.info("Done.") + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/src/Tools/MakeNewBuildNbr.py b/src/Tools/MakeNewBuildNbr.py index e07914926f..6a8a4ed820 100644 --- a/src/Tools/MakeNewBuildNbr.py +++ b/src/Tools/MakeNewBuildNbr.py @@ -1,25 +1,25 @@ -#*************************************************************************** -#* Copyright (c) 2002 Jürgen Riegel * -#* * -#* This file is part of the FreeCAD CAx development system. * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Library General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* FreeCAD is distributed in the hope that it will be useful, * -#* but WITHOUT ANY WARRANTY; without even the implied warranty of * -#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -#* GNU Library General Public License for more details. * -#* * -#* You should have received a copy of the GNU Library General Public * -#* License along with FreeCAD; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#***************************************************************************/ +# *************************************************************************** +# * Copyright (c) 2002 Jürgen Riegel * +# * * +# * This file is part of the FreeCAD CAx development system. * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Library General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * FreeCAD is distributed in the hope that it will be useful, * +# * but WITHOUT ANY WARRANTY; without even the implied warranty of * +# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +# * GNU Library General Public License for more details. * +# * * +# * You should have received a copy of the GNU Library General Public * +# * License along with FreeCAD; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# ***************************************************************************/ # FreeCAD MakeNewBuildNbr script # @@ -28,14 +28,32 @@ import time # reading the last Version information -[FCVersionMajor,FCVersionMinor,FCVersionBuild,FCVersionDisDa,dummy] = open("../Version.h",'r').readlines() +[FCVersionMajor, FCVersionMinor, FCVersionBuild, FCVersionDisDa, dummy] = open( + "../Version.h", "r" +).readlines() # increasing build number -BuildNumber = int(FCVersionBuild[23:-1]) +1 +BuildNumber = int(FCVersionBuild[23:-1]) + 1 # writing new Version.h File -open("../Version.h",'w').writelines([FCVersionMajor,FCVersionMinor,FCVersionBuild[:23]+str(BuildNumber)+'\n',FCVersionDisDa[:23]+ '"'+time.asctime()+'"']) +open("../Version.h", "w").writelines( + [ + FCVersionMajor, + FCVersionMinor, + FCVersionBuild[:23] + str(BuildNumber) + "\n", + FCVersionDisDa[:23] + '"' + time.asctime() + '"', + ] +) # writing the ChangeLog.txt -open("../ChangeLog.txt",'a').write("\nVersion: V"+FCVersionMajor[23:-1]+"."+FCVersionMinor[23:-1]+"B"+str(BuildNumber)+" Date: "+time.asctime()+' +++++++++++++++++++++++++++++++\n') - +open("../ChangeLog.txt", "a").write( + "\nVersion: V" + + FCVersionMajor[23:-1] + + "." + + FCVersionMinor[23:-1] + + "B" + + str(BuildNumber) + + " Date: " + + time.asctime() + + " +++++++++++++++++++++++++++++++\n" +) diff --git a/src/Tools/MemoryLeaks.py b/src/Tools/MemoryLeaks.py index 441d0f8843..c5417f9627 100755 --- a/src/Tools/MemoryLeaks.py +++ b/src/Tools/MemoryLeaks.py @@ -3,29 +3,28 @@ # (c) 2006 Werner Mayer LGPL # FreeCAD report memory leaks script to get provide the log file of Visual Studio in more readable file. -import string,re +import string, re # Open the memory leak file file = open("MemLog.txt") lines = file.readlines() file.close() -d=dict() -l=list() +d = dict() +l = list() for line in lines: - r=re.search("\\(#\\s*\\d+\\)",line) + r = re.search("\\(#\\s*\\d+\\)", line) if r is not None: - s=line[r.start():r.end()] - t=re.search("^Leak",line) + s = line[r.start() : r.end()] + t = re.search("^Leak", line) if t is not None: - m=d[s] + m = d[s] l.append(m) else: - d[s]=line + d[s] = line -file = open("MemLog_leaks.txt","w") +file = open("MemLog_leaks.txt", "w") for line in l: - line = string.replace(line,'Alloc','Leak') + line = string.replace(line, "Alloc", "Leak") file.write(line) file.close() - diff --git a/src/Tools/PythonToCPP.py b/src/Tools/PythonToCPP.py index 0b60a9325d..06774548e7 100644 --- a/src/Tools/PythonToCPP.py +++ b/src/Tools/PythonToCPP.py @@ -2,28 +2,28 @@ # -*- coding: utf-8 -*- # (c) 2004 Werner Mayer LGPL -import os,sys +import os, sys -#os.chdir("E:\\Develop\\FreeCADWin\\scripts") +# os.chdir("E:\\Develop\\FreeCADWin\\scripts") try: - file = open(sys.argv[1],encoding="utf-8") + file = open(sys.argv[1], encoding="utf-8") except TypeError: file = open(sys.argv[1]) -if(len(sys.argv) > 4): +if len(sys.argv) > 4: sys.stderr.write("Wrong Parameter\n Usage:\n PythonToCPP Infile.py [Outfile][Variable]\n") -if(len(sys.argv) > 2): +if len(sys.argv) > 2: try: - out = open(sys.argv[2],"w",encoding="utf-8"); + out = open(sys.argv[2], "w", encoding="utf-8") except TypeError: - out = open(sys.argv[2],"w"); + out = open(sys.argv[2], "w") else: out = sys.stdout -if(len(sys.argv) > 3): +if len(sys.argv) > 3: identifier = sys.argv[3] else: identifier = os.path.basename(sys.argv[1]) @@ -38,16 +38,12 @@ for line in lines: # remove new line line2 = line.rstrip() # replace special chars - line2 = line2.replace('\\','\\\\') - line2 = line2.replace('\"','\\\"') - line2 = line2.replace("\'","\\\'") - + line2 = line2.replace("\\", "\\\\") + line2 = line2.replace('"', '\\"') + line2 = line2.replace("'", "\\'") # output - #out.write(line) - out.write( '\"' + line2 + '\\n\"\n') - -out.write(";\n\n\n"); - - + # out.write(line) + out.write('"' + line2 + '\\n"\n') +out.write(";\n\n\n") diff --git a/src/Tools/RegExp/main.cpp b/src/Tools/RegExp/main.cpp index 456311515f..3c7a5e81ed 100644 --- a/src/Tools/RegExp/main.cpp +++ b/src/Tools/RegExp/main.cpp @@ -25,7 +25,7 @@ #include -int main( int argc, char** argv ) +int main(int argc, char** argv) { QApplication app(argc, argv); @@ -35,4 +35,3 @@ int main( int argc, char** argv ) return 0; } - diff --git a/src/Tools/RegExp/regexpdialog.cpp b/src/Tools/RegExp/regexpdialog.cpp index 3ccbb5c22f..50619d856d 100644 --- a/src/Tools/RegExp/regexpdialog.cpp +++ b/src/Tools/RegExp/regexpdialog.cpp @@ -31,7 +31,8 @@ #include RegExpDialog::RegExpDialog(QWidget* parent) - : QDialog(parent), ui(new Ui_RegExpDialog()) + : QDialog(parent), + ui(new Ui_RegExpDialog()) { ui->setupUi(this); rxhilighter = new RegExpSyntaxHighlighter(ui->textEdit1); @@ -39,22 +40,17 @@ RegExpDialog::RegExpDialog(QWidget* parent) validator = new QRegularExpressionValidator(this); ui->lineEdit->setValidator(validator); - connect(ui->lineEditRegExp, &QLineEdit::textChanged, - this, &RegExpDialog::performRegExp); - connect(ui->caseInsensitiveOption, &QCheckBox::toggled, - this, &RegExpDialog::performRegExp); - connect(ui->invertedGreedinessOption, &QCheckBox::toggled, - this, &RegExpDialog::performRegExp); - connect(ui->dotMatchesEverythingOption, &QCheckBox::toggled, - this, &RegExpDialog::performRegExp); - connect(ui->multilineOption, &QCheckBox::toggled, - this, &RegExpDialog::performRegExp); - connect(ui->extendedPatternSyntaxOption, &QCheckBox::toggled, - this, &RegExpDialog::performRegExp); - connect(ui->dontCaptureOption, &QCheckBox::toggled, - this, &RegExpDialog::performRegExp); - connect(ui->useUnicodePropertiesOption, &QCheckBox::toggled, - this, &RegExpDialog::performRegExp); + connect(ui->lineEditRegExp, &QLineEdit::textChanged, this, &RegExpDialog::performRegExp); + connect(ui->caseInsensitiveOption, &QCheckBox::toggled, this, &RegExpDialog::performRegExp); + connect(ui->invertedGreedinessOption, &QCheckBox::toggled, this, &RegExpDialog::performRegExp); + connect( + ui->dotMatchesEverythingOption, &QCheckBox::toggled, this, &RegExpDialog::performRegExp); + connect(ui->multilineOption, &QCheckBox::toggled, this, &RegExpDialog::performRegExp); + connect( + ui->extendedPatternSyntaxOption, &QCheckBox::toggled, this, &RegExpDialog::performRegExp); + connect(ui->dontCaptureOption, &QCheckBox::toggled, this, &RegExpDialog::performRegExp); + connect( + ui->useUnicodePropertiesOption, &QCheckBox::toggled, this, &RegExpDialog::performRegExp); } RegExpDialog::~RegExpDialog() @@ -105,7 +101,7 @@ void RegExpDialog::performRegExp() ui->textLabel4->setText(rx.errorString()); if (!rx.isValid()) { rxhilighter->resethighlight(); - return; // invalid expression + return;// invalid expression } rxhilighter->highlightMatchedText(rx); @@ -120,16 +116,14 @@ void RegExpDialog::about() // ------------------------------------------------------------- -RegExpSyntaxHighlighter::RegExpSyntaxHighlighter (QTextEdit * textEdit) - : QSyntaxHighlighter(textEdit) -{ -} +RegExpSyntaxHighlighter::RegExpSyntaxHighlighter(QTextEdit* textEdit) + : QSyntaxHighlighter(textEdit) +{} RegExpSyntaxHighlighter::~RegExpSyntaxHighlighter() -{ -} +{} -void RegExpSyntaxHighlighter::highlightBlock (const QString & text) +void RegExpSyntaxHighlighter::highlightBlock(const QString& text) { QTextCharFormat regFormat; regFormat.setForeground(Qt::black); @@ -137,7 +131,7 @@ void RegExpSyntaxHighlighter::highlightBlock (const QString & text) setFormat(0, text.length(), regFormat); if (regexp.pattern().isEmpty()) - return; // empty regular expression + return;// empty regular expression int pos = 0; int last = -1; diff --git a/src/Tools/RegExp/regexpdialog.h b/src/Tools/RegExp/regexpdialog.h index 6ba5fe8e57..b3fdbd3385 100644 --- a/src/Tools/RegExp/regexpdialog.h +++ b/src/Tools/RegExp/regexpdialog.h @@ -32,7 +32,7 @@ class QRegularExpressionValidator; class RegExpSyntaxHighlighter; class Ui_RegExpDialog; -class RegExpDialog : public QDialog +class RegExpDialog: public QDialog { Q_OBJECT public: @@ -52,18 +52,18 @@ private: // ------------------------------------------------------------- -class RegExpSyntaxHighlighter : public QSyntaxHighlighter +class RegExpSyntaxHighlighter: public QSyntaxHighlighter { public: - RegExpSyntaxHighlighter (QTextEdit * textEdit); + RegExpSyntaxHighlighter(QTextEdit* textEdit); ~RegExpSyntaxHighlighter(); - void highlightBlock (const QString & text); - void highlightMatchedText( const QRegularExpression& ); + void highlightBlock(const QString& text); + void highlightMatchedText(const QRegularExpression&); void resethighlight(); private: QRegularExpression regexp; }; -#endif // REG_EXP_DIALOG_H +#endif// REG_EXP_DIALOG_H diff --git a/src/Tools/SubWCRev.py b/src/Tools/SubWCRev.py index 388a4376f9..1f3f0a4363 100644 --- a/src/Tools/SubWCRev.py +++ b/src/Tools/SubWCRev.py @@ -9,10 +9,11 @@ # 2012/02/01: The script was extended to support git # 2011/02/05: The script was extended to support also Bazaar -import os,sys,re,time,getopt +import os, sys, re, time, getopt import xml.sax import xml.sax.handler import xml.sax.xmlreader + try: from StringIO import StringIO except ImportError: @@ -51,6 +52,7 @@ class SvnHandler(xml.sax.handler.ContentHandler): self.mapping["Date"] = self.buffer self.buffer = "" + class VersionControl: def __init__(self): self.rev = "" @@ -64,18 +66,19 @@ class VersionControl: print("") def writeVersion(self, lines): - content=[] + content = [] for line in lines: - line = line.replace('$WCREV$',self.rev) - line = line.replace('$WCDATE$',self.date) - line = line.replace('$WCURL$',self.url) + line = line.replace("$WCREV$", self.rev) + line = line.replace("$WCDATE$", self.date) + line = line.replace("$WCURL$", self.url) content.append(line) return content + class UnknownControl(VersionControl): def extractInfo(self, srcdir, bindir): # Do not overwrite existing file with almost useless information - if os.path.exists(bindir+"/src/Build/Version.h.out"): + if os.path.exists(bindir + "/src/Build/Version.h.out"): return False self.rev = "Unknown" self.date = "Unknown" @@ -85,41 +88,50 @@ class UnknownControl(VersionControl): def printInfo(self): print("Unknown version control") + class DebianChangelog(VersionControl): def extractInfo(self, srcdir, bindir): # Do not overwrite existing file with almost useless information - if os.path.exists(bindir+"/src/Build/Version.h.out"): + if os.path.exists(bindir + "/src/Build/Version.h.out"): return False try: - f = open(srcdir+"/debian/changelog") + f = open(srcdir + "/debian/changelog") except Exception: return False c = f.readline() f.close() - r=re.search("bzr(\\d+)",c) + r = re.search("bzr(\\d+)", c) if r is not None: self.rev = r.groups()[0] + " (Launchpad)" t = time.localtime() - self.date = ("%d/%02d/%02d %02d:%02d:%02d") % (t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec) + self.date = ("%d/%02d/%02d %02d:%02d:%02d") % ( + t.tm_year, + t.tm_mon, + t.tm_mday, + t.tm_hour, + t.tm_min, + t.tm_sec, + ) self.url = "https://code.launchpad.net/~vcs-imports/freecad/trunk" return True def printInfo(self): print("debian/changelog") + class BazaarControl(VersionControl): def extractInfo(self, srcdir, bindir): - info=os.popen("bzr log -l 1 %s" % (srcdir)).read() + info = os.popen("bzr log -l 1 %s" % (srcdir)).read() if len(info) == 0: return False - lines=info.split("\n") + lines = info.split("\n") for i in lines: r = re.match("^revno: (\\d+)$", i) if r is not None: self.rev = r.groups()[0] continue - r=re.match("^timestamp: (\\w+ \\d+-\\d+-\\d+ \\d+:\\d+:\\d+)",i) + r = re.match("^timestamp: (\\w+ \\d+-\\d+-\\d+ \\d+:\\d+:\\d+)", i) if r is not None: self.date = r.groups()[0] continue @@ -128,13 +140,14 @@ class BazaarControl(VersionControl): def printInfo(self): print("bazaar") + class DebianGitHub(VersionControl): - #https://gist.github.com/0penBrain/7be59a48aba778c955d992aa69e524c5 - #https://gist.github.com/yershalom/a7c08f9441d1aadb13777bce4c7cdc3b - #https://github.community/t5/GitHub-API-Development-and/How-to-get-all-branches-which-contain-a-commit-from-SHA-using/td-p/25006 + # https://gist.github.com/0penBrain/7be59a48aba778c955d992aa69e524c5 + # https://gist.github.com/yershalom/a7c08f9441d1aadb13777bce4c7cdc3b + # https://github.community/t5/GitHub-API-Development-and/How-to-get-all-branches-which-contain-a-commit-from-SHA-using/td-p/25006 def extractInfo(self, srcdir, bindir): try: - f = open(srcdir+"/debian/git-build-recipe.manifest") + f = open(srcdir + "/debian/git-build-recipe.manifest") except Exception: return False @@ -146,30 +159,46 @@ class DebianGitHub(VersionControl): base_url = "https://api.github.com" owner = "FreeCAD" repo = "FreeCAD" - sha = commit[commit.rfind(':') + 1 : -1] + sha = commit[commit.rfind(":") + 1 : -1] self.hash = sha try: import requests - request_url = "{}/repos/{}/{}/commits?per_page=1&sha={}".format(base_url, owner, repo, sha) + + request_url = "{}/repos/{}/{}/commits?per_page=1&sha={}".format( + base_url, owner, repo, sha + ) commit_req = requests.get(request_url) if not commit_req.ok: return False - commit_date = commit_req.headers.get('last-modified') + commit_date = commit_req.headers.get("last-modified") except Exception: # if connection fails then use the date of the file git-build-recipe.manifest - commit_date = recipe[recipe.rfind('~') + 1 : -1] - + commit_date = recipe[recipe.rfind("~") + 1 : -1] try: # Try to convert into the same format as GitControl t = time.strptime(commit_date, "%a, %d %b %Y %H:%M:%S GMT") - commit_date = ("%d/%02d/%02d %02d:%02d:%02d") % (t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec) + commit_date = ("%d/%02d/%02d %02d:%02d:%02d") % ( + t.tm_year, + t.tm_mon, + t.tm_mday, + t.tm_hour, + t.tm_min, + t.tm_sec, + ) except Exception: t = time.strptime(commit_date, "%Y%m%d%H%M") - commit_date = ("%d/%02d/%02d %02d:%02d:%02d") % (t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec) + commit_date = ("%d/%02d/%02d %02d:%02d:%02d") % ( + t.tm_year, + t.tm_mon, + t.tm_mday, + t.tm_hour, + t.tm_min, + t.tm_sec, + ) self.date = commit_date self.branch = "unknown" @@ -181,7 +210,7 @@ class DebianGitHub(VersionControl): branch_req = requests.get(branch_url) if branch_req.ok: html = branch_req.text - pattern = "
  • 0: self.url = sorted(urls)[-1][1] else: self.url = "Unknown" - def revisionNumber(self, srcdir,origin=None): + def revisionNumber(self, srcdir, origin=None): """sets the revision number for master and release branches all commits are counted for other branches. The version number is split in to two parts: The first number reflects the number of commits in common with the blessed master repository. The second part (separated by " +") reflects the number of commits that are different from the master repository""" - referencecommit="7d8e53aaab17961d85c5009de34f69f2af084e8b" - referencerevision=14555 + referencecommit = "7d8e53aaab17961d85c5009de34f69f2af084e8b" + referencerevision = 14555 result = None - countallfh=os.popen("git rev-list --count %s..HEAD" % \ - referencecommit) - countallstr=countallfh.read().strip() - if countallfh.close() is not None: #reference commit not present - self.rev = '%04d (Git shallow)' % referencerevision + countallfh = os.popen("git rev-list --count %s..HEAD" % referencecommit) + countallstr = countallfh.read().strip() + if countallfh.close() is not None: # reference commit not present + self.rev = "%04d (Git shallow)" % referencerevision return else: countall = int(countallstr) - if origin is not None and self.branch.lower() != 'master' and \ - 'release' not in self.branch.lower(): - mbfh=os.popen("git merge-base %s/master HEAD" % origin) + if ( + origin is not None + and self.branch.lower() != "master" + and "release" not in self.branch.lower() + ): + mbfh = os.popen("git merge-base %s/master HEAD" % origin) mergebase = mbfh.read().strip() - if mbfh.close() is None: # exit code == 0 + if mbfh.close() is None: # exit code == 0 try: - countmergebase=int(os.popen("git rev-list --count %s..%s"\ - % (referencecommit,mergebase)).read().strip()) + countmergebase = int( + os.popen("git rev-list --count %s..%s" % (referencecommit, mergebase)) + .read() + .strip() + ) if countall > countmergebase: - result = '%04d +%d (Git)' % (countmergebase +\ - referencerevision,countall-countmergebase) + result = "%04d +%d (Git)" % ( + countmergebase + referencerevision, + countall - countmergebase, + ) except ValueError: pass - self.rev = result or ('%04d (Git)' % (countall+referencerevision)) + self.rev = result or ("%04d (Git)" % (countall + referencerevision)) def namebranchbyparents(self): """name multiple branches in case that the last commit was a merge @@ -294,68 +338,68 @@ class GitControl(VersionControl): if the describe does not return a ref name (the hash is added) if one parent is the master and the second one has no ref name, one branch was merged.""" - parents=os.popen("git log -n1 --pretty=%P").read()\ - .strip().split(' ') - if len(parents) >= 2: #merge commit - parentrefs=[] - names=[] - hasnames=0 + parents = os.popen("git log -n1 --pretty=%P").read().strip().split(" ") + if len(parents) >= 2: # merge commit + parentrefs = [] + names = [] + hasnames = 0 for p in parents: - refs=os.popen("git show -s --pretty=%%d %s" % p).read()\ - .strip(" ()\n").split(', ') - if refs[0] != '': #has a ref name + refs = os.popen("git show -s --pretty=%%d %s" % p).read().strip(" ()\n").split(", ") + if refs[0] != "": # has a ref name parentrefs.append(refs) names.append(refs[-1]) hasnames += 1 else: parentrefs.append(p) names.append(p[:7]) - if hasnames >=2: # merging master into dev is not enough - self.branch=','.join(names) + if hasnames >= 2: # merging master into dev is not enough + self.branch = ",".join(names) def extractInfo(self, srcdir, bindir): - self.hash=os.popen("git log -1 --pretty=format:%H").read().strip() + self.hash = os.popen("git log -1 --pretty=format:%H").read().strip() if self.hash == "": - return False # not a git repo + return False # not a git repo # date/time import time - info=os.popen("git log -1 --date=raw --pretty=format:%cd").read() + + info = os.popen("git log -1 --date=raw --pretty=format:%cd").read() # commit time is more meaningful than author time # use UTC - self.date = time.strftime("%Y/%m/%d %H:%M:%S",time.gmtime(\ - float(info.strip().split(' ',1)[0]))) - for self.branch in os.popen("git branch --no-color").read().split('\n'): - if re.match( "\*", self.branch ) is not None: + self.date = time.strftime( + "%Y/%m/%d %H:%M:%S", time.gmtime(float(info.strip().split(" ", 1)[0])) + ) + for self.branch in os.popen("git branch --no-color").read().split("\n"): + if re.match("\*", self.branch) is not None: break - self.branch=self.branch[2:] - self.getremotes() #setup self.remotes and branchlst + self.branch = self.branch[2:] + self.getremotes() # setup self.remotes and branchlst self.geturl() - origin = None #remote for the blessed master - for fetchurl in ("git@github.com:FreeCAD/FreeCAD.git",\ - "https://github.com/FreeCAD/FreeCAD.git"): - for key,url in self.remotes.items(): + origin = None # remote for the blessed master + for fetchurl in ( + "git@github.com:FreeCAD/FreeCAD.git", + "https://github.com/FreeCAD/FreeCAD.git", + ): + for key, url in self.remotes.items(): if fetchurl in url: origin = key break if origin is not None: break - self.revisionNumber(srcdir,origin) - if self.branch.lower() != 'master' and \ - 'release' not in self.branch.lower(): + self.revisionNumber(srcdir, origin) + if self.branch.lower() != "master" and "release" not in self.branch.lower(): self.namebranchbyparents() - if self.branch == '(no branch)': #check for remote branches + if self.branch == "(no branch)": # check for remote branches if len(self.branchlst) >= 2: self.branch = self.branchlst[1] - else: # guess - self.branch = '(%s)' % \ - os.popen("git describe --all --dirty").read().strip() - #if the branch name contained any slashes but was not a remote - #there might be no result by now. Hence we assume origin + else: # guess + self.branch = "(%s)" % os.popen("git describe --all --dirty").read().strip() + # if the branch name contained any slashes but was not a remote + # there might be no result by now. Hence we assume origin if self.url == "Unknown": for i in info: - r = re.match("origin\\W+(\\S+)",i) + r = re.match("origin\\W+(\\S+)", i) if r is not None: self.url = r.groups()[0] break @@ -366,11 +410,12 @@ class GitControl(VersionControl): def writeVersion(self, lines): content = VersionControl.writeVersion(self, lines) - content.append('// Git relevant stuff\n') + content.append("// Git relevant stuff\n") content.append('#define FCRepositoryHash "%s"\n' % (self.hash)) content.append('#define FCRepositoryBranch "%s"\n' % (self.branch)) return content + class MercurialControl(VersionControl): def extractInfo(self, srcdir, bindir): return False @@ -378,57 +423,68 @@ class MercurialControl(VersionControl): def printInfo(self): print("mercurial") + class Subversion(VersionControl): def extractInfo(self, srcdir, bindir): - parser=xml.sax.make_parser() - handler=SvnHandler() + parser = xml.sax.make_parser() + handler = SvnHandler() parser.setContentHandler(handler) - #Create an XML stream with the required information and read in with a SAX parser - Ver=os.popen("svnversion %s -n" % (srcdir)).read() - Info=os.popen("svn info %s --xml" % (srcdir)).read() + # Create an XML stream with the required information and read in with a SAX parser + Ver = os.popen("svnversion %s -n" % (srcdir)).read() + Info = os.popen("svn info %s --xml" % (srcdir)).read() try: inpsrc = xml.sax.InputSource() - strio=StringIO.StringIO(Info) + strio = StringIO.StringIO(Info) inpsrc.setByteStream(strio) parser.parse(inpsrc) except Exception: return False - #Information of the Subversion stuff + # Information of the Subversion stuff self.url = handler.mapping["Url"] self.rev = handler.mapping["Rev"] self.date = handler.mapping["Date"] self.date = self.date[:19] - #Same format as SubWCRev does - self.date = self.date.replace('T',' ') - self.date = self.date.replace('-','/') + # Same format as SubWCRev does + self.date = self.date.replace("T", " ") + self.date = self.date.replace("-", "/") - #Date is given as GMT. Now we must convert to local date. - m=time.strptime(self.date,"%Y/%m/%d %H:%M:%S") - #Copy the tuple and set tm_isdst to 0 because it's GMT - l=(m.tm_year,m.tm_mon,m.tm_mday,m.tm_hour,m.tm_min,m.tm_sec,m.tm_wday,m.tm_yday,0) - #Take timezone into account - t=time.mktime(l)-time.timezone - self.date=time.strftime("%Y/%m/%d %H:%M:%S",time.localtime(t)) + # Date is given as GMT. Now we must convert to local date. + m = time.strptime(self.date, "%Y/%m/%d %H:%M:%S") + # Copy the tuple and set tm_isdst to 0 because it's GMT + l = ( + m.tm_year, + m.tm_mon, + m.tm_mday, + m.tm_hour, + m.tm_min, + m.tm_sec, + m.tm_wday, + m.tm_yday, + 0, + ) + # Take timezone into account + t = time.mktime(l) - time.timezone + self.date = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(t)) - #Get the current local date + # Get the current local date self.time = time.strftime("%Y/%m/%d %H:%M:%S") - self.mods = 'Src not modified' - self.mixed = 'Src not mixed' + self.mods = "Src not modified" + self.mixed = "Src not mixed" self.range = self.rev # if version string ends with an 'M' - r=re.search("M$",Ver) + r = re.search("M$", Ver) if r is not None: - self.mods = 'Src modified' + self.mods = "Src modified" # if version string contains a range - r=re.match("^\\d+\\:\\d+",Ver) + r = re.match("^\\d+\\:\\d+", Ver) if r is not None: - self.mixed = 'Src mixed' - self.range = Ver[:r.end()] + self.mixed = "Src mixed" + self.range = Ver[: r.end()] return True def printInfo(self): @@ -436,13 +492,13 @@ class Subversion(VersionControl): def main(): - #if(len(sys.argv) != 2): + # if(len(sys.argv) != 2): # sys.stderr.write("Usage: SubWCRev \"`svn info .. --xml`\"\n") - srcdir="." - bindir="." + srcdir = "." + bindir = "." try: - opts, args = getopt.getopt(sys.argv[1:], "sb:", ["srcdir=","bindir="]) + opts, args = getopt.getopt(sys.argv[1:], "sb:", ["srcdir=", "bindir="]) except getopt.GetoptError: pass @@ -452,7 +508,15 @@ def main(): if o in ("-b", "--bindir"): bindir = a - vcs=[GitControl(), DebianGitHub(), BazaarControl(), Subversion(), MercurialControl(), DebianChangelog(), UnknownControl()] + vcs = [ + GitControl(), + DebianGitHub(), + BazaarControl(), + Subversion(), + MercurialControl(), + DebianChangelog(), + UnknownControl(), + ] for i in vcs: if i.extractInfo(srcdir, bindir): # Open the template file and the version file @@ -460,13 +524,14 @@ def main(): lines = inp.readlines() inp.close() lines = i.writeVersion(lines) - out = open("%s/src/Build/Version.h.out" % (bindir),"w"); + out = open("%s/src/Build/Version.h.out" % (bindir), "w") out.writelines(lines) - out.write('\n') + out.write("\n") out.close() i.printInfo() sys.stdout.write("%s/src/Build/Version.h.out written\n" % (bindir)) break + if __name__ == "__main__": main() diff --git a/src/Tools/ThumbnailProvider/ClassFactory.cpp b/src/Tools/ThumbnailProvider/ClassFactory.cpp index 99c75f6420..4f04bb9ba1 100644 --- a/src/Tools/ThumbnailProvider/ClassFactory.cpp +++ b/src/Tools/ThumbnailProvider/ClassFactory.cpp @@ -22,8 +22,8 @@ #define INITGUID -#include "Common.h" #include "ClassFactory.h" +#include "Common.h" STDAPI CThumbnailProvider_CreateInstance(REFIID riid, void** ppvObject); @@ -41,11 +41,9 @@ CClassFactory::~CClassFactory() } -STDMETHODIMP CClassFactory::QueryInterface(REFIID riid, - void** ppvObject) +STDMETHODIMP CClassFactory::QueryInterface(REFIID riid, void** ppvObject) { - static const QITAB qit[] = - { + static const QITAB qit[] = { QITABENT(CClassFactory, IClassFactory), {0}, }; @@ -69,9 +67,7 @@ STDMETHODIMP_(ULONG) CClassFactory::Release() } -STDMETHODIMP CClassFactory::CreateInstance(IUnknown* punkOuter, - REFIID riid, - void** ppvObject) +STDMETHODIMP CClassFactory::CreateInstance(IUnknown* punkOuter, REFIID riid, void** ppvObject) { if (NULL != punkOuter) return CLASS_E_NOAGGREGATION; @@ -86,9 +82,7 @@ STDMETHODIMP CClassFactory::LockServer(BOOL fLock) } -STDAPI DllGetClassObject(REFCLSID rclsid, - REFIID riid, - void **ppv) +STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void** ppv) { if (NULL == ppv) return E_INVALIDARG; @@ -96,7 +90,7 @@ STDAPI DllGetClassObject(REFCLSID rclsid, if (!IsEqualCLSID(CLSID_SampleThumbnailProvider, rclsid)) return CLASS_E_CLASSNOTAVAILABLE; - CClassFactory *pcf; + CClassFactory* pcf; HRESULT hr; pcf = new CClassFactory(); @@ -106,4 +100,4 @@ STDAPI DllGetClassObject(REFCLSID rclsid, hr = pcf->QueryInterface(riid, ppv); pcf->Release(); return hr; -} \ No newline at end of file +} diff --git a/src/Tools/ThumbnailProvider/ClassFactory.h b/src/Tools/ThumbnailProvider/ClassFactory.h index b6e75c8833..bad0928322 100644 --- a/src/Tools/ThumbnailProvider/ClassFactory.h +++ b/src/Tools/ThumbnailProvider/ClassFactory.h @@ -23,7 +23,7 @@ #pragma once -class CClassFactory : public IClassFactory +class CClassFactory: public IClassFactory { private: LONG m_cRef; diff --git a/src/Tools/ThumbnailProvider/Common.h b/src/Tools/ThumbnailProvider/Common.h index 6df80b8480..ddcb70db8d 100644 --- a/src/Tools/ThumbnailProvider/Common.h +++ b/src/Tools/ThumbnailProvider/Common.h @@ -23,12 +23,12 @@ #pragma once -#include #include #include -#include -#include #include +#include +#include +#include STDAPI_(ULONG) DllAddRef(); STDAPI_(ULONG) DllRelease(); @@ -36,4 +36,5 @@ STDAPI_(HINSTANCE) DllInstance(); // {4BBBEAB5-BE00-41f4-A209-FE838660B9B1} #define szCLSID_SampleThumbnailProvider L"{4BBBEAB5-BE00-41f4-A209-FE838660B9B1}" -DEFINE_GUID(CLSID_SampleThumbnailProvider, 0x4bbbeab5, 0xbe00, 0x41f4, 0xa2, 0x9, 0xfe, 0x83, 0x86, 0x60, 0xb9, 0xb1); +DEFINE_GUID(CLSID_SampleThumbnailProvider, 0x4bbbeab5, 0xbe00, 0x41f4, 0xa2, 0x9, 0xfe, 0x83, 0x86, + 0x60, 0xb9, 0xb1); diff --git a/src/Tools/ThumbnailProvider/FCConfig.h b/src/Tools/ThumbnailProvider/FCConfig.h index 30403c7ba3..98c5f748e8 100644 --- a/src/Tools/ThumbnailProvider/FCConfig.h +++ b/src/Tools/ThumbnailProvider/FCConfig.h @@ -31,66 +31,65 @@ #define FC_CONFIG_H - //************************************************************************** // switching the operating systems // First check for *WIN64* since the *WIN32* are also set on 64-bit platforms #if defined(WIN64) || defined(_WIN64) || defined(__WIN64__) -# ifndef FC_OS_WIN32 -# define FC_OS_WIN32 -# endif -# ifndef FC_OS_WIN64 -# define FC_OS_WIN64 -# endif +#ifndef FC_OS_WIN32 +#define FC_OS_WIN32 +#endif +#ifndef FC_OS_WIN64 +#define FC_OS_WIN64 +#endif #elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) -# ifndef FC_OS_WIN32 -# define FC_OS_WIN32 -# endif -# if defined(__MINGW32__) -# if HAVE_CONFIG_H -# include -# endif // HAVE_CONFIG_H -# endif +#ifndef FC_OS_WIN32 +#define FC_OS_WIN32 +#endif +#if defined(__MINGW32__) +#if HAVE_CONFIG_H +#include +#endif// HAVE_CONFIG_H +#endif #elif defined(__MWERKS__) && defined(__INTEL__) -# ifndef FC_OS_WIN32 -# define FC_OS_WIN32 -# endif +#ifndef FC_OS_WIN32 +#define FC_OS_WIN32 +#endif #elif defined(__APPLE__) -# ifndef FC_OS_MACOSX -# define FC_OS_MACOSX -# endif +#ifndef FC_OS_MACOSX +#define FC_OS_MACOSX +#endif #elif defined(linux) || defined(__linux) || defined(__linux__) || defined(__GLIBC__) -# ifndef FC_OS_LINUX -# define FC_OS_LINUX -# endif +#ifndef FC_OS_LINUX +#define FC_OS_LINUX +#endif #elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__) -# ifndef FC_OS_BSD -# define FC_OS_BSD -# endif +#ifndef FC_OS_BSD +#define FC_OS_BSD +#endif #elif defined(__CYGWIN__) -# ifndef FC_OS_CYGWIN -# define FC_OS_CYGWIN +#ifndef FC_OS_CYGWIN +#define FC_OS_CYGWIN // Avoid conflicts with Inventor -# define HAVE_INT8_T -# define HAVE_UINT8_T -# define HAVE_INT16_T -# define HAVE_UINT16_T -# define HAVE_INT32_T -# define HAVE_UINT32_T -# define HAVE_INT64_T -# define HAVE_UINT64_T -# define HAVE_INTPTR_T -# define HAVE_UINTPTR_T +#define HAVE_INT8_T +#define HAVE_UINT8_T +#define HAVE_INT16_T +#define HAVE_UINT16_T +#define HAVE_INT32_T +#define HAVE_UINT32_T +#define HAVE_INT64_T +#define HAVE_UINT64_T +#define HAVE_INTPTR_T +#define HAVE_UINTPTR_T #endif #else -# error "FreeCAD is not ported to this OS yet. For help see www.freecadweb.org" +#error "FreeCAD is not ported to this OS yet. For help see www.freecadweb.org" #endif #ifdef FC_OS_WIN32 -# define PATHSEP '\\' +#define PATHSEP '\\' #else -# define PATHSEP '/' +#define PATHSEP '/' #endif //************************************************************************** @@ -98,46 +97,46 @@ #if defined(__MINGW32__) // nothing specific here -#elif defined (FC_OS_WIN64) || defined (FC_OS_WIN32) +#elif defined(FC_OS_WIN64) || defined(FC_OS_WIN32) #ifndef HAVE_INT8_T #define HAVE_INT8_T -typedef signed char int8_t; +typedef signed char int8_t; #endif #ifndef HAVE_UINT8_T #define HAVE_UINT8_T -typedef unsigned char uint8_t; +typedef unsigned char uint8_t; #endif #ifndef HAVE_INT16_T #define HAVE_INT16_T -typedef short int16_t; +typedef short int16_t; #endif #ifndef HAVE_UINT16_T #define HAVE_UINT16_T -typedef unsigned short uint16_t; +typedef unsigned short uint16_t; #endif #ifndef HAVE_INT32_T #define HAVE_INT32_T -typedef int int32_t; +typedef int int32_t; #endif #ifndef HAVE_UINT32_T #define HAVE_UINT32_T -typedef unsigned int uint32_t; +typedef unsigned int uint32_t; #endif #ifndef HAVE_INT64_T #define HAVE_INT64_T -typedef __int64 int64_t; +typedef __int64 int64_t; #endif #ifndef HAVE_UINT64_T #define HAVE_UINT64_T -typedef unsigned __int64 uint64_t; +typedef unsigned __int64 uint64_t; #endif #endif @@ -146,29 +145,29 @@ typedef unsigned __int64 uint64_t; //************************************************************************** // Windows import export DLL defines #ifndef BaseExport -# define BaseExport +#define BaseExport #endif #ifndef GuiExport -# define GuiExport +#define GuiExport #endif #ifndef AppExport -# define AppExport +#define AppExport #endif #ifndef DataExport -# define DataExport +#define DataExport #endif //************************************************************************** // point at which warnings of overly long specifiers disabled (needed for VC6) #ifdef _MSC_VER -# pragma warning( disable : 4251 ) -# pragma warning( disable : 4996 ) // suppress deprecated warning for e.g. open() +#pragma warning(disable : 4251) +#pragma warning(disable : 4996)// suppress deprecated warning for e.g. open() #if defined(WIN64) || defined(_WIN64) || defined(__WIN64__) -# pragma warning( disable : 4244 ) -# pragma warning( disable : 4267 ) +#pragma warning(disable : 4244) +#pragma warning(disable : 4267) #endif #endif -#endif //FC_CONFIG_H +#endif// FC_CONFIG_H diff --git a/src/Tools/ThumbnailProvider/Main.cpp b/src/Tools/ThumbnailProvider/Main.cpp index 5612f404c2..48dcc8480e 100644 --- a/src/Tools/ThumbnailProvider/Main.cpp +++ b/src/Tools/ThumbnailProvider/Main.cpp @@ -42,54 +42,52 @@ typedef struct _REGKEY_SUBKEY_AND_VALUE LPCWSTR lpszValue; DWORD dwType; DWORD_PTR dwData; -; + ; } REGKEY_SUBKEY_AND_VALUE; STDAPI CreateRegistryKeys(REGKEY_SUBKEY_AND_VALUE* aKeys, ULONG cKeys); STDAPI DeleteRegistryKeys(REGKEY_DELETEKEY* aKeys, ULONG cKeys); -BOOL APIENTRY DllMain(HINSTANCE hinstDll, - DWORD dwReason, - LPVOID pvReserved) +BOOL APIENTRY DllMain(HINSTANCE hinstDll, DWORD dwReason, LPVOID pvReserved) { - switch (dwReason) - { - case DLL_PROCESS_ATTACH: - g_hinstDll = hinstDll; - break; - } - return TRUE; + switch (dwReason) { + case DLL_PROCESS_ATTACH: + g_hinstDll = hinstDll; + break; + } + return TRUE; } STDAPI_(HINSTANCE) DllInstance() { - return g_hinstDll; + return g_hinstDll; } STDAPI DllCanUnloadNow() { - return g_cRef ? S_FALSE : S_OK; + return g_cRef ? S_FALSE : S_OK; } STDAPI_(ULONG) DllAddRef() { - LONG cRef = InterlockedIncrement(&g_cRef); - return cRef; + LONG cRef = InterlockedIncrement(&g_cRef); + return cRef; } STDAPI_(ULONG) DllRelease() { - LONG cRef = InterlockedDecrement(&g_cRef); - if (0 > cRef) - cRef = 0; - return cRef; + LONG cRef = InterlockedDecrement(&g_cRef); + if (0 > cRef) + cRef = 0; + return cRef; } STDAPI DllRegisterServer() { - // This tells the shell to invalidate the thumbnail cache. This is important because any .recipe files - // viewed before registering this handler would otherwise show cached blank thumbnails. + // This tells the shell to invalidate the thumbnail cache. This is important because any + // .recipe files viewed before registering this handler would otherwise show cached blank + // thumbnails. SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); WCHAR szModule[MAX_PATH]; @@ -97,19 +95,44 @@ STDAPI DllRegisterServer() ZeroMemory(szModule, sizeof(szModule)); GetModuleFileName(g_hinstDll, szModule, ARRAYSIZE(szModule)); - //uncomment the following + // uncomment the following REGKEY_SUBKEY_AND_VALUE keys[] = { - {HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider, NULL, REG_SZ, (DWORD_PTR)L"FCStd Thumbnail Provider"}, + {HKEY_CLASSES_ROOT, + L"CLSID\\" szCLSID_SampleThumbnailProvider, + NULL, + REG_SZ, + (DWORD_PTR)L"FCStd Thumbnail Provider"}, #if 1 - //{HKEY_CLASSES_ROOT, L"CLSID\\DisableProcessIsolation", NULL, REG_DWORD, (DWORD) 1}, - {HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider, L"DisableProcessIsolation", REG_DWORD, (DWORD) 1}, + //{HKEY_CLASSES_ROOT, L"CLSID\\DisableProcessIsolation", NULL, REG_DWORD, (DWORD) 1}, + {HKEY_CLASSES_ROOT, + L"CLSID\\" szCLSID_SampleThumbnailProvider, + L"DisableProcessIsolation", + REG_DWORD, + (DWORD)1}, #endif - {HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider L"\\InprocServer32", NULL, REG_SZ, (DWORD_PTR)szModule}, - {HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider L"\\InprocServer32", L"ThreadingModel", REG_SZ, (DWORD_PTR)L"Apartment"}, - //{HKEY_CLASSES_ROOT, L".FCStd\\shellex", L"Trick only here to create shellex when not existing",REG_DWORD, 1}, - {HKEY_CLASSES_ROOT, L".FCStd\\shellex\\{E357FCCD-A995-4576-B01F-234630154E96}", NULL, REG_SZ, (DWORD_PTR)szCLSID_SampleThumbnailProvider}, - {HKEY_CLASSES_ROOT, L".FCBak\\shellex\\{E357FCCD-A995-4576-B01F-234630154E96}", NULL, REG_SZ, (DWORD_PTR)szCLSID_SampleThumbnailProvider} - }; + {HKEY_CLASSES_ROOT, + L"CLSID\\" szCLSID_SampleThumbnailProvider L"\\InprocServer32", + NULL, + REG_SZ, + (DWORD_PTR)szModule}, + {HKEY_CLASSES_ROOT, + L"CLSID\\" szCLSID_SampleThumbnailProvider L"\\InprocServer32", + L"ThreadingModel", + REG_SZ, + (DWORD_PTR)L"Apartment"}, + //{HKEY_CLASSES_ROOT, L".FCStd\\shellex", L"Trick only here to create shellex when not + // existing",REG_DWORD, 1}, + {HKEY_CLASSES_ROOT, + L".FCStd\\shellex\\{E357FCCD-A995-4576-B01F-234630154E96}", + NULL, + REG_SZ, + (DWORD_PTR)szCLSID_SampleThumbnailProvider}, + {HKEY_CLASSES_ROOT, + L".FCBak\\shellex\\{E357FCCD-A995-4576-B01F-234630154E96}", + NULL, + REG_SZ, + (DWORD_PTR)szCLSID_SampleThumbnailProvider} + }; return CreateRegistryKeys(keys, ARRAYSIZE(keys)); } @@ -127,32 +150,29 @@ STDAPI CreateRegistryKey(REGKEY_SUBKEY_AND_VALUE* pKey) LPVOID pvData = NULL; HRESULT hr = S_OK; - switch(pKey->dwType) - { - case REG_DWORD: - pvData = (LPVOID)(LPDWORD)&pKey->dwData; - cbData = sizeof(DWORD); - break; + switch (pKey->dwType) { + case REG_DWORD: + pvData = (LPVOID)(LPDWORD)&pKey->dwData; + cbData = sizeof(DWORD); + break; - case REG_SZ: - case REG_EXPAND_SZ: - hr = StringCbLength((LPCWSTR)pKey->dwData, STRSAFE_MAX_CCH, &cbData); - if (SUCCEEDED(hr)) - { - pvData = (LPVOID)(LPCWSTR)pKey->dwData; - cbData += sizeof(WCHAR); - } - break; + case REG_SZ: + case REG_EXPAND_SZ: + hr = StringCbLength((LPCWSTR)pKey->dwData, STRSAFE_MAX_CCH, &cbData); + if (SUCCEEDED(hr)) { + pvData = (LPVOID)(LPCWSTR)pKey->dwData; + cbData += sizeof(WCHAR); + } + break; - default: - hr = E_INVALIDARG; + default: + hr = E_INVALIDARG; } - if (SUCCEEDED(hr)) - { - LSTATUS status = SHSetValue(pKey->hKey, pKey->lpszSubKey, pKey->lpszValue, pKey->dwType, pvData, (DWORD)cbData); - if (NOERROR != status) - { + if (SUCCEEDED(hr)) { + LSTATUS status = SHSetValue( + pKey->hKey, pKey->lpszSubKey, pKey->lpszValue, pKey->dwType, pvData, (DWORD)cbData); + if (NOERROR != status) { hr = HRESULT_FROM_WIN32(status); } } @@ -161,16 +181,13 @@ STDAPI CreateRegistryKey(REGKEY_SUBKEY_AND_VALUE* pKey) } - STDAPI CreateRegistryKeys(REGKEY_SUBKEY_AND_VALUE* aKeys, ULONG cKeys) { HRESULT hr = S_OK; - for (ULONG iKey = 0; iKey < cKeys; iKey++) - { + for (ULONG iKey = 0; iKey < cKeys; iKey++) { HRESULT hrTemp = CreateRegistryKey(&aKeys[iKey]); - if (FAILED(hrTemp)) - { + if (FAILED(hrTemp)) { hr = hrTemp; } } @@ -183,13 +200,11 @@ STDAPI DeleteRegistryKeys(REGKEY_DELETEKEY* aKeys, ULONG cKeys) HRESULT hr = S_OK; LSTATUS status; - for (ULONG iKey = 0; iKey < cKeys; iKey++) - { + for (ULONG iKey = 0; iKey < cKeys; iKey++) { status = RegDeleteTree(aKeys[iKey].hKey, aKeys[iKey].lpszSubKey); - if (NOERROR != status) - { + if (NOERROR != status) { hr = HRESULT_FROM_WIN32(status); } } return hr; -} \ No newline at end of file +} diff --git a/src/Tools/ThumbnailProvider/ThumbnailProvider.cpp b/src/Tools/ThumbnailProvider/ThumbnailProvider.cpp index b980c7c55e..56c67706ce 100644 --- a/src/Tools/ThumbnailProvider/ThumbnailProvider.cpp +++ b/src/Tools/ThumbnailProvider/ThumbnailProvider.cpp @@ -23,14 +23,14 @@ #pragma warning(disable : 4995) -#include "Common.h" #include "ThumbnailProvider.h" +#include "Common.h" #include -#include -#include #include #include +#include +#include #pragma comment(lib, "WindowsCodecs.lib") // The functions @@ -82,7 +82,11 @@ IWICBitmapSource* LoadBitmapFromStream(IStream* ipImageStream) // load WIC's PNG decoder IWICBitmapDecoder* ipDecoder = NULL; - if (FAILED(CoCreateInstance(CLSID_WICPngDecoder, NULL, CLSCTX_INPROC_SERVER, __uuidof(ipDecoder), reinterpret_cast(&ipDecoder)))) + if (FAILED(CoCreateInstance(CLSID_WICPngDecoder, + NULL, + CLSCTX_INPROC_SERVER, + __uuidof(ipDecoder), + reinterpret_cast(&ipDecoder)))) goto Return; // load the PNG @@ -144,8 +148,7 @@ HBITMAP CreateHBITMAP(IWICBitmapSource* ipBitmap) const UINT cbStride = width * 4; const UINT cbImage = cbStride * height; - if (FAILED(ipBitmap->CopyPixels(NULL, cbStride, cbImage, static_cast(pvImageBits)))) - { + if (FAILED(ipBitmap->CopyPixels(NULL, cbStride, cbImage, static_cast(pvImageBits)))) { // couldn't extract image; delete HBITMAP DeleteObject(hbmp); @@ -166,8 +169,7 @@ CThumbnailProvider::CThumbnailProvider() CThumbnailProvider::~CThumbnailProvider() { - if (m_pSite) - { + if (m_pSite) { m_pSite->Release(); m_pSite = NULL; } @@ -175,12 +177,10 @@ CThumbnailProvider::~CThumbnailProvider() } -STDMETHODIMP CThumbnailProvider::QueryInterface(REFIID riid, - void** ppvObject) +STDMETHODIMP CThumbnailProvider::QueryInterface(REFIID riid, void** ppvObject) { - static const QITAB qit[] = - { - //QITABENT(CThumbnailProvider, IInitializeWithStream), + static const QITAB qit[] = { + // QITABENT(CThumbnailProvider, IInitializeWithStream), QITABENT(CThumbnailProvider, IInitializeWithFile), QITABENT(CThumbnailProvider, IThumbnailProvider), QITABENT(CThumbnailProvider, IObjectWithSite), @@ -206,14 +206,12 @@ STDMETHODIMP_(ULONG) CThumbnailProvider::Release() } -STDMETHODIMP CThumbnailProvider::Initialize(IStream *pstm, - DWORD grfMode) +STDMETHODIMP CThumbnailProvider::Initialize(IStream* pstm, DWORD grfMode) { return S_OK; } -STDMETHODIMP CThumbnailProvider::Initialize(LPCWSTR pszFilePath, - DWORD grfMode) +STDMETHODIMP CThumbnailProvider::Initialize(LPCWSTR pszFilePath, DWORD grfMode) { wcscpy_s(m_szFile, pszFilePath); return S_OK; @@ -224,7 +222,7 @@ bool CThumbnailProvider::CheckZip() const // open file and check magic number (PK\x03\x04) std::ifstream zip(m_szFile, std::ios::in | std::ios::binary); unsigned char pk[4] = {0x50, 0x4b, 0x03, 0x04}; - for (int i=0; i<4; i++) { + for (int i = 0; i < 4; i++) { unsigned char c; if (!zip.get((char&)c)) return false; @@ -235,9 +233,7 @@ bool CThumbnailProvider::CheckZip() const return true; } -STDMETHODIMP CThumbnailProvider::GetThumbnail(UINT cx, - HBITMAP *phbmp, - WTS_ALPHATYPE *pdwAlpha) +STDMETHODIMP CThumbnailProvider::GetThumbnail(UINT cx, HBITMAP* phbmp, WTS_ALPHATYPE* pdwAlpha) { try { // first make sure we have a zip file but that might still be invalid @@ -252,7 +248,7 @@ STDMETHODIMP CThumbnailProvider::GetThumbnail(UINT cx, entry = zipstream.getNextEntry(); if (entry && entry->isValid()) { // ok, we have found the file. Now, read it in byte for byte - std::istream *str = &zipstream; + std::istream* str = &zipstream; std::vector content; unsigned char c; while (str->get((char&)c)) { @@ -272,7 +268,7 @@ STDMETHODIMP CThumbnailProvider::GetThumbnail(UINT cx, } } } - catch(...) { + catch (...) { // This may happen if the file is corrupted, not a valid zip file // or whatever could go wrong } @@ -281,11 +277,9 @@ STDMETHODIMP CThumbnailProvider::GetThumbnail(UINT cx, } -STDMETHODIMP CThumbnailProvider::GetSite(REFIID riid, - void** ppvSite) +STDMETHODIMP CThumbnailProvider::GetSite(REFIID riid, void** ppvSite) { - if (m_pSite) - { + if (m_pSite) { return m_pSite->QueryInterface(riid, ppvSite); } return E_NOINTERFACE; @@ -294,15 +288,13 @@ STDMETHODIMP CThumbnailProvider::GetSite(REFIID riid, STDMETHODIMP CThumbnailProvider::SetSite(IUnknown* pUnkSite) { - if (m_pSite) - { + if (m_pSite) { m_pSite->Release(); m_pSite = NULL; } m_pSite = pUnkSite; - if (m_pSite) - { + if (m_pSite) { m_pSite->AddRef(); } return S_OK; @@ -314,8 +306,7 @@ STDAPI CThumbnailProvider_CreateInstance(REFIID riid, void** ppvObject) *ppvObject = NULL; CThumbnailProvider* ptp = new CThumbnailProvider(); - if (!ptp) - { + if (!ptp) { return E_OUTOFMEMORY; } diff --git a/src/Tools/ThumbnailProvider/ThumbnailProvider.def b/src/Tools/ThumbnailProvider/ThumbnailProvider.def index 10044d84ed..9abe17258f 100644 --- a/src/Tools/ThumbnailProvider/ThumbnailProvider.def +++ b/src/Tools/ThumbnailProvider/ThumbnailProvider.def @@ -4,4 +4,4 @@ EXPORTS DllRegisterServer PRIVATE DllUnregisterServer PRIVATE DllGetClassObject PRIVATE - DllCanUnloadNow PRIVATE \ No newline at end of file + DllCanUnloadNow PRIVATE diff --git a/src/Tools/ThumbnailProvider/ThumbnailProvider.h b/src/Tools/ThumbnailProvider/ThumbnailProvider.h index bae9b1284b..632f3eda6f 100644 --- a/src/Tools/ThumbnailProvider/ThumbnailProvider.h +++ b/src/Tools/ThumbnailProvider/ThumbnailProvider.h @@ -23,8 +23,8 @@ #pragma once -//class CThumbnailProvider : public IThumbnailProvider, IObjectWithSite, IInitializeWithStream -class CThumbnailProvider : public IThumbnailProvider, IObjectWithSite, IInitializeWithFile +// class CThumbnailProvider : public IThumbnailProvider, IObjectWithSite, IInitializeWithStream +class CThumbnailProvider: public IThumbnailProvider, IObjectWithSite, IInitializeWithFile { private: LONG m_cRef; @@ -45,7 +45,7 @@ public: // IInitializeWithSteam methods STDMETHOD(Initialize)(IStream*, DWORD); // IInitializeWithFile methods - STDMETHOD(Initialize)(LPCWSTR , DWORD); + STDMETHOD(Initialize)(LPCWSTR, DWORD); // IThumbnailProvider methods STDMETHOD(GetThumbnail)(UINT, HBITMAP*, WTS_ALPHATYPE*); @@ -53,4 +53,4 @@ public: // IObjectWithSite methods STDMETHOD(GetSite)(REFIID, void**); STDMETHOD(SetSite)(IUnknown*); -}; \ No newline at end of file +}; diff --git a/src/Tools/WinVersion.py b/src/Tools/WinVersion.py index 930219cf2a..bb3abc71b8 100644 --- a/src/Tools/WinVersion.py +++ b/src/Tools/WinVersion.py @@ -5,28 +5,29 @@ # Script to create files used in Windows build # uses SubWCRev.py for version detection# -import SubWCRev,getopt,sys,string +import SubWCRev, getopt, sys, string + def main(): - input="" - output="." + input = "" + output = "." try: - opts, args = getopt.getopt(sys.argv[1:], "dso:", ["dir=","src=","out="]) + opts, args = getopt.getopt(sys.argv[1:], "dso:", ["dir=", "src=", "out="]) except getopt.GetoptError: pass for o, a in opts: if o in ("-d", "--dir"): - print ("The %s option is deprecated. Ignoring." % (o)) + print("The %s option is deprecated. Ignoring." % (o)) if o in ("-s", "--src"): input = a if o in ("-o", "--out"): output = a git = SubWCRev.GitControl() - if(git.extractInfo(input, "")): + if git.extractInfo(input, ""): print(git.hash) print(git.branch) print(git.rev[0:4]) @@ -35,12 +36,12 @@ def main(): print(input) print(output) - f = open(input,'r') - o = open(output,'w') + f = open(input, "r") + o = open(output, "w") for line in f.readlines(): - line = string.replace(line,'$WCREV$',git.rev[0:4]) - line = string.replace(line,'$WCDATE$',git.date) - line = string.replace(line,'$WCURL$',git.url) + line = string.replace(line, "$WCREV$", git.rev[0:4]) + line = string.replace(line, "$WCDATE$", git.date) + line = string.replace(line, "$WCURL$", git.url) o.write(line) diff --git a/src/Tools/_TEMPLATEPY_/InitGui.py b/src/Tools/_TEMPLATEPY_/InitGui.py index c03b7c7ba4..b6721b7f85 100644 --- a/src/Tools/_TEMPLATEPY_/InitGui.py +++ b/src/Tools/_TEMPLATEPY_/InitGui.py @@ -3,7 +3,8 @@ # (c) 2001 Juergen Riegel # License LGPL -class _TEMPLATEPY_Workbench ( Workbench ): + +class _TEMPLATEPY_Workbench(Workbench): "_TEMPLATEPY_ workbench object" Icon = FreeCAD.getResourceDir() + "Mod/_TEMPLATEPY_/Resources/icons/_TEMPLATEPY_Workbench.svg" MenuText = "_TEMPLATEPY_" @@ -12,10 +13,12 @@ class _TEMPLATEPY_Workbench ( Workbench ): def Initialize(self): # load the module import _TEMPLATEPY_Gui - self.appendToolbar('_TEMPLATEPY_',['_TEMPLATEPY__HelloWorld']) - self.appendMenu('_TEMPLATEPY_',['_TEMPLATEPY__HelloWorld']) + + self.appendToolbar("_TEMPLATEPY_", ["_TEMPLATEPY__HelloWorld"]) + self.appendMenu("_TEMPLATEPY_", ["_TEMPLATEPY__HelloWorld"]) def GetClassName(self): return "Gui::PythonWorkbench" + Gui.addWorkbench(_TEMPLATEPY_Workbench()) diff --git a/src/Tools/_TEMPLATEPY_/_TEMPLATEPY_.dox b/src/Tools/_TEMPLATEPY_/_TEMPLATEPY_.dox index b6b6ab28b0..f9ca3b7af9 100644 --- a/src/Tools/_TEMPLATEPY_/_TEMPLATEPY_.dox +++ b/src/Tools/_TEMPLATEPY_/_TEMPLATEPY_.dox @@ -1,3 +1,2 @@ /** \defgroup TEMPLATE _TEMPLATEPY_ * \ingroup WORKBENCHES */ - diff --git a/src/Tools/_TEMPLATEPY_/_TEMPLATEPY_Gui.py b/src/Tools/_TEMPLATEPY_/_TEMPLATEPY_Gui.py index 1da2960637..5aad32873c 100644 --- a/src/Tools/_TEMPLATEPY_/_TEMPLATEPY_Gui.py +++ b/src/Tools/_TEMPLATEPY_/_TEMPLATEPY_Gui.py @@ -5,12 +5,20 @@ import FreeCAD, FreeCADGui + class CmdHelloWorld: def Activated(self): FreeCAD.Console.PrintMessage("Hello, World!\n") + def IsActive(self): return True - def GetResources(self): - return {'Pixmap': 'freecad', 'MenuText': 'Hello World', 'ToolTip': 'Print Hello World'} -FreeCADGui.addCommand('_TEMPLATEPY__HelloWorld', CmdHelloWorld()) + def GetResources(self): + return { + "Pixmap": "freecad", + "MenuText": "Hello World", + "ToolTip": "Print Hello World", + } + + +FreeCADGui.addCommand("_TEMPLATEPY__HelloWorld", CmdHelloWorld()) diff --git a/src/Tools/_TEMPLATE_/App/App_TEMPLATE_.cpp b/src/Tools/_TEMPLATE_/App/App_TEMPLATE_.cpp index 279d875514..37a3fb31ed 100644 --- a/src/Tools/_TEMPLATE_/App/App_TEMPLATE_.cpp +++ b/src/Tools/_TEMPLATE_/App/App_TEMPLATE_.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include @@ -34,16 +34,19 @@ #include -namespace _TEMPLATE_ { -class Module : public Py::ExtensionModule +namespace _TEMPLATE_ +{ +class Module: public Py::ExtensionModule { public: - Module() : Py::ExtensionModule("_TEMPLATE_") + Module() + : Py::ExtensionModule("_TEMPLATE_") { - initialize("This module is the _TEMPLATE_ module."); // register with Python + initialize("This module is the _TEMPLATE_ module.");// register with Python } - virtual ~Module() {} + virtual ~Module() + {} private: }; @@ -54,7 +57,7 @@ PyObject* initModule() } -} // namespace _TEMPLATE_ +}// namespace _TEMPLATE_ /* Python entry */ diff --git a/src/Tools/_TEMPLATE_/App/PreCompiled.cpp b/src/Tools/_TEMPLATE_/App/PreCompiled.cpp index 68d7ea8a80..ccd1b7fe10 100644 --- a/src/Tools/_TEMPLATE_/App/PreCompiled.cpp +++ b/src/Tools/_TEMPLATE_/App/PreCompiled.cpp @@ -21,4 +21,4 @@ ***************************************************************************/ -#include "PreCompiled.h" +#include "PreCompiled.h" diff --git a/src/Tools/_TEMPLATE_/App/PreCompiled.h b/src/Tools/_TEMPLATE_/App/PreCompiled.h index 7556c1fd3e..ba4f3063e3 100644 --- a/src/Tools/_TEMPLATE_/App/PreCompiled.h +++ b/src/Tools/_TEMPLATE_/App/PreCompiled.h @@ -28,16 +28,16 @@ // Exporting of App classes #ifdef FC_OS_WIN32 -# define _TEMPLATE_AppExport __declspec(dllexport) -#else // for Linux -# define _TEMPLATE_AppExport +#define _TEMPLATE_AppExport __declspec(dllexport) +#else// for Linux +#define _TEMPLATE_AppExport #endif #ifdef _PreComp_ // standard -#include #include +#include #include // STL @@ -55,7 +55,6 @@ // Xerces #include -#endif //_PreComp_ +#endif//_PreComp_ #endif - diff --git a/src/Tools/_TEMPLATE_/Gui/App_TEMPLATE_Gui.cpp b/src/Tools/_TEMPLATE_/Gui/App_TEMPLATE_Gui.cpp index a36affc848..6206d76462 100644 --- a/src/Tools/_TEMPLATE_/Gui/App_TEMPLATE_Gui.cpp +++ b/src/Tools/_TEMPLATE_/Gui/App_TEMPLATE_Gui.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif #include @@ -40,16 +40,19 @@ void Create_TEMPLATE_Commands(void); -namespace _TEMPLATE_Gui { -class Module : public Py::ExtensionModule +namespace _TEMPLATE_Gui +{ +class Module: public Py::ExtensionModule { public: - Module() : Py::ExtensionModule("_TEMPLATE_Gui") + Module() + : Py::ExtensionModule("_TEMPLATE_Gui") { - initialize("This module is the _TEMPLATE_Gui module."); // register with Python + initialize("This module is the _TEMPLATE_Gui module.");// register with Python } - virtual ~Module() {} + virtual ~Module() + {} private: }; @@ -59,7 +62,7 @@ PyObject* initModule() return Base::Interpreter().addModule(new Module); } -} // namespace _TEMPLATE_Gui +}// namespace _TEMPLATE_Gui /* Python entry */ diff --git a/src/Tools/_TEMPLATE_/Gui/Command.cpp b/src/Tools/_TEMPLATE_/Gui/Command.cpp index 1cba467b94..88bc81e8bc 100644 --- a/src/Tools/_TEMPLATE_/Gui/Command.cpp +++ b/src/Tools/_TEMPLATE_/Gui/Command.cpp @@ -25,8 +25,8 @@ #ifndef _PreComp_ #endif -#include #include +#include #include #include @@ -39,16 +39,16 @@ DEF_STD_CMD(Cmd_TEMPLATE_Test) Cmd_TEMPLATE_Test::Cmd_TEMPLATE_Test() - :Command("_TEMPLATE__Test") + : Command("_TEMPLATE__Test") { - sAppModule = "_TEMPLATE_"; - sGroup = QT_TR_NOOP("_TEMPLATE_"); - sMenuText = QT_TR_NOOP("Hello"); - sToolTipText = QT_TR_NOOP("_TEMPLATE_ Test function"); - sWhatsThis = "_TEMPLATE__Test"; - sStatusTip = QT_TR_NOOP("_TEMPLATE_ Test function"); - sPixmap = "_TEMPLATE_Workbench"; - sAccel = "CTRL+H"; + sAppModule = "_TEMPLATE_"; + sGroup = QT_TR_NOOP("_TEMPLATE_"); + sMenuText = QT_TR_NOOP("Hello"); + sToolTipText = QT_TR_NOOP("_TEMPLATE_ Test function"); + sWhatsThis = "_TEMPLATE__Test"; + sStatusTip = QT_TR_NOOP("_TEMPLATE_ Test function"); + sPixmap = "_TEMPLATE_Workbench"; + sAccel = "CTRL+H"; } void Cmd_TEMPLATE_Test::activated(int) @@ -58,6 +58,6 @@ void Cmd_TEMPLATE_Test::activated(int) void Create_TEMPLATE_Commands(void) { - Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); + Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new Cmd_TEMPLATE_Test()); } diff --git a/src/Tools/_TEMPLATE_/Gui/PreCompiled.cpp b/src/Tools/_TEMPLATE_/Gui/PreCompiled.cpp index 68d7ea8a80..ccd1b7fe10 100644 --- a/src/Tools/_TEMPLATE_/Gui/PreCompiled.cpp +++ b/src/Tools/_TEMPLATE_/Gui/PreCompiled.cpp @@ -21,4 +21,4 @@ ***************************************************************************/ -#include "PreCompiled.h" +#include "PreCompiled.h" diff --git a/src/Tools/_TEMPLATE_/Gui/PreCompiled.h b/src/Tools/_TEMPLATE_/Gui/PreCompiled.h index 22f3e34fe4..af3161df95 100644 --- a/src/Tools/_TEMPLATE_/Gui/PreCompiled.h +++ b/src/Tools/_TEMPLATE_/Gui/PreCompiled.h @@ -28,18 +28,18 @@ // Importing of App classes #ifdef FC_OS_WIN32 -# define _TEMPLATE_AppExport __declspec(dllimport) -# define _TEMPLATE_GuiExport __declspec(dllexport) -#else // for Linux -# define _TEMPLATE_AppExport -# define _TEMPLATE_GuiExport +#define _TEMPLATE_AppExport __declspec(dllimport) +#define _TEMPLATE_GuiExport __declspec(dllexport) +#else// for Linux +#define _TEMPLATE_AppExport +#define _TEMPLATE_GuiExport #endif #ifdef _PreComp_ // standard -#include #include +#include // STL #include @@ -57,14 +57,14 @@ #include #ifdef FC_OS_WIN32 -# include +#include #endif // Qt Toolkit #ifndef __QtAll__ -# include +#include #endif -#endif //_PreComp_ +#endif//_PreComp_ -#endif // GUI_PRECOMPILED_H +#endif// GUI_PRECOMPILED_H diff --git a/src/Tools/_TEMPLATE_/Gui/Resources/_TEMPLATE_.qrc b/src/Tools/_TEMPLATE_/Gui/Resources/_TEMPLATE_.qrc index 023842c5de..8c1838d19d 100644 --- a/src/Tools/_TEMPLATE_/Gui/Resources/_TEMPLATE_.qrc +++ b/src/Tools/_TEMPLATE_/Gui/Resources/_TEMPLATE_.qrc @@ -1,5 +1,5 @@ - + icons/_TEMPLATE_Workbench.svg - + diff --git a/src/Tools/_TEMPLATE_/Gui/Workbench.cpp b/src/Tools/_TEMPLATE_/Gui/Workbench.cpp index fe66b3ea01..b5e10b04b6 100644 --- a/src/Tools/_TEMPLATE_/Gui/Workbench.cpp +++ b/src/Tools/_TEMPLATE_/Gui/Workbench.cpp @@ -36,19 +36,17 @@ using namespace _TEMPLATE_Gui; TYPESYSTEM_SOURCE(_TEMPLATE_Gui::Workbench, Gui::StdWorkbench) Workbench::Workbench() -{ -} +{} Workbench::~Workbench() -{ -} +{} Gui::MenuItem* Workbench::setupMenuBar() const { Gui::MenuItem* root = StdWorkbench::setupMenuBar(); - Gui::MenuItem* item = root->findItem( "&Windows" ); + Gui::MenuItem* item = root->findItem("&Windows"); Gui::MenuItem* test = new Gui::MenuItem; - root->insertItem( item, test ); + root->insertItem(item, test); test->setCommand("_TEMPLATE_"); *test << "_TEMPLATE__Test"; return root; @@ -58,7 +56,7 @@ Gui::ToolBarItem* Workbench::setupToolBars() const { Gui::ToolBarItem* root = StdWorkbench::setupToolBars(); Gui::ToolBarItem* test = new Gui::ToolBarItem(root); - test->setCommand( "_TEMPLATE_ Tools" ); - *test << "_TEMPLATE__Test"; + test->setCommand("_TEMPLATE_ Tools"); + *test << "_TEMPLATE__Test"; return root; } diff --git a/src/Tools/_TEMPLATE_/Gui/Workbench.h b/src/Tools/_TEMPLATE_/Gui/Workbench.h index dfe9eeb56e..faa0603f2e 100644 --- a/src/Tools/_TEMPLATE_/Gui/Workbench.h +++ b/src/Tools/_TEMPLATE_/Gui/Workbench.h @@ -26,9 +26,10 @@ #include -namespace _TEMPLATE_Gui { +namespace _TEMPLATE_Gui +{ -class Workbench : public Gui::StdWorkbench +class Workbench: public Gui::StdWorkbench { TYPESYSTEM_HEADER(); @@ -41,7 +42,7 @@ protected: Gui::ToolBarItem* setupToolBars() const; }; -} // namespace _TEMPLATE_Gui +}// namespace _TEMPLATE_Gui -#endif // _TEMPLATE__WORKBENCH_H +#endif// _TEMPLATE__WORKBENCH_H diff --git a/src/Tools/_TEMPLATE_/InitGui.py b/src/Tools/_TEMPLATE_/InitGui.py index d0a28f1ac0..6ebe346b82 100644 --- a/src/Tools/_TEMPLATE_/InitGui.py +++ b/src/Tools/_TEMPLATE_/InitGui.py @@ -1,7 +1,8 @@ # _TEMPLATE_ gui init module # (c) 2001 Juergen Riegel LGPL -class _TEMPLATE_Workbench (Workbench): + +class _TEMPLATE_Workbench(Workbench): "_TEMPLATE_ workbench object" MenuText = "_TEMPLATE_" ToolTip = "_TEMPLATE_ workbench" @@ -13,4 +14,5 @@ class _TEMPLATE_Workbench (Workbench): def GetClassName(self): return "_TEMPLATE_Gui::Workbench" + Gui.addWorkbench(_TEMPLATE_Workbench()) diff --git a/src/Tools/_TEMPLATE_/_TEMPLATE_.dox b/src/Tools/_TEMPLATE_/_TEMPLATE_.dox index 47dd340277..0f7e5764f1 100644 --- a/src/Tools/_TEMPLATE_/_TEMPLATE_.dox +++ b/src/Tools/_TEMPLATE_/_TEMPLATE_.dox @@ -1,3 +1,2 @@ /** \defgroup TEMPLATE _TEMPLATE_ * \ingroup WORKBENCHES */ - diff --git a/src/Tools/_TEMPLATE_/_TEMPLATE_Global.h b/src/Tools/_TEMPLATE_/_TEMPLATE_Global.h index 0b08f3a20a..9984aa6984 100644 --- a/src/Tools/_TEMPLATE_/_TEMPLATE_Global.h +++ b/src/Tools/_TEMPLATE_/_TEMPLATE_Global.h @@ -29,19 +29,19 @@ // _TEMPLATE_ #ifndef _TEMPLATE_Export #ifdef _TEMPLATE__EXPORTS -# define _TEMPLATE_Export FREECAD_DECL_EXPORT +#define _TEMPLATE_Export FREECAD_DECL_EXPORT #else -# define _TEMPLATE_Export FREECAD_DECL_IMPORT +#define _TEMPLATE_Export FREECAD_DECL_IMPORT #endif #endif // _TEMPLATE_Gui #ifndef _TEMPLATE_GuiExport #ifdef _TEMPLATE_Gui_EXPORTS -# define _TEMPLATE_GuiExport FREECAD_DECL_EXPORT +#define _TEMPLATE_GuiExport FREECAD_DECL_EXPORT #else -# define _TEMPLATE_GuiExport FREECAD_DECL_IMPORT +#define _TEMPLATE_GuiExport FREECAD_DECL_IMPORT #endif #endif -#endif //_TEMPLATE__GLOBAL_H +#endif//_TEMPLATE__GLOBAL_H diff --git a/src/Tools/catfiles.py b/src/Tools/catfiles.py index da48d239f3..9bc318506c 100644 --- a/src/Tools/catfiles.py +++ b/src/Tools/catfiles.py @@ -3,12 +3,14 @@ # (c) 2018 Werner Mayer LGPL # -import sys,getopt -#import os # The code that needs this is commented out +import sys, getopt + +# import os # The code that needs this is commented out import shutil + def main(): - outputfile="" + outputfile = "" try: opts, args = getopt.getopt(sys.argv[1:], "o:", ["outputfile="]) except getopt.GetoptError: @@ -18,7 +20,7 @@ def main(): if o in ("-o", "--outputfile"): outputfile = a - #if os.path.exists(outputfile): + # if os.path.exists(outputfile): # do_not_create = True # ts = os.path.getmtime(outputfile) # for f in args: @@ -30,11 +32,12 @@ def main(): # print ("Up-to-date file {0}".format(outputfile)) # return - with open(outputfile,'wb') as wfd: + with open(outputfile, "wb") as wfd: for f in args: - with open(f,'rb') as fd: - shutil.copyfileobj(fd, wfd, 1024*1024*10) - print ("Created file {0}".format(outputfile)) + with open(f, "rb") as fd: + shutil.copyfileobj(fd, wfd, 1024 * 1024 * 10) + print("Created file {0}".format(outputfile)) + if __name__ == "__main__": main() diff --git a/src/Tools/chm.css b/src/Tools/chm.css index b5dc000550..10602b080e 100644 --- a/src/Tools/chm.css +++ b/src/Tools/chm.css @@ -1,6 +1,6 @@ a.new{ color:#ba0000; text-decoration:none; } -#toc { +#toc { /*border:1px solid #2f6fab;*/ border:1px solid #aaaaaa; background-color:#f9f9f9; @@ -17,22 +17,22 @@ a.new{ color:#ba0000; text-decoration:none; } } /* images */ -div.floatright { - float: right; +div.floatright { + float: right; margin: 0; position:relative; border: 0.5em solid White; border-width: 0.5em 0 0.8em 1.4em; } -div.floatright p { font-style: italic;} -div.floatleft { - float: left; +div.floatright p { font-style: italic;} +div.floatleft { + float: left; margin: 0.3em 0.5em 0.5em 0; position:relative; border: 0.5em solid White; border-width: 0.5em 1.4em 0.8em 0; } -div.floatleft p { font-style: italic; } +div.floatleft p { font-style: italic; } /* thumbnails */ div.thumb { margin-bottom: 0.5em; @@ -67,10 +67,10 @@ div.tleft { /* table standards */ table.rimage { - float:right; - width:1pt; + float:right; + width:1pt; position:relative; - margin-left:1em; + margin-left:1em; margin-bottom:1em; text-align:center; } @@ -103,7 +103,7 @@ li#f-privacy { display: none; } -ul { +ul { list-style-type: square; } @@ -122,7 +122,7 @@ h1, h2, h3, h4, h5, h6 p, .documentDescription { /*margin: 1em 0 ! important;*/ - line-height: 1.2em; + line-height: 1.2em; } .tocindent p { @@ -208,7 +208,7 @@ div.townBox { } div.townBox dl { padding: 0; - margin: 0 0 0.3em 0; + margin: 0 0 0.3em 0; font-size: 96%; } div.townBox dl dt { @@ -229,7 +229,7 @@ table.gallery { background-color:#ffffff; } -table.gallery tr { +table.gallery tr { vertical-align:top; } @@ -244,12 +244,12 @@ div.gallerybox div.thumb { text-align: center; border: 1px solid #cccccc; margin: 2px; -} +} div.gallerytext { font-size: 94%; padding: 2px 4px; -} +} /* ** Diff rendering diff --git a/src/Tools/dir2qrc.py b/src/Tools/dir2qrc.py index adcf5f50d9..3c51a6a790 100644 --- a/src/Tools/dir2qrc.py +++ b/src/Tools/dir2qrc.py @@ -5,21 +5,21 @@ Usage = """dir2qrc - merging all files in a directory in a qrc file Usage: - dir2qrc [Optionen] - + dir2qrc [Optionen] + Options: -v, --verbose print out all files collected -o --out-file=FILENAME use this file name for output, default resources.qrc -d, --directory=DIRNAME directory to search, default PWD -h, --help print this help message - + This program walks a directory (tree) and collects all supported files and put them in a .qrc file, to compile in with the QT resource facility. Examples: - + dir2qrc -v -o resource.qrc -d "d:/Develop/Resources" - + Author: (c) 2007 Juergen Riegel juergen.riegel@web.de @@ -29,48 +29,55 @@ Version: 0.1 """ -import os,sys,getopt +import os, sys, getopt from os.path import join # Globals Verbose = False Automatic = False ExtraDist = False -Dir = '.' -Output = 'resources.qrc' +Dir = "." +Output = "resources.qrc" hhcHeader = """ - + """ -hhcFooter=""" - +hhcFooter = """ + """ -EndingList = ['.xpm','.svg','.qm','.png','.ui'] +EndingList = [".xpm", ".svg", ".qm", ".png", ".ui"] + +locations = [ + ["../Gui/Language", "translation.qrc", ' prefix="/translations"'], + ["../Gui/Icons", "resource.qrc", ' prefix="/icons"'], + ["../Mod/Assembly/Gui/Resources", "Assembly.qrc"], + ["../Mod/Complete/Gui/Resources", "Complete.qrc"], + ["../Mod/Draft/Resources", "Draft.qrc"], + ["../Mod/Drawing/Gui/Resources", "Drawing.qrc"], + ["../Mod/Fem/Gui/Resources", "Fem.qrc"], + ["../Mod/Image/Gui/Resources", "Image.qrc"], + ["../Mod/Mesh/Gui/Resources", "Mesh.qrc"], + ["../Mod/MeshPart/Gui/Resources", "MeshPart.qrc"], + ["../Mod/Part/Gui/Resources", "Part.qrc"], + ["../Mod/PartDesign/Gui/Resources", "PartDesign.qrc"], + ["../Mod/Points/Gui/Resources", "Points.qrc"], + ["../Mod/Raytracing/Gui/Resources", "Raytracing.qrc"], + ["../Mod/ReverseEngineering/Gui/Resources", "ReverseEngineering.qrc"], + ["../Mod/Robot/Gui/Resources", "Robot.qrc"], + ["../Mod/Sketcher/Gui/Resources", "Sketcher.qrc"], +] -locations = [["../Gui/Language","translation.qrc"," prefix=\"/translations\""], - ["../Gui/Icons","resource.qrc"," prefix=\"/icons\""], - ["../Mod/Assembly/Gui/Resources","Assembly.qrc"], - ["../Mod/Complete/Gui/Resources","Complete.qrc"], - ["../Mod/Draft/Resources","Draft.qrc"], - ["../Mod/Drawing/Gui/Resources","Drawing.qrc"], - ["../Mod/Fem/Gui/Resources","Fem.qrc"], - ["../Mod/Image/Gui/Resources","Image.qrc"], - ["../Mod/Mesh/Gui/Resources","Mesh.qrc"], - ["../Mod/MeshPart/Gui/Resources","MeshPart.qrc"], - ["../Mod/Part/Gui/Resources","Part.qrc"], - ["../Mod/PartDesign/Gui/Resources","PartDesign.qrc"], - ["../Mod/Points/Gui/Resources","Points.qrc"], - ["../Mod/Raytracing/Gui/Resources","Raytracing.qrc"], - ["../Mod/ReverseEngineering/Gui/Resources","ReverseEngineering.qrc"], - ["../Mod/Robot/Gui/Resources","Robot.qrc"], - ["../Mod/Sketcher/Gui/Resources","Sketcher.qrc"]] def main(): - global Verbose,Automatic,ExtraDist,Dir,Output - + global Verbose, Automatic, ExtraDist, Dir, Output + try: - opts, args = getopt.getopt(sys.argv[1:], "hvd:o:", ["help", "verbose", "auto", "dist", "directory=","out-file="]) + opts, args = getopt.getopt( + sys.argv[1:], + "hvd:o:", + ["help", "verbose", "auto", "dist", "directory=", "out-file="], + ) except getopt.GetoptError: # print help information and exit: sys.stderr.write(Usage) @@ -90,18 +97,18 @@ def main(): if o in ("-o", "--out-file"): Output = a if o in ("-d", "--directory"): - print("Using path: " + a +"\n") + print("Using path: " + a + "\n") Dir = a - + if Automatic: path = os.path.realpath(__file__) path = os.path.dirname(path) for i in locations: - qrcDir = os.path.realpath(join(path,i[0])) + qrcDir = os.path.realpath(join(path, i[0])) if len(i) > 2: - updateResourceFile(qrcDir,i[1],i[2]) + updateResourceFile(qrcDir, i[1], i[2]) else: - updateResourceFile(qrcDir,i[1]) + updateResourceFile(qrcDir, i[1]) if ExtraDist: makeTargetExtraDist(qrcDir) else: @@ -109,31 +116,33 @@ def main(): if ExtraDist: makeTargetExtraDist(Dir) -def updateResourceFile(Dir, Output,prefix=""): + +def updateResourceFile(Dir, Output, prefix=""): global Verbose - Output = join(Dir,Output) - file = open(Output,"w") + Output = join(Dir, Output) + file = open(Output, "w") file.write(hhcHeader % (prefix)) DirPath = Dir + os.path.sep - filelist=[] + filelist = [] for root, dirs, files in os.walk(Dir): for name in files: - if ( (1 in [c in name for c in EndingList]) and not ('.svn' in root) ): - FilePathOrg = join(root,name) - FilePath = FilePathOrg.replace(DirPath,'') - FilePath = FilePath.replace('.\\','') - FilePath = FilePath.replace('\\','/') - if Verbose: print(FilePathOrg + ' -> ' + FilePath) + if (1 in [c in name for c in EndingList]) and not (".svn" in root): + FilePathOrg = join(root, name) + FilePath = FilePathOrg.replace(DirPath, "") + FilePath = FilePath.replace(".\\", "") + FilePath = FilePath.replace("\\", "/") + if Verbose: + print(FilePathOrg + " -> " + FilePath) filelist.append(FilePath) - filelist.sort() for i in filelist: - file.write(' ' + i + '\n') + file.write(" " + i + "\n") file.write(hhcFooter) file.close() + def makeTargetExtraDist(Dir): extensions = EndingList[:] extensions.append(".qrc") @@ -143,13 +152,14 @@ def makeTargetExtraDist(Dir): DirPath = Dir + os.path.sep for root, dirs, files in os.walk(Dir): for name in files: - if ( (1 in [c in name for c in extensions]) and not ('.svn' in root) ): - FilePathOrg = join(root,name) - FilePath = FilePathOrg.replace(DirPath,'') - FilePath = FilePath.replace('.\\','') - FilePath = FilePath.replace('\\','/') + if (1 in [c in name for c in extensions]) and not (".svn" in root): + FilePathOrg = join(root, name) + FilePath = FilePathOrg.replace(DirPath, "") + FilePath = FilePath.replace(".\\", "") + FilePath = FilePath.replace("\\", "/") print("\t\t%s \\" % (FilePath)) print() + if __name__ == "__main__": main() diff --git a/src/Tools/doctools.py b/src/Tools/doctools.py index 9d7bae667f..398aa58720 100644 --- a/src/Tools/doctools.py +++ b/src/Tools/doctools.py @@ -17,9 +17,9 @@ class DocumentHandler(xml.sax.handler.ContentHandler): self.dirname = dirname def startElement(self, name, attributes): - item=attributes.get("file") + item = attributes.get("file") if item is not None: - self.files.append(os.path.join(self.dirname,str(item))) + self.files.append(os.path.join(self.dirname, str(item))) def characters(self, data): return @@ -27,43 +27,46 @@ class DocumentHandler(xml.sax.handler.ContentHandler): def endElement(self, name): return + def extractDocument(filename, outpath): - zfile=zipfile.ZipFile(filename) - files=zfile.namelist() - + zfile = zipfile.ZipFile(filename) + files = zfile.namelist() + for i in files: - data=zfile.read(i) - dirs=i.split("/") + data = zfile.read(i) + dirs = i.split("/") if len(dirs) > 1: dirs.pop() - curpath=outpath + curpath = outpath for j in dirs: - curpath=curpath+"/"+j + curpath = curpath + "/" + j os.mkdir(curpath) - output=open(outpath+"/"+i,'wb') + output = open(outpath + "/" + i, "wb") output.write(data) output.close() + def createDocument(filename, outpath): - files=getFilesList(filename) - compress=zipfile.ZipFile(outpath,'w',zipfile.ZIP_DEFLATED) + files = getFilesList(filename) + compress = zipfile.ZipFile(outpath, "w", zipfile.ZIP_DEFLATED) for i in files: - dirs=os.path.split(i) - #print i, dirs[-1] - compress.write(i,dirs[-1],zipfile.ZIP_DEFLATED) + dirs = os.path.split(i) + # print i, dirs[-1] + compress.write(i, dirs[-1], zipfile.ZIP_DEFLATED) compress.close() + def getFilesList(filename): - dirname=os.path.dirname(filename) - handler=DocumentHandler(dirname) - parser=xml.sax.make_parser() + dirname = os.path.dirname(filename) + handler = DocumentHandler(dirname) + parser = xml.sax.make_parser() parser.setContentHandler(handler) parser.parse(filename) - files=[] + files = [] files.append(filename) files.extend(iter(handler.files)) - dirname=os.path.join(dirname,"GuiDocument.xml") + dirname = os.path.join(dirname, "GuiDocument.xml") if os.path.exists(dirname): files.append(dirname) return files diff --git a/src/Tools/embedded/PySide/mainwindow.py b/src/Tools/embedded/PySide/mainwindow.py index ea217fe174..597de09470 100644 --- a/src/Tools/embedded/PySide/mainwindow.py +++ b/src/Tools/embedded/PySide/mainwindow.py @@ -1,20 +1,23 @@ import sys -#sys.path.append("") + +# sys.path.append("") from PySide import QtCore, QtGui import FreeCAD, FreeCADGui from ui_mainwindow import Ui_MainWindow + class MainWindow(QtGui.QMainWindow): - def __init__(self, parent = None): + def __init__(self, parent=None): super(MainWindow, self).__init__(parent) from PySide import QtNetwork + # Webkit is used to create icons from SVG files. This could cause a deadlock # when setting up the internally used network interface. Doing this before # creating the icons fixes the issue. QtNetwork.QNetworkConfigurationManager() - + def showEvent(self, event): FreeCADGui.showMainWindow() self.setCentralWidget(FreeCADGui.getMainWindow()) @@ -22,32 +25,36 @@ class MainWindow(QtGui.QMainWindow): class BlankWorkbench(FreeCADGui.Workbench): MenuText = "Blank" ToolTip = "Blank workbench" + def Initialize(self): return + def GetClassName(self): return "Gui::BlankWorkbench" + FreeCADGui.addWorkbench(BlankWorkbench) FreeCADGui.activateWorkbench("BlankWorkbench") - + @QtCore.Slot() def on_actionEmbed_triggered(self): return - + @QtCore.Slot() def on_actionDocument_triggered(self): FreeCAD.newDocument() - + @QtCore.Slot() def on_actionCube_triggered(self): FreeCAD.ActiveDocument.addObject("Part::Box") FreeCAD.ActiveDocument.recompute() FreeCADGui.ActiveDocument.ActiveView.fitAll() -app=QtGui.QApplication(sys.argv) -ui=Ui_MainWindow() -mw=MainWindow() + +app = QtGui.QApplication(sys.argv) +ui = Ui_MainWindow() +mw = MainWindow() ui.setupUi(mw) ui.actionEmbed.setVisible(False) -mw.resize(1200,800) +mw.resize(1200, 800) mw.show() app.exec_() diff --git a/src/Tools/embedded/PySide/mainwindow2.py b/src/Tools/embedded/PySide/mainwindow2.py index eaa60d8cee..272903f1df 100644 --- a/src/Tools/embedded/PySide/mainwindow2.py +++ b/src/Tools/embedded/PySide/mainwindow2.py @@ -1,18 +1,21 @@ import sys -#sys.path.append("") + +# sys.path.append("") from PySide import QtGui import FreeCADGui + class MainWindow(QtGui.QMainWindow): - def __init__(self, parent = None): + def __init__(self, parent=None): super(MainWindow, self).__init__(parent) from PySide import QtNetwork + # Webkit is used to create icons from SVG files. This could cause a deadlock # when setting up the internally used network interface. Doing this before # creating the icons fixes the issue. QtNetwork.QNetworkConfigurationManager() - + def showEvent(self, event): FreeCADGui.showMainWindow() self.setCentralWidget(FreeCADGui.getMainWindow()) @@ -20,16 +23,20 @@ class MainWindow(QtGui.QMainWindow): class BlankWorkbench(FreeCADGui.Workbench): MenuText = "Blank" ToolTip = "Blank workbench" + def Initialize(self): - self.appendMenu("Menu",["Std_New", "Part_Box"]) + self.appendMenu("Menu", ["Std_New", "Part_Box"]) return + def GetClassName(self): return "Gui::PythonBlankWorkbench" + FreeCADGui.addWorkbench(BlankWorkbench) FreeCADGui.activateWorkbench("BlankWorkbench") -app=QtGui.QApplication(sys.argv) -mw=MainWindow() -mw.resize(1200,800) + +app = QtGui.QApplication(sys.argv) +mw = MainWindow() +mw.resize(1200, 800) mw.show() app.exec_() diff --git a/src/Tools/embedded/PySide/mainwindow3.py b/src/Tools/embedded/PySide/mainwindow3.py index cfbee18c92..0ab78ea9ef 100644 --- a/src/Tools/embedded/PySide/mainwindow3.py +++ b/src/Tools/embedded/PySide/mainwindow3.py @@ -1,5 +1,6 @@ import sys -#sys.path.append("") + +# sys.path.append("") from PySide import QtCore, QtGui import FreeCAD, FreeCADGui @@ -7,10 +8,12 @@ import ctypes from ui_mainwindow import Ui_MainWindow + class MainWindow(QtGui.QMainWindow): - def __init__(self, parent = None): + def __init__(self, parent=None): super(MainWindow, self).__init__(parent) from PySide import QtNetwork + # Webkit is used to create icons from SVG files. This could cause a deadlock # when setting up the internally used network interface. Doing this before # creating the icons fixes the issue. @@ -19,18 +22,23 @@ class MainWindow(QtGui.QMainWindow): @QtCore.Slot() def on_actionEmbed_triggered(self): FreeCADGui.showMainWindow() - hwnd=self.winId() - PyCObject_AsVoidPtr = ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object)(('PyCObject_AsVoidPtr', ctypes.pythonapi)) + hwnd = self.winId() + PyCObject_AsVoidPtr = ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object)( + ("PyCObject_AsVoidPtr", ctypes.pythonapi) + ) addr = PyCObject_AsVoidPtr(hwnd) FreeCADGui.embedToWindow(hex(addr)) # Need version >= 0.16.5949 class BlankWorkbench(FreeCADGui.Workbench): MenuText = "Blank" ToolTip = "Blank workbench" + def Initialize(self): return + def GetClassName(self): return "Gui::BlankWorkbench" + FreeCADGui.addWorkbench(BlankWorkbench) FreeCADGui.activateWorkbench("BlankWorkbench") @@ -44,10 +52,11 @@ class MainWindow(QtGui.QMainWindow): FreeCAD.ActiveDocument.recompute() FreeCADGui.ActiveDocument.ActiveView.fitAll() -app=QtGui.QApplication(sys.argv) -ui=Ui_MainWindow() -mw=MainWindow() + +app = QtGui.QApplication(sys.argv) +ui = Ui_MainWindow() +mw = MainWindow() ui.setupUi(mw) -mw.resize(1200,800) +mw.resize(1200, 800) mw.show() app.exec_() diff --git a/src/Tools/embedded/PySide/minimal.py b/src/Tools/embedded/PySide/minimal.py index a1f4e00200..d612f5d57c 100644 --- a/src/Tools/embedded/PySide/minimal.py +++ b/src/Tools/embedded/PySide/minimal.py @@ -2,14 +2,16 @@ import sys from PySide2 import QtWidgets import FreeCADGui + class MainWindow(QtWidgets.QMainWindow): def showEvent(self, event): FreeCADGui.showMainWindow() self.setCentralWidget(FreeCADGui.getMainWindow()) + app = QtWidgets.QApplication(sys.argv) mw = MainWindow() -mw.resize(1200,800) +mw.resize(1200, 800) mw.show() # must be done a few times to update the GUI @@ -18,7 +20,8 @@ app.processEvents() app.processEvents() import Part -cube = Part.makeBox(2,2,2) + +cube = Part.makeBox(2, 2, 2) # creates a document and a Part feature with the cube Part.show(cube) app.processEvents() diff --git a/src/Tools/embedded/PySide/ui_mainwindow.py b/src/Tools/embedded/PySide/ui_mainwindow.py index e0da9672bf..28560e86cb 100644 --- a/src/Tools/embedded/PySide/ui_mainwindow.py +++ b/src/Tools/embedded/PySide/ui_mainwindow.py @@ -9,6 +9,7 @@ from PySide import QtCore, QtGui + class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") @@ -40,9 +41,26 @@ class Ui_MainWindow(object): QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): - MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) - self.menuFreeCAD.setTitle(QtGui.QApplication.translate("MainWindow", "FreeCAD", None, QtGui.QApplication.UnicodeUTF8)) - self.actionEmbed.setText(QtGui.QApplication.translate("MainWindow", "Embed", None, QtGui.QApplication.UnicodeUTF8)) - self.actionDocument.setText(QtGui.QApplication.translate("MainWindow", "Document", None, QtGui.QApplication.UnicodeUTF8)) - self.actionCube.setText(QtGui.QApplication.translate("MainWindow", "Cube", None, QtGui.QApplication.UnicodeUTF8)) - + MainWindow.setWindowTitle( + QtGui.QApplication.translate( + "MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8 + ) + ) + self.menuFreeCAD.setTitle( + QtGui.QApplication.translate( + "MainWindow", "FreeCAD", None, QtGui.QApplication.UnicodeUTF8 + ) + ) + self.actionEmbed.setText( + QtGui.QApplication.translate( + "MainWindow", "Embed", None, QtGui.QApplication.UnicodeUTF8 + ) + ) + self.actionDocument.setText( + QtGui.QApplication.translate( + "MainWindow", "Document", None, QtGui.QApplication.UnicodeUTF8 + ) + ) + self.actionCube.setText( + QtGui.QApplication.translate("MainWindow", "Cube", None, QtGui.QApplication.UnicodeUTF8) + ) diff --git a/src/Tools/embedded/Qt/cxx/PreCompiled.h b/src/Tools/embedded/Qt/cxx/PreCompiled.h index c8e5fd06c4..d6fb8dfafa 100644 --- a/src/Tools/embedded/Qt/cxx/PreCompiled.h +++ b/src/Tools/embedded/Qt/cxx/PreCompiled.h @@ -2,20 +2,20 @@ #define __PRECOMPILED__ #ifdef _MSC_VER -# pragma warning( disable : 4251 ) +#pragma warning(disable : 4251) #endif #ifdef FC_OS_WIN32 // cmake generates this define -# if defined (FreeCADPlugin_EXPORTS) -# define FC_PLUGIN_EXPORT __declspec(dllexport) -# else -# define FC_PLUGIN_EXPORT __declspec(dllimport) -# endif -# define MeshExport __declspec(dllimport) -#else // for Linux -# define FC_PLUGIN_EXPORT -# define MeshExport +#if defined(FreeCADPlugin_EXPORTS) +#define FC_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FC_PLUGIN_EXPORT __declspec(dllimport) +#endif +#define MeshExport __declspec(dllimport) +#else// for Linux +#define FC_PLUGIN_EXPORT +#define MeshExport #endif diff --git a/src/Tools/embedded/Qt/cxx/main.cpp b/src/Tools/embedded/Qt/cxx/main.cpp index 4040e1ad4b..6d128cf9a5 100644 --- a/src/Tools/embedded/Qt/cxx/main.cpp +++ b/src/Tools/embedded/Qt/cxx/main.cpp @@ -1,9 +1,9 @@ #include #include -#include -#include #include +#include +#include QLibrary* freecadPlugin = nullptr; diff --git a/src/Tools/embedded/Qt/cxx/plugin.cpp b/src/Tools/embedded/Qt/cxx/plugin.cpp index 5b15485d75..7173d77066 100644 --- a/src/Tools/embedded/Qt/cxx/plugin.cpp +++ b/src/Tools/embedded/Qt/cxx/plugin.cpp @@ -5,16 +5,16 @@ #include #include +#include #include #include -#include #include #include PyMODINIT_FUNC FreeCAD_init() { - static QVector argv; + static QVector argv; #if defined(_DEBUG) argv << "FreeCADApp_d.dll" << 0; #else @@ -40,14 +40,12 @@ PyMODINIT_FUNC FreeCAD_init() /* A test function for the plugin to load a mesh and call "getVal()" */ PyMODINIT_FUNC FreeCAD_test(const char* path) { - try - { // Use FreeCADGui here, not Gui + try {// Use FreeCADGui here, not Gui Base::Interpreter().runString("FreeCADGui.activateWorkbench(\"MeshWorkbench\")"); Base::Interpreter().runString("import Mesh"); Base::Interpreter().runStringArg("Mesh.insert(u\"%s\", \"%s\")", path, "Document"); } - catch (const Base::Exception& e) - { + catch (const Base::Exception& e) { QMessageBox::warning(0, "Exception", e.what()); } } diff --git a/src/Tools/embedded/Qt/main.cpp b/src/Tools/embedded/Qt/main.cpp index f00a5adfdc..b2ab4a0c4d 100644 --- a/src/Tools/embedded/Qt/main.cpp +++ b/src/Tools/embedded/Qt/main.cpp @@ -4,22 +4,22 @@ #include "mainwindow.h" -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { const char* name = "Qt example"; - Py_SetProgramName(Py_DecodeLocale(name,NULL)); + Py_SetProgramName(Py_DecodeLocale(name, NULL)); Py_Initialize(); size_t size = argc; - wchar_t **_argv = new wchar_t*[size]; + wchar_t** _argv = new wchar_t*[size]; for (int i = 0; i < argc; i++) { - _argv[i] = Py_DecodeLocale(argv[i],NULL); + _argv[i] = Py_DecodeLocale(argv[i], NULL); } PySys_SetArgv(argc, _argv); QApplication app(argc, argv); MainWindow mainWin; - mainWin.resize(600,400); + mainWin.resize(600, 400); mainWin.show(); return app.exec(); } diff --git a/src/Tools/embedded/Qt/mainwindow.cpp b/src/Tools/embedded/Qt/mainwindow.cpp index bb66026f17..f930a12770 100644 --- a/src/Tools/embedded/Qt/mainwindow.cpp +++ b/src/Tools/embedded/Qt/mainwindow.cpp @@ -1,11 +1,11 @@ #include -#include -#include #include #include +#include +#include #if defined(Q_WS_X11) -# include +#include #endif #include "mainwindow.h" @@ -67,7 +67,7 @@ void MainWindow::loadFreeCAD() { QString path = QFileDialog::getExistingDirectory(this, "FreeCAD module path"); if (!path.isEmpty()) { - path.replace('\\','/'); + path.replace('\\', '/'); PyObject* main = PyImport_AddModule("__main__"); PyObject* dict = PyModule_GetDict(main); std::stringstream cmd; @@ -100,8 +100,7 @@ void MainWindow::newDocument() { PyObject* main = PyImport_AddModule("__main__"); PyObject* dict = PyModule_GetDict(main); - const char* cmd = - "FreeCAD.newDocument()\n"; + const char* cmd = "FreeCAD.newDocument()\n"; PyObject* result = PyRun_String(cmd, Py_file_input, dict, dict); if (result) { @@ -151,8 +150,8 @@ void MainWindow::embedWindow() QWidget* mw = nullptr; for (auto it : qApp->topLevelWidgets()) { if (it->inherits("Gui::MainWindow")) { - mw = it; - break; + mw = it; + break; } } if (mw) { @@ -177,6 +176,5 @@ void MainWindow::embedWindow() void MainWindow::about() { - QMessageBox::about(this, tr("About"), - tr("Demonstrates remote control of FreeCAD")); + QMessageBox::about(this, tr("About"), tr("Demonstrates remote control of FreeCAD")); } diff --git a/src/Tools/embedded/Qt/mainwindow.h b/src/Tools/embedded/Qt/mainwindow.h index 14a350742d..f7472d7c06 100644 --- a/src/Tools/embedded/Qt/mainwindow.h +++ b/src/Tools/embedded/Qt/mainwindow.h @@ -10,7 +10,7 @@ class QMenu; class QTextEdit; QT_END_NAMESPACE -class MainWindow : public QMainWindow +class MainWindow: public QMainWindow { Q_OBJECT @@ -27,14 +27,14 @@ private: void createActions(); void createMenus(); - QMenu *fileMenu; - QMenu *editMenu; - QMenu *helpMenu; - QAction *loadAct; - QAction *newAct; - QAction *embedAct; - QAction *exitAct; - QAction *aboutAct; + QMenu* fileMenu; + QMenu* editMenu; + QMenu* helpMenu; + QAction* loadAct; + QAction* newAct; + QAction* embedAct; + QAction* exitAct; + QAction* aboutAct; }; #endif diff --git a/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.cpp b/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.cpp index b65140bef0..47ee6a7bb6 100644 --- a/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.cpp +++ b/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.cpp @@ -1,70 +1,63 @@ // FreeCAD_widget.cpp : Defines the entry point for the application. // +#include "FreeCAD_widget.h" #include "stdafx.h" #include #include -#include "FreeCAD_widget.h" -#include #include +#include #define MAX_LOADSTRING 100 // Global Variables: -HINSTANCE hInst; // current instance -TCHAR szTitle[MAX_LOADSTRING]; // The title bar text -TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name +HINSTANCE hInst; // current instance +TCHAR szTitle[MAX_LOADSTRING]; // The title bar text +TCHAR szWindowClass[MAX_LOADSTRING];// the main window class name // Forward declarations of functions included in this code module: -ATOM MyRegisterClass(HINSTANCE hInstance); -BOOL InitInstance(HINSTANCE, int); -LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); -INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); -std::string OnFileOpen(HWND, UINT, WPARAM, LPARAM); -void OnLoadFreeCAD(HWND, UINT, WPARAM, LPARAM); -void OnNewDocument(HWND); -void OnEmbedWidget(HWND hWnd); +ATOM MyRegisterClass(HINSTANCE hInstance); +BOOL InitInstance(HINSTANCE, int); +LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); +INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); +std::string OnFileOpen(HWND, UINT, WPARAM, LPARAM); +void OnLoadFreeCAD(HWND, UINT, WPARAM, LPARAM); +void OnNewDocument(HWND); +void OnEmbedWidget(HWND hWnd); -int APIENTRY _tWinMain(HINSTANCE hInstance, - HINSTANCE hPrevInstance, - LPTSTR lpCmdLine, - int nCmdShow) +int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { - UNREFERENCED_PARAMETER(hPrevInstance); - UNREFERENCED_PARAMETER(lpCmdLine); + UNREFERENCED_PARAMETER(hPrevInstance); + UNREFERENCED_PARAMETER(lpCmdLine); - // TODO: Place code here. - MSG msg; - HACCEL hAccelTable; + // TODO: Place code here. + MSG msg; + HACCEL hAccelTable; - // Initialize global strings - LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); - LoadString(hInstance, IDC_FREECAD_WIDGET, szWindowClass, MAX_LOADSTRING); - MyRegisterClass(hInstance); + // Initialize global strings + LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); + LoadString(hInstance, IDC_FREECAD_WIDGET, szWindowClass, MAX_LOADSTRING); + MyRegisterClass(hInstance); - // Perform application initialization: - if (!InitInstance (hInstance, nCmdShow)) - { - return FALSE; - } + // Perform application initialization: + if (!InitInstance(hInstance, nCmdShow)) { + return FALSE; + } - hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_FREECAD_WIDGET)); + hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_FREECAD_WIDGET)); - // Main message loop: - while (GetMessage(&msg, NULL, 0, 0)) - { - if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } + // Main message loop: + while (GetMessage(&msg, NULL, 0, 0)) { + if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } - return (int) msg.wParam; + return (int)msg.wParam; } - // // FUNCTION: MyRegisterClass() // @@ -80,23 +73,23 @@ int APIENTRY _tWinMain(HINSTANCE hInstance, // ATOM MyRegisterClass(HINSTANCE hInstance) { - WNDCLASSEX wcex; + WNDCLASSEX wcex; - wcex.cbSize = sizeof(WNDCLASSEX); + wcex.cbSize = sizeof(WNDCLASSEX); - wcex.style = CS_HREDRAW | CS_VREDRAW; - wcex.lpfnWndProc = WndProc; - wcex.cbClsExtra = 0; - wcex.cbWndExtra = 0; - wcex.hInstance = hInstance; - wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_FREECAD_WIDGET)); - wcex.hCursor = LoadCursor(NULL, IDC_ARROW); - wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); - wcex.lpszMenuName = MAKEINTRESOURCE(IDC_FREECAD_WIDGET); - wcex.lpszClassName = szWindowClass; - wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = WndProc; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = hInstance; + wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_FREECAD_WIDGET)); + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); + wcex.lpszMenuName = MAKEINTRESOURCE(IDC_FREECAD_WIDGET); + wcex.lpszClassName = szWindowClass; + wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); - return RegisterClassEx(&wcex); + return RegisterClassEx(&wcex); } // @@ -111,22 +104,30 @@ ATOM MyRegisterClass(HINSTANCE hInstance) // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { - HWND hWnd; + HWND hWnd; - hInst = hInstance; // Store instance handle in our global variable + hInst = hInstance;// Store instance handle in our global variable - hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, - CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); + hWnd = CreateWindow(szWindowClass, + szTitle, + WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, + 0, + CW_USEDEFAULT, + 0, + NULL, + NULL, + hInstance, + NULL); - if (!hWnd) - { - return FALSE; - } + if (!hWnd) { + return FALSE; + } - ShowWindow(hWnd, nCmdShow); - UpdateWindow(hWnd); + ShowWindow(hWnd, nCmdShow); + UpdateWindow(hWnd); - return TRUE; + return TRUE; } // @@ -141,69 +142,65 @@ BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { - int wmId, wmEvent; - PAINTSTRUCT ps; - HDC hdc; + int wmId, wmEvent; + PAINTSTRUCT ps; + HDC hdc; - switch (message) - { - case WM_COMMAND: - wmId = LOWORD(wParam); - wmEvent = HIWORD(wParam); - // Parse the menu selections: - switch (wmId) - { - case IDM_ABOUT: - DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); - break; - case IDM_EXIT: - DestroyWindow(hWnd); - break; - case ID_FREECAD_LOAD: - OnLoadFreeCAD(hWnd, message, wParam, lParam); + switch (message) { + case WM_COMMAND: + wmId = LOWORD(wParam); + wmEvent = HIWORD(wParam); + // Parse the menu selections: + switch (wmId) { + case IDM_ABOUT: + DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); + break; + case IDM_EXIT: + DestroyWindow(hWnd); + break; + case ID_FREECAD_LOAD: + OnLoadFreeCAD(hWnd, message, wParam, lParam); + break; + case ID_FREECAD_NEWDOCUMENT: + OnNewDocument(hWnd); + break; + case ID_FREECAD_EMBEDWINDOW: + OnEmbedWidget(hWnd); + break; + default: + return DefWindowProc(hWnd, message, wParam, lParam); + } break; - case ID_FREECAD_NEWDOCUMENT: - OnNewDocument(hWnd); + case WM_PAINT: + hdc = BeginPaint(hWnd, &ps); + // TODO: Add any drawing code here... + EndPaint(hWnd, &ps); break; - case ID_FREECAD_EMBEDWINDOW: - OnEmbedWidget(hWnd); + case WM_DESTROY: + PostQuitMessage(0); break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - break; - case WM_PAINT: - hdc = BeginPaint(hWnd, &ps); - // TODO: Add any drawing code here... - EndPaint(hWnd, &ps); - break; - case WM_DESTROY: - PostQuitMessage(0); - break; - default: - return DefWindowProc(hWnd, message, wParam, lParam); - } - return 0; + default: + return DefWindowProc(hWnd, message, wParam, lParam); + } + return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { - UNREFERENCED_PARAMETER(lParam); - switch (message) - { - case WM_INITDIALOG: - return (INT_PTR)TRUE; + UNREFERENCED_PARAMETER(lParam); + switch (message) { + case WM_INITDIALOG: + return (INT_PTR)TRUE; - case WM_COMMAND: - if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) - { - EndDialog(hDlg, LOWORD(wParam)); - return (INT_PTR)TRUE; - } - break; - } - return (INT_PTR)FALSE; + case WM_COMMAND: + if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { + EndDialog(hDlg, LOWORD(wParam)); + return (INT_PTR)TRUE; + } + break; + } + return (INT_PTR)FALSE; } #include @@ -221,12 +218,12 @@ std::string OnFileOpen(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) ITEMIDLIST* pList = SHBrowseForFolder(&bi); if (pList) { - char szFolder[MAX_PATH+1]; + char szFolder[MAX_PATH + 1]; SHGetPathFromIDList(pList, szFolder); path = szFolder; LPMALLOC pMalloc; if (S_OK == SHGetMalloc(&pMalloc)) { - pMalloc->Free( pList ); + pMalloc->Free(pList); } } @@ -240,7 +237,7 @@ void OnLoadFreeCAD(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) Py_Initialize(); static int argc = 1; static wchar_t* app = L"CEmbed_FreeCADDlg"; - static wchar_t *argv[2] = {app,0}; + static wchar_t* argv[2] = {app, 0}; PySys_SetArgv(argc, argv); } @@ -283,8 +280,7 @@ void OnNewDocument(HWND hWnd) { PyObject* main = PyImport_AddModule("__main__"); PyObject* dict = PyModule_GetDict(main); - const char* cmd = - "FreeCAD.newDocument()\n"; + const char* cmd = "FreeCAD.newDocument()\n"; PyObject* result = PyRun_String(cmd, Py_file_input, dict, dict); if (result) { diff --git a/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.rc b/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.rc index db81690281..b6a947abb8 100644 --- a/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.rc +++ b/src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.rc @@ -41,7 +41,7 @@ IDI_SMALL ICON "small.ico" // Menu // -IDC_FREECAD_WIDGET MENU +IDC_FREECAD_WIDGET MENU BEGIN POPUP "&File" BEGIN @@ -65,7 +65,7 @@ END // Accelerator // -IDC_FREECAD_WIDGET ACCELERATORS +IDC_FREECAD_WIDGET ACCELERATORS BEGIN "?", IDM_ABOUT, ASCII, ALT "/", IDM_ABOUT, ASCII, ALT @@ -95,7 +95,7 @@ END // #ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO +GUIDELINES DESIGNINFO BEGIN IDD_ABOUTBOX, DIALOG BEGIN @@ -114,12 +114,12 @@ END // TEXTINCLUDE // -1 TEXTINCLUDE +1 TEXTINCLUDE BEGIN "resource.h\0" END -2 TEXTINCLUDE +2 TEXTINCLUDE BEGIN "#ifndef APSTUDIO_INVOKED\r\n" "#include ""targetver.h""\r\n" @@ -130,7 +130,7 @@ BEGIN "\0" END -3 TEXTINCLUDE +3 TEXTINCLUDE BEGIN "\r\n" "\0" @@ -144,7 +144,7 @@ END // String Table // -STRINGTABLE +STRINGTABLE BEGIN IDS_APP_TITLE "FreeCAD_widget" IDC_FREECAD_WIDGET "FREECAD_WIDGET" @@ -164,4 +164,3 @@ END ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED - diff --git a/src/Tools/embedded/Win32/FreeCAD_widget/resource.h b/src/Tools/embedded/Win32/FreeCAD_widget/resource.h index 7340994e22..335e7928e6 100644 --- a/src/Tools/embedded/Win32/FreeCAD_widget/resource.h +++ b/src/Tools/embedded/Win32/FreeCAD_widget/resource.h @@ -2,29 +2,29 @@ // Microsoft Visual C++ generated include file. // Used by FreeCAD_widget.rc // -#define IDC_MYICON 2 -#define IDD_FREECAD_WIDGET_DIALOG 102 -#define IDS_APP_TITLE 103 -#define IDD_ABOUTBOX 103 -#define IDM_ABOUT 104 -#define IDM_EXIT 105 -#define IDI_FREECAD_WIDGET 107 -#define IDI_SMALL 108 -#define IDC_FREECAD_WIDGET 109 -#define IDR_MAINFRAME 128 -#define ID_FREECAD_LOAD 32771 -#define ID_FREECAD_NEWDOCUMENT 32772 -#define ID_FREECAD_EMBEDWINDOW 32773 -#define IDC_STATIC -1 +#define IDC_MYICON 2 +#define IDD_FREECAD_WIDGET_DIALOG 102 +#define IDS_APP_TITLE 103 +#define IDD_ABOUTBOX 103 +#define IDM_ABOUT 104 +#define IDM_EXIT 105 +#define IDI_FREECAD_WIDGET 107 +#define IDI_SMALL 108 +#define IDC_FREECAD_WIDGET 109 +#define IDR_MAINFRAME 128 +#define ID_FREECAD_LOAD 32771 +#define ID_FREECAD_NEWDOCUMENT 32772 +#define ID_FREECAD_EMBEDWINDOW 32773 +#define IDC_STATIC -1 // Next default values for new objects -// +// #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_NEXT_RESOURCE_VALUE 129 -#define _APS_NEXT_COMMAND_VALUE 32774 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 110 +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 129 +#define _APS_NEXT_COMMAND_VALUE 32774 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 110 #endif #endif diff --git a/src/Tools/embedded/Win32/FreeCAD_widget/stdafx.h b/src/Tools/embedded/Win32/FreeCAD_widget/stdafx.h index de0dfa3cdb..ec5fdfca34 100644 --- a/src/Tools/embedded/Win32/FreeCAD_widget/stdafx.h +++ b/src/Tools/embedded/Win32/FreeCAD_widget/stdafx.h @@ -7,14 +7,14 @@ #include "targetver.h" -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#define WIN32_LEAN_AND_MEAN// Exclude rarely-used stuff from Windows headers // Windows Header Files: #include // C RunTime Header Files -#include #include #include +#include #include diff --git a/src/Tools/embedded/Win32/FreeCAD_widget/targetver.h b/src/Tools/embedded/Win32/FreeCAD_widget/targetver.h index f583181dfd..b7b02af3a2 100644 --- a/src/Tools/embedded/Win32/FreeCAD_widget/targetver.h +++ b/src/Tools/embedded/Win32/FreeCAD_widget/targetver.h @@ -1,24 +1,25 @@ #pragma once // The following macros define the minimum required platform. The minimum required platform -// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run -// your application. The macros work by enabling all features available on platform versions up to and -// including the version specified. +// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run +// your application. The macros work by enabling all features available on platform versions up to +// and including the version specified. // Modify the following defines if you have to target a platform prior to the ones specified below. // Refer to MSDN for the latest info on corresponding values for different platforms. -#ifndef WINVER // Specifies that the minimum required platform is Windows Vista. -#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows. +#ifndef WINVER // Specifies that the minimum required platform is Windows Vista. +#define WINVER 0x0600// Change this to the appropriate value to target other versions of Windows. #endif -#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista. -#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows. +#ifndef _WIN32_WINNT// Specifies that the minimum required platform is Windows Vista. +#define _WIN32_WINNT \ + 0x0600// Change this to the appropriate value to target other versions of Windows. #endif -#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98. -#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later. +#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98. +#define _WIN32_WINDOWS 0x0410// Change this to the appropriate value to target Windows Me or later. #endif -#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0. -#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE. +#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0. +#define _WIN32_IE 0x0700// Change this to the appropriate value to target other versions of IE. #endif diff --git a/src/Tools/embedded/glib/main.c b/src/Tools/embedded/glib/main.c index 48bf601e73..0bfd1bff75 100644 --- a/src/Tools/embedded/glib/main.c +++ b/src/Tools/embedded/glib/main.c @@ -1,17 +1,21 @@ -#include -#include #include +#include +#include -static void helloWorld (GtkWidget *wid, GtkWidget *win) +static void helloWorld(GtkWidget* wid, GtkWidget* win) { PyObject* mmod = PyImport_AddModule("__main__"); PyObject* dict = PyModule_GetDict(mmod); PyRun_String("import sys\n" "sys.path.append(\"/home/werner/FreeCAD/lib\")", - Py_file_input, dict, dict); + Py_file_input, + dict, + dict); PyObject* result = PyRun_String("import FreeCADGui\n" "FreeCADGui.showMainWindow()", - Py_file_input, dict, dict); + Py_file_input, + dict, + dict); if (result) { Py_DECREF(result); } @@ -21,69 +25,70 @@ static void helloWorld (GtkWidget *wid, GtkWidget *win) PyObject* pystring = PyObject_Str(pvalue); const char* error = PyUnicode_AsUTF8(pystring); - GtkWidget *dialog = NULL; - dialog = gtk_message_dialog_new (GTK_WINDOW (win), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "%s", error); - gtk_window_set_position (GTK_WINDOW (dialog), GTK_WIN_POS_CENTER); - gtk_dialog_run (GTK_DIALOG (dialog)); - gtk_widget_destroy (dialog); + GtkWidget* dialog = NULL; + dialog = gtk_message_dialog_new( + GTK_WINDOW(win), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE, "%s", error); + gtk_window_set_position(GTK_WINDOW(dialog), GTK_WIN_POS_CENTER); + gtk_dialog_run(GTK_DIALOG(dialog)); + gtk_widget_destroy(dialog); Py_DECREF(pystring); } Py_DECREF(dict); } -int main (int argc, char *argv[]) +int main(int argc, char* argv[]) { - GtkWidget *button = NULL; - GtkWidget *win = NULL; - GtkWidget *vbox = NULL; + GtkWidget* button = NULL; + GtkWidget* win = NULL; + GtkWidget* vbox = NULL; - /* Init Python */ - wchar_t *program = Py_DecodeLocale(argv[0], NULL); - if (program == NULL) { - fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); - exit(1); - } + /* Init Python */ + wchar_t* program = Py_DecodeLocale(argv[0], NULL); + if (program == NULL) { + fprintf(stderr, "Fatal error: cannot decode argv[0]\n"); + exit(1); + } - Py_SetProgramName(program); - Py_Initialize(); - PyEval_InitThreads(); + Py_SetProgramName(program); + Py_Initialize(); + PyEval_InitThreads(); - wchar_t *args[argc]; - for (int i = 0; i < argc; i++) { - args[i] = Py_DecodeLocale(argv[i], NULL); - } - PySys_SetArgv(argc, args); + wchar_t* args[argc]; + for (int i = 0; i < argc; i++) { + args[i] = Py_DecodeLocale(argv[i], NULL); + } + PySys_SetArgv(argc, args); - /* Initialize GTK+ */ - g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING, (GLogFunc) gtk_false, NULL); - gtk_init (&argc, &argv); - g_log_set_handler ("Gtk", G_LOG_LEVEL_WARNING, g_log_default_handler, NULL); + /* Initialize GTK+ */ + g_log_set_handler("Gtk", G_LOG_LEVEL_WARNING, (GLogFunc)gtk_false, NULL); + gtk_init(&argc, &argv); + g_log_set_handler("Gtk", G_LOG_LEVEL_WARNING, g_log_default_handler, NULL); - /* Create the main window */ - win = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_container_set_border_width (GTK_CONTAINER (win), 8); - gtk_window_set_title (GTK_WINDOW (win), "Hello World"); - gtk_window_set_position (GTK_WINDOW (win), GTK_WIN_POS_CENTER); - gtk_widget_realize (win); - g_signal_connect (win, "destroy", gtk_main_quit, NULL); + /* Create the main window */ + win = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_container_set_border_width(GTK_CONTAINER(win), 8); + gtk_window_set_title(GTK_WINDOW(win), "Hello World"); + gtk_window_set_position(GTK_WINDOW(win), GTK_WIN_POS_CENTER); + gtk_widget_realize(win); + g_signal_connect(win, "destroy", gtk_main_quit, NULL); - /* Create a vertical box with buttons */ - vbox = gtk_box_new (TRUE, 6); - gtk_container_add (GTK_CONTAINER (win), vbox); + /* Create a vertical box with buttons */ + vbox = gtk_box_new(TRUE, 6); + gtk_container_add(GTK_CONTAINER(win), vbox); - button = gtk_button_new_from_icon_name ("document-open", GTK_ICON_SIZE_BUTTON); - gtk_button_set_label((GtkButton*)button, "Load module"); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (helloWorld), (gpointer) win); - gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0); + button = gtk_button_new_from_icon_name("document-open", GTK_ICON_SIZE_BUTTON); + gtk_button_set_label((GtkButton*)button, "Load module"); + g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(helloWorld), (gpointer)win); + gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 0); - button = gtk_button_new_from_icon_name ("window-close", GTK_ICON_SIZE_BUTTON); - gtk_button_set_label((GtkButton*)button, "Close"); - g_signal_connect (button, "clicked", gtk_main_quit, NULL); - gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0); + button = gtk_button_new_from_icon_name("window-close", GTK_ICON_SIZE_BUTTON); + gtk_button_set_label((GtkButton*)button, "Close"); + g_signal_connect(button, "clicked", gtk_main_quit, NULL); + gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 0); - /* Enter the main loop */ - gtk_widget_show_all (win); - gtk_main (); - return 0; + /* Enter the main loop */ + gtk_widget_show_all(win); + gtk_main(); + return 0; } diff --git a/src/Tools/examplePy2wiki.py b/src/Tools/examplePy2wiki.py index 7edf31683d..f4cb678fd7 100644 --- a/src/Tools/examplePy2wiki.py +++ b/src/Tools/examplePy2wiki.py @@ -4,15 +4,15 @@ Usage = """examplePy2wiki - generating a wiki text out of a python example Usage: - examplePy2wiki [Optionen] - + examplePy2wiki [Optionen] + Options: -o --out-file=FILENAME use this file name for output, default resources.qrc -i, --in-file=FILENAME directory to search, default PWD -h, --help print this help message - + This program reads python files and generate a output suited for a Mediawiki page. -The python comments get translated to text and the code blocks get intended to +The python comments get translated to text and the code blocks get intended to show up us code in the wiki. @@ -25,20 +25,22 @@ Version: 0.1 """ -import os,sys,string,getopt +import os, sys, string, getopt + def Process(line): - if(line[0:2]=='# '): + if line[0:2] == "# ": return line[2:] else: - return ' '+line - - + return " " + line + def main(): try: - opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["help", "verbose", "in-file=","out-file="]) + opts, args = getopt.getopt( + sys.argv[1:], "hi:o:", ["help", "verbose", "in-file=", "out-file="] + ) except getopt.GetoptError: # print help information and exit: sys.stderr.write(Usage) @@ -50,15 +52,15 @@ def main(): sys.stderr.write(Usage) sys.exit() if o in ("-o", "--out-file"): - outfile = open(a,'w') + outfile = open(a, "w") if o in ("-i", "--in-file"): - infile = open(a,'r') - + infile = open(a, "r") lines = infile.readlines() for l in lines: outfile.write(Process(l)) - #print l - + # print l + + if __name__ == "__main__": main() diff --git a/src/Tools/fcbt.py b/src/Tools/fcbt.py index c8b2fc22f9..73496fc924 100644 --- a/src/Tools/fcbt.py +++ b/src/Tools/fcbt.py @@ -15,7 +15,7 @@ possible commands are: - DistSetup (DI) Build a Setup Distr. of the current source tree - DistSetup (DUI) Build a User Setup Distr. of the current source tree - DistAll (DA) Run all three above modules - - NextBuildNumber (NBN) Increase the Build Number of this Version + - NextBuildNumber (NBN) Increase the Build Number of this Version - CreateModule (CM) Insert a new FreeCAD Module in the module directory - CreatePyModule (CP) Insert a new FreeCAD Python Module in the module directory @@ -24,18 +24,18 @@ For help on the modules type: """ -if(len(sys.argv) < 2): +if len(sys.argv) < 2: sys.stdout.write(help1) sys.stdout.write("Insert command: ") sys.stdout.flush() CmdRaw = sys.stdin.readline()[:-1] else: CmdRaw = sys.argv[1] - + Cmd = CmdRaw.lower() -if Cmd == "distsrc" or Cmd == "ds" : +if Cmd == "distsrc" or Cmd == "ds": import fcbt.DistSrc elif Cmd == "distbin" or Cmd == "db": import fcbt.DistBin @@ -58,4 +58,3 @@ elif Cmd == "?" or Cmd == "help" or Cmd == "/h" or Cmd == "/?" or Cmd == "-h" or else: print(CmdRaw + " is an unknown command!\n") sys.exit(1) - diff --git a/src/Tools/fcbt/BuildDoc.py b/src/Tools/fcbt/BuildDoc.py index 71e2a9c519..5e4ac0f0eb 100644 --- a/src/Tools/fcbt/BuildDoc.py +++ b/src/Tools/fcbt/BuildDoc.py @@ -1,10 +1,9 @@ - - # shell and operating system -import os,sys,FileTools -#sys.path.append( "..\Tools" ) +import os, sys, FileTools -#import FileTools +# sys.path.append( "..\Tools" ) + +# import FileTools # line separator ls = os.linesep @@ -13,21 +12,21 @@ ps = os.pathsep # dir separator ds = os.sep -#==================================================================== +# ==================================================================== # script assumes to run in src/Doc -#os.chdir("e:/Develop/FreeCADWin/src/Doc") -LogFile = open("MakeDoc.log",'w') +# os.chdir("e:/Develop/FreeCADWin/src/Doc") +LogFile = open("MakeDoc.log", "w") if not os.path.isdir("../../doc"): os.mkdir("../../doc") -#if not os.path.isdir("../../Doc/res"): +# if not os.path.isdir("../../Doc/res"): # os.mkdir("../../Doc/res") -#FileTools.cpfile("index.html","../../doc/index.html") -#FileTools.cpfile("FreeCAD.css","../../doc/res/FreeCAD.css") +# FileTools.cpfile("index.html","../../doc/index.html") +# FileTools.cpfile("FreeCAD.css","../../doc/res/FreeCAD.css") -#==================================================================== -sys.stdout.write ('Running source documentation ...') +# ==================================================================== +sys.stdout.write("Running source documentation ...") # running doxygen with the parameters from the config file -param = "doxygen fcbt"+ds+"BuildDocDoxy.cfg" +param = "doxygen fcbt" + ds + "BuildDocDoxy.cfg" LogFile.write(param) print(param) text = os.popen(param).read() @@ -35,9 +34,9 @@ LogFile.write(text) if not os.path.isdir("../../doc/SourceDocumentation"): os.mkdir("../../doc/SourceDocumentation") -#==================================================================== -sys.stdout.write( ' done\n Generate HTML ...') -FileTools.cpall("html","../../doc/SourceDocumentation") +# ==================================================================== +sys.stdout.write(" done\n Generate HTML ...") +FileTools.cpall("html", "../../doc/SourceDocumentation") """ #==================================================================== @@ -146,13 +145,11 @@ FileTools.cpall("Online","../../Doc/Online") sys.stdout.write (' done\n Clean up temporary files ...') LogFile.close() """ -#==================================================================== +# ==================================================================== FileTools.rmall("html") -#==================================================================== -sys.stdout.write (' done\nDocumentation done!\n') +# ==================================================================== +sys.stdout.write(" done\nDocumentation done!\n") - - -#print text +# print text diff --git a/src/Tools/fcbt/BuildDocDoxy.cfg b/src/Tools/fcbt/BuildDocDoxy.cfg index 14a4ea7d9e..737e95a478 100644 --- a/src/Tools/fcbt/BuildDocDoxy.cfg +++ b/src/Tools/fcbt/BuildDocDoxy.cfg @@ -3,21 +3,21 @@ #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- -HAVE_DOT = YES -PROJECT_NAME = -PROJECT_NUMBER = -OUTPUT_DIRECTORY = +HAVE_DOT = YES +PROJECT_NAME = +PROJECT_NUMBER = +OUTPUT_DIRECTORY = CREATE_SUBDIRS = YES OUTPUT_LANGUAGE = English USE_WINDOWS_ENCODING = YES BRIEF_MEMBER_DESC = YES REPEAT_BRIEF = YES -ABBREVIATE_BRIEF = +ABBREVIATE_BRIEF = ALWAYS_DETAILED_SEC = YES INLINE_INHERITED_MEMB = NO FULL_PATH_NAMES = NO -STRIP_FROM_PATH = -STRIP_FROM_INC_PATH = +STRIP_FROM_PATH = +STRIP_FROM_INC_PATH = SHORT_NAMES = NO JAVADOC_AUTOBRIEF = NO MULTILINE_CPP_IS_BRIEF = NO @@ -25,7 +25,7 @@ DETAILS_AT_TOP = NO INHERIT_DOCS = YES DISTRIBUTE_GROUP_DOC = NO TAB_SIZE = 8 -ALIASES = +ALIASES = OPTIMIZE_OUTPUT_FOR_C = NO OPTIMIZE_OUTPUT_JAVA = NO SUBGROUPING = YES @@ -63,8 +63,8 @@ QUIET = YES WARNINGS = YES WARN_IF_UNDOCUMENTED = NO WARN_IF_DOC_ERROR = YES -WARN_FORMAT = -WARN_LOGFILE = +WARN_FORMAT = +WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- @@ -72,22 +72,22 @@ INPUT = ../Gui \ ../App \ ../Base \ ../Tools \ - ../Mod/Mesh + ../Mod/Mesh FILE_PATTERNS = *.h \ *.cpp \ *.py RECURSIVE = YES -EXCLUDE = +EXCLUDE = EXCLUDE_SYMLINKS = NO EXCLUDE_PATTERNS = *.moc.* \ moc_* \ *.ui.h -EXAMPLE_PATH = -EXAMPLE_PATTERNS = +EXAMPLE_PATH = +EXAMPLE_PATTERNS = EXAMPLE_RECURSIVE = NO -IMAGE_PATH = -INPUT_FILTER = -FILTER_PATTERNS = +IMAGE_PATH = +INPUT_FILTER = +FILTER_PATTERNS = FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing @@ -103,20 +103,20 @@ VERBATIM_HEADERS = NO #--------------------------------------------------------------------------- ALPHABETICAL_INDEX = NO COLS_IN_ALPHA_INDEX = 5 -IGNORE_PREFIX = +IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- GENERATE_HTML = YES -HTML_OUTPUT = +HTML_OUTPUT = HTML_FILE_EXTENSION = .html -HTML_HEADER = -HTML_FOOTER = -HTML_STYLESHEET = +HTML_HEADER = +HTML_FOOTER = +HTML_STYLESHEET = HTML_ALIGN_MEMBERS = YES GENERATE_HTMLHELP = YES -CHM_FILE = -HHC_LOCATION = +CHM_FILE = +HHC_LOCATION = GENERATE_CHI = NO BINARY_TOC = NO TOC_EXPAND = NO @@ -128,13 +128,13 @@ TREEVIEW_WIDTH = 250 # configuration options related to the LaTeX output #--------------------------------------------------------------------------- GENERATE_LATEX = NO -LATEX_OUTPUT = +LATEX_OUTPUT = LATEX_CMD_NAME = latex MAKEINDEX_CMD_NAME = makeindex COMPACT_LATEX = NO PAPER_TYPE = a4wide -EXTRA_PACKAGES = -LATEX_HEADER = +EXTRA_PACKAGES = +LATEX_HEADER = PDF_HYPERLINKS = NO USE_PDFLATEX = NO LATEX_BATCHMODE = NO @@ -143,25 +143,25 @@ LATEX_HIDE_INDICES = NO # configuration options related to the RTF output #--------------------------------------------------------------------------- GENERATE_RTF = NO -RTF_OUTPUT = +RTF_OUTPUT = COMPACT_RTF = NO RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -RTF_EXTENSIONS_FILE = +RTF_STYLESHEET_FILE = +RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- GENERATE_MAN = NO -MAN_OUTPUT = -MAN_EXTENSION = +MAN_OUTPUT = +MAN_EXTENSION = MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- GENERATE_XML = NO XML_OUTPUT = xml -XML_SCHEMA = -XML_DTD = +XML_SCHEMA = +XML_DTD = XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output @@ -173,29 +173,29 @@ GENERATE_AUTOGEN_DEF = NO GENERATE_PERLMOD = NO PERLMOD_LATEX = NO PERLMOD_PRETTY = YES -PERLMOD_MAKEVAR_PREFIX = +PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- -# Configuration options related to the preprocessor +# Configuration options related to the preprocessor #--------------------------------------------------------------------------- ENABLE_PREPROCESSING = YES MACRO_EXPANSION = YES EXPAND_ONLY_PREDEF = NO SEARCH_INCLUDES = YES -INCLUDE_PATH = -INCLUDE_FILE_PATTERNS = -PREDEFINED = -EXPAND_AS_DEFINED = +INCLUDE_PATH = +INCLUDE_FILE_PATTERNS = +PREDEFINED = +EXPAND_AS_DEFINED = SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- -# Configuration::additions related to external references +# Configuration::additions related to external references #--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = +TAGFILES = +GENERATE_TAGFILE = ALLEXTERNALS = NO EXTERNAL_GROUPS = YES -PERL_PATH = +PERL_PATH = #--------------------------------------------------------------------------- -# Configuration options related to the dot tool +# Configuration options related to the dot tool #--------------------------------------------------------------------------- CLASS_DIAGRAMS = YES HIDE_UNDOC_RELATIONS = YES @@ -209,14 +209,14 @@ INCLUDED_BY_GRAPH = YES CALL_GRAPH = NO GRAPHICAL_HIERARCHY = YES DOT_IMAGE_FORMAT = png -DOT_PATH = -DOTFILE_DIRS = +DOT_PATH = +DOTFILE_DIRS = MAX_DOT_GRAPH_WIDTH = 1024 MAX_DOT_GRAPH_HEIGHT = 1024 MAX_DOT_GRAPH_DEPTH = 0 GENERATE_LEGEND = YES DOT_CLEANUP = YES #--------------------------------------------------------------------------- -# Configuration::additions related to the search engine +# Configuration::additions related to the search engine #--------------------------------------------------------------------------- SEARCHENGINE = NO diff --git a/src/Tools/fcbt/CreateModule.py b/src/Tools/fcbt/CreateModule.py index 7dd00d7d29..1710bbacac 100644 --- a/src/Tools/fcbt/CreateModule.py +++ b/src/Tools/fcbt/CreateModule.py @@ -3,65 +3,70 @@ # # Creates a new application -#*************************************************************************** -#* (c) Werner Mayer (werner.wm.mayer@gmx.de) 2003 * -#* * -#* This file is part of the FreeCAD CAx development system. * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* FreeCAD is distributed in the hope that it will be useful, * -#* but WITHOUT ANY WARRANTY; without even the implied warranty of * -#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -#* GNU Lesser General Public License for more details. * -#* * -#* You should have received a copy of the GNU Library General Public * -#* License along with FreeCAD; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#* Werner Mayer 2003 * -#*************************************************************************** +# *************************************************************************** +# * (c) Werner Mayer (werner.wm.mayer@gmx.de) 2003 * +# * * +# * This file is part of the FreeCAD CAx development system. * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * FreeCAD is distributed in the hope that it will be useful, * +# * but WITHOUT ANY WARRANTY; without even the implied warranty of * +# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +# * GNU Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Library General Public * +# * License along with FreeCAD; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# * Werner Mayer 2003 * +# *************************************************************************** -import os,sys +import os, sys import MakeAppTools import re -FilFilter = ["^.*\\.o$", - "^.*Makefile$", - "^.*\\.la$", - "^.*\\.lo$", - "^.*\\.positions$", - "^.*\\.aux$", - "^.*\\.bsc$", - "^.*\\.exp$", - "^.*\\.ilg$", - "^.*\\.ilk$", - "^.*\\.in$", - "^.*\\.mak$", - "^.*\\.ncb$", - "^.*\\.opt$", - "^.*\\.pyc$", - "^.*\\.pyd$", - "^.*\\.pdb$", - "^.*\\.plg$"] +FilFilter = [ + "^.*\\.o$", + "^.*Makefile$", + "^.*\\.la$", + "^.*\\.lo$", + "^.*\\.positions$", + "^.*\\.aux$", + "^.*\\.bsc$", + "^.*\\.exp$", + "^.*\\.ilg$", + "^.*\\.ilk$", + "^.*\\.in$", + "^.*\\.mak$", + "^.*\\.ncb$", + "^.*\\.opt$", + "^.*\\.pyc$", + "^.*\\.pyd$", + "^.*\\.pdb$", + "^.*\\.plg$", +] + +DirFilter = [ + "^.*\\.o$", + "^Debug$", + "^DebugCmd$", + "^DebugPy$", + "^Release$", + "^ReleaseCmd$", + "^ReleasePy$", + "^Attic$", + "^CVS$", + "^\\.svn$", + "^\\.deps$", + "^\\.libs$", +] -DirFilter = ["^.*\\.o$", - "^Debug$", - "^DebugCmd$", - "^DebugPy$", - "^Release$", - "^ReleaseCmd$", - "^ReleasePy$", - "^Attic$", - "^CVS$", - "^\\.svn$", - "^\\.deps$", - "^\\.libs$"] def SetupFilter(MatchList): RegList = [] @@ -76,44 +81,56 @@ def createApp(Application): Create a new application by copying the template """ # create directory ../Mod/ - if not os.path.isdir("../Mod/"+Application): - os.mkdir("../Mod/"+Application) + if not os.path.isdir("../Mod/" + Application): + os.mkdir("../Mod/" + Application) else: sys.stdout.write(Application + " already exists. Please enter another name.\n") sys.exit() - # copying files from _TEMPLATE_ to ../Mod/ sys.stdout.write("Copying files...") - MakeAppTools.copyTemplate("_TEMPLATE_","../Mod/"+Application,"_TEMPLATE_", Application, SetupFilter(FilFilter),SetupFilter(DirFilter)) + MakeAppTools.copyTemplate( + "_TEMPLATE_", + "../Mod/" + Application, + "_TEMPLATE_", + Application, + SetupFilter(FilFilter), + SetupFilter(DirFilter), + ) sys.stdout.write("Ok\n") # replace the _TEMPLATE_ string by sys.stdout.write("Modifying files...\n") - MakeAppTools.replaceTemplate("../Mod/" + Application,"_TEMPLATE_",Application) - MakeAppTools.replaceTemplate("../Mod/" + Application,"${CMAKE_SOURCE_DIR}/src/Tools/","${CMAKE_SOURCE_DIR}/src/Mod/") + MakeAppTools.replaceTemplate("../Mod/" + Application, "_TEMPLATE_", Application) + MakeAppTools.replaceTemplate( + "../Mod/" + Application, + "${CMAKE_SOURCE_DIR}/src/Tools/", + "${CMAKE_SOURCE_DIR}/src/Mod/", + ) # make the configure script executable - #os.chmod("../Mod/" + Application + "/configure", 0777); + # os.chmod("../Mod/" + Application + "/configure", 0777); sys.stdout.write("Modifying files done.\n") sys.stdout.write(Application + " module created successfully.\n") + def validateApp(AppName): """ - Validates the class name + Validates the class name """ - if(len(AppName) < 2): - sys.stdout.write("Too short name: '"+AppName+"'\n") + if len(AppName) < 2: + sys.stdout.write("Too short name: '" + AppName + "'\n") sys.exit() # name is long enough - clName="class "+AppName+": self=0" + clName = "class " + AppName + ": self=0" try: exec(clName) except Exception: # Invalid class name - sys.stdout.write("Invalid name: '"+AppName+"'\n") + sys.stdout.write("Invalid name: '" + AppName + "'\n") sys.exit() + sys.stdout.write("Please enter a name for your application:") sys.stdout.flush() AppName = sys.stdin.readline()[:-1] diff --git a/src/Tools/fcbt/CreatePyModule.py b/src/Tools/fcbt/CreatePyModule.py index c47c9137ae..4ff1b697b5 100644 --- a/src/Tools/fcbt/CreatePyModule.py +++ b/src/Tools/fcbt/CreatePyModule.py @@ -1,64 +1,69 @@ -#*************************************************************************** -#* Copyright (c) 2003 Werner Mayer * -#* * -#* This file is part of the FreeCAD CAx development system. * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* FreeCAD is distributed in the hope that it will be useful, * -#* but WITHOUT ANY WARRANTY; without even the implied warranty of * -#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -#* GNU Lesser General Public License for more details. * -#* * -#* You should have received a copy of the GNU Library General Public * -#* License along with FreeCAD; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * Copyright (c) 2003 Werner Mayer * +# * * +# * This file is part of the FreeCAD CAx development system. * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * FreeCAD is distributed in the hope that it will be useful, * +# * but WITHOUT ANY WARRANTY; without even the implied warranty of * +# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +# * GNU Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Library General Public * +# * License along with FreeCAD; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** # FreeCAD MakeNewBuildNbr script # Creates a new application -import os,sys +import os, sys import MakeAppTools import re -FilFilter = ["^.*\\.o$", - "^.*Makefile$", - "^.*\\.la$", - "^.*\\.lo$", - "^.*\\.positions$", - "^.*\\.aux$", - "^.*\\.bsc$", - "^.*\\.exp$", - "^.*\\.ilg$", - "^.*\\.ilk$", - "^.*\\.in$", - "^.*\\.mak$", - "^.*\\.ncb$", - "^.*\\.opt$", - "^.*\\.pyc$", - "^.*\\.pyd$", - "^.*\\.pdb$", - "^.*\\.plg$"] +FilFilter = [ + "^.*\\.o$", + "^.*Makefile$", + "^.*\\.la$", + "^.*\\.lo$", + "^.*\\.positions$", + "^.*\\.aux$", + "^.*\\.bsc$", + "^.*\\.exp$", + "^.*\\.ilg$", + "^.*\\.ilk$", + "^.*\\.in$", + "^.*\\.mak$", + "^.*\\.ncb$", + "^.*\\.opt$", + "^.*\\.pyc$", + "^.*\\.pyd$", + "^.*\\.pdb$", + "^.*\\.plg$", +] + +DirFilter = [ + "^.*\\.o$", + "^Debug$", + "^DebugCmd$", + "^DebugPy$", + "^Release$", + "^ReleaseCmd$", + "^ReleasePy$", + "^Attic$", + "^CVS$", + "^\\.svn$", + "^\\.deps$", + "^\\.libs$", +] -DirFilter = ["^.*\\.o$", - "^Debug$", - "^DebugCmd$", - "^DebugPy$", - "^Release$", - "^ReleaseCmd$", - "^ReleasePy$", - "^Attic$", - "^CVS$", - "^\\.svn$", - "^\\.deps$", - "^\\.libs$"] def SetupFilter(MatchList): RegList = [] @@ -73,44 +78,56 @@ def createApp(Application): Create a new application by copying the template """ # create directory ../Mod/ - if not os.path.isdir("../Mod/"+Application): - os.mkdir("../Mod/"+Application) + if not os.path.isdir("../Mod/" + Application): + os.mkdir("../Mod/" + Application) else: sys.stdout.write(Application + " already exists. Please enter another name.\n") sys.exit() - # copying files from _TEMPLATEPY_ to ../Mod/ sys.stdout.write("Copying files...") - MakeAppTools.copyTemplate("_TEMPLATEPY_","../Mod/"+Application,"_TEMPLATEPY_", Application, SetupFilter(FilFilter),SetupFilter(DirFilter)) + MakeAppTools.copyTemplate( + "_TEMPLATEPY_", + "../Mod/" + Application, + "_TEMPLATEPY_", + Application, + SetupFilter(FilFilter), + SetupFilter(DirFilter), + ) sys.stdout.write("Ok\n") # replace the _TEMPLATEPY_ string by sys.stdout.write("Modifying files...\n") - MakeAppTools.replaceTemplate("../Mod/" + Application,"_TEMPLATEPY_",Application) - MakeAppTools.replaceTemplate("../Mod/" + Application,"${CMAKE_SOURCE_DIR}/src/Tools/","${CMAKE_SOURCE_DIR}/src/Mod/") + MakeAppTools.replaceTemplate("../Mod/" + Application, "_TEMPLATEPY_", Application) + MakeAppTools.replaceTemplate( + "../Mod/" + Application, + "${CMAKE_SOURCE_DIR}/src/Tools/", + "${CMAKE_SOURCE_DIR}/src/Mod/", + ) # make the configure script executable - #os.chmod("../Mod/" + Application + "/configure", 0777); + # os.chmod("../Mod/" + Application + "/configure", 0777); sys.stdout.write("Modifying files done.\n") sys.stdout.write(Application + " module created successfully.\n") + def validateApp(AppName): """ Validates the class name """ - if(len(AppName) < 2): - sys.stdout.write("Too short name: '"+AppName+"'\n") + if len(AppName) < 2: + sys.stdout.write("Too short name: '" + AppName + "'\n") sys.exit() # name is long enough - clName="class "+AppName+": self=0" + clName = "class " + AppName + ": self=0" try: exec(clName) except Exception: # Invalid class name - sys.stdout.write("Invalid name: '"+AppName+"'\n") + sys.stdout.write("Invalid name: '" + AppName + "'\n") sys.exit() + sys.stdout.write("Please enter a name for your application:") sys.stdout.flush() AppName = sys.stdin.readline()[:-1] diff --git a/src/Tools/fcbt/DistBin.py b/src/Tools/fcbt/DistBin.py index 94bc13e7f4..1785c42d46 100644 --- a/src/Tools/fcbt/DistBin.py +++ b/src/Tools/fcbt/DistBin.py @@ -1,8 +1,7 @@ - - # shell and operating system -import os,sys -#sys.path.append( "E:\\Develop\\Projekte\\FreeCADWin\\src\\Tools" ) +import os, sys + +# sys.path.append( "E:\\Develop\\Projekte\\FreeCADWin\\src\\Tools" ) from . import DistTools, FileTools @@ -15,48 +14,58 @@ ds = os.sep DistName = DistTools.BuildDistName() -DistBin = DistName + "_binary_WinX86" -DistDir = "../../DistTemp/" +DistBin = DistName + "_binary_WinX86" +DistDir = "../../DistTemp/" -#==================================================================== +# ==================================================================== # script assumes to run in src/Tools DistTools.EnsureDir(DistDir) -if (DistTools.EnsureDir(DistDir+DistBin) == 1): +if DistTools.EnsureDir(DistDir + DistBin) == 1: raise RuntimeError("Dist path already there!!") -#==================================================================== +# ==================================================================== # copy src -sys.stdout.write( 'Copy src Tree ...\n') -DistTools.EnsureDir(DistDir+DistBin+'/src') -FileTools.cpallWithFilter('../../src',DistDir+DistBin+'/src',FileTools.SetUpFilter(DistTools.SrcFilter)) +sys.stdout.write("Copy src Tree ...\n") +DistTools.EnsureDir(DistDir + DistBin + "/src") +FileTools.cpallWithFilter( + "../../src", DistDir + DistBin + "/src", FileTools.SetUpFilter(DistTools.SrcFilter) +) -#==================================================================== +# ==================================================================== # copy bin and lib -sys.stdout.write( 'Copy bin and lib Tree ...\n') -DistTools.EnsureDir(DistDir+DistBin+'/bin') -FileTools.cpallWithFilter('../../bin',DistDir+DistBin+'/bin',FileTools.SetUpFilter(DistTools.BinFilter)) -DistTools.EnsureDir(DistDir+DistBin+'/lib') -FileTools.cpallWithFilter('../../lib',DistDir+DistBin+'/lib',FileTools.SetUpFilter(DistTools.LibFilter)) +sys.stdout.write("Copy bin and lib Tree ...\n") +DistTools.EnsureDir(DistDir + DistBin + "/bin") +FileTools.cpallWithFilter( + "../../bin", DistDir + DistBin + "/bin", FileTools.SetUpFilter(DistTools.BinFilter) +) +DistTools.EnsureDir(DistDir + DistBin + "/lib") +FileTools.cpallWithFilter( + "../../lib", DistDir + DistBin + "/lib", FileTools.SetUpFilter(DistTools.LibFilter) +) -#==================================================================== +# ==================================================================== # copy Modules -sys.stdout.write( 'Copy module Tree ...\n') -DistTools.EnsureDir(DistDir+DistBin+'/Mod') -FileTools.cpallWithFilter('../../src/Mod',DistDir+DistBin+'/Mod',FileTools.SetUpFilter(DistTools.ModFilter)) +sys.stdout.write("Copy module Tree ...\n") +DistTools.EnsureDir(DistDir + DistBin + "/Mod") +FileTools.cpallWithFilter( + "../../src/Mod", + DistDir + DistBin + "/Mod", + FileTools.SetUpFilter(DistTools.ModFilter), +) -#==================================================================== +# ==================================================================== # copy top level files -#FileTools.cpfile("../Doc/README.html",DistDir+DistBin+"/README.html") -#FileTools.cpfile("../Doc/INSTALL.html",DistDir+DistBin+"/INSTALL.html") -#FileTools.cpfile("../Doc/LICENSE.GPL.html",DistDir+DistBin+"/LICENSE.GPL.html") -#FileTools.cpfile("../Doc/LICENSE.LGPL.html",DistDir+DistBin+"/LICENSE.LGPL.html") -#DistTools.cpfile("../Tools/BuildTool.py",DistDir+DistBin+"/BuildTool.py") +# FileTools.cpfile("../Doc/README.html",DistDir+DistBin+"/README.html") +# FileTools.cpfile("../Doc/INSTALL.html",DistDir+DistBin+"/INSTALL.html") +# FileTools.cpfile("../Doc/LICENSE.GPL.html",DistDir+DistBin+"/LICENSE.GPL.html") +# FileTools.cpfile("../Doc/LICENSE.LGPL.html",DistDir+DistBin+"/LICENSE.LGPL.html") +# DistTools.cpfile("../Tools/BuildTool.py",DistDir+DistBin+"/BuildTool.py") -#==================================================================== +# ==================================================================== # zipping an archive -#os.popen("rar.exe a "+DistDir+DistBin+".rar "+ DistDir+DistBin) -os.popen("7z a -tzip "+DistDir+DistBin+".zip "+ DistDir+DistBin+ " -mx9") +# os.popen("rar.exe a "+DistDir+DistBin+".rar "+ DistDir+DistBin) +os.popen("7z a -tzip " + DistDir + DistBin + ".zip " + DistDir + DistBin + " -mx9") -FileTools.rmall(DistDir+DistBin) +FileTools.rmall(DistDir + DistBin) diff --git a/src/Tools/fcbt/DistSetup.py b/src/Tools/fcbt/DistSetup.py index 2085caef14..2acd816c16 100644 --- a/src/Tools/fcbt/DistSetup.py +++ b/src/Tools/fcbt/DistSetup.py @@ -1,13 +1,11 @@ - -from . import DistTools,FileTools +from . import DistTools, FileTools DistName = DistTools.BuildDistName() -DistInst = DistName + "_installer.msi" -DistDir = "../../DistTemp/" +DistInst = DistName + "_installer.msi" +DistDir = "../../DistTemp/" -#==================================================================== +# ==================================================================== # copy installer file -FileTools.cpfile("../../Install/FreeCAD.msi",DistDir+DistInst) - +FileTools.cpfile("../../Install/FreeCAD.msi", DistDir + DistInst) diff --git a/src/Tools/fcbt/DistSrc.py b/src/Tools/fcbt/DistSrc.py index ccbfd6c36c..9786b05f2c 100644 --- a/src/Tools/fcbt/DistSrc.py +++ b/src/Tools/fcbt/DistSrc.py @@ -1,12 +1,11 @@ - - # shell and operating system -import os,sys -#sys.path.append( "E:\\Develop\\Projekte\\FreeCADWin\\src\\Tools" ) +import os, sys + +# sys.path.append( "E:\\Develop\\Projekte\\FreeCADWin\\src\\Tools" ) from . import DistTools, FileTools -# line separator +# line separator ls = os.linesep # path separator ps = os.pathsep @@ -15,34 +14,35 @@ ds = os.sep DistName = DistTools.BuildDistName() -DistSrc = DistName + "_src" -DistDir = "../../DistTemp/" +DistSrc = DistName + "_src" +DistDir = "../../DistTemp/" -#==================================================================== +# ==================================================================== # script assumes to run in src/Tools DistTools.EnsureDir(DistDir) -if (DistTools.EnsureDir(DistDir+DistSrc) == 1): +if DistTools.EnsureDir(DistDir + DistSrc) == 1: raise RuntimeError("Dist path already there!!") -#==================================================================== -# copy src -sys.stdout.write( 'Copy src Tree ...\n') -DistTools.EnsureDir(DistDir+DistSrc+'/src') -FileTools.cpallWithFilter('../../src',DistDir+DistSrc+'/src',FileTools.SetUpFilter(DistTools.SrcFilter)) +# ==================================================================== +# copy src +sys.stdout.write("Copy src Tree ...\n") +DistTools.EnsureDir(DistDir + DistSrc + "/src") +FileTools.cpallWithFilter( + "../../src", DistDir + DistSrc + "/src", FileTools.SetUpFilter(DistTools.SrcFilter) +) -#==================================================================== +# ==================================================================== # copy top level files -#FileTools.cpfile("../Doc/README.html",DistDir+DistBin+"/README.html") -#FileTools.cpfile("../Doc/INSTALL.html",DistDir+DistBin+"/INSTALL.html") -#FileTools.cpfile("../Doc/LICENSE.GPL.html",DistDir+DistBin+"/LICENSE.GPL.html") -#FileTools.cpfile("../Doc/LICENSE.LGPL.html",DistDir+DistBin+"/LICENSE.LGPL.html") -#DistTools.cpfile("../Tools/BuildTool.py",DistDir+DistBin+"/BuildTool.py") +# FileTools.cpfile("../Doc/README.html",DistDir+DistBin+"/README.html") +# FileTools.cpfile("../Doc/INSTALL.html",DistDir+DistBin+"/INSTALL.html") +# FileTools.cpfile("../Doc/LICENSE.GPL.html",DistDir+DistBin+"/LICENSE.GPL.html") +# FileTools.cpfile("../Doc/LICENSE.LGPL.html",DistDir+DistBin+"/LICENSE.LGPL.html") +# DistTools.cpfile("../Tools/BuildTool.py",DistDir+DistBin+"/BuildTool.py") -#==================================================================== +# ==================================================================== # zipping an archive -os.popen("7z a -tzip "+ DistDir+DistSrc+".zip "+ DistDir+DistSrc + " -mx9") - -FileTools.rmall(DistDir+DistSrc) +os.popen("7z a -tzip " + DistDir + DistSrc + ".zip " + DistDir + DistSrc + " -mx9") +FileTools.rmall(DistDir + DistSrc) diff --git a/src/Tools/fcbt/DistTools.py b/src/Tools/fcbt/DistTools.py index 335b36eec9..72f3b7e00a 100644 --- a/src/Tools/fcbt/DistTools.py +++ b/src/Tools/fcbt/DistTools.py @@ -1,7 +1,6 @@ - - # shell and operating system import os + verbose = 0 dcount = fcount = 0 maxfileload = 100000 @@ -11,35 +10,58 @@ blksize = 1024 * 8 def BuildDistName(): # Building dist name # reading the last Version information - [FCVersionMajor,FCVersionMinor,FCVersionBuild,FCVersionDisDa] = open("../Version.h",'r').readlines() - DistName = "FreeCAD_V" + FCVersionMajor[23:-1] + '.' +FCVersionMinor[23:-1] + 'B' + FCVersionBuild[23:-1] + [FCVersionMajor, FCVersionMinor, FCVersionBuild, FCVersionDisDa] = open( + "../Version.h", "r" + ).readlines() + DistName = ( + "FreeCAD_V" + + FCVersionMajor[23:-1] + + "." + + FCVersionMinor[23:-1] + + "B" + + FCVersionBuild[23:-1] + ) return DistName + + def BuildSetupName(): # Building dist name # reading the last Version information - [FCVersionMajor,FCVersionMinor,FCVersionBuild,FCVersionDisDa] = open("../Version.h",'r').readlines() - DistName = "FreeCAD_V" + FCVersionMajor[23:-1] + '.' +FCVersionMinor[23:-1] + [FCVersionMajor, FCVersionMinor, FCVersionBuild, FCVersionDisDa] = open( + "../Version.h", "r" + ).readlines() + DistName = "FreeCAD_V" + FCVersionMajor[23:-1] + "." + FCVersionMinor[23:-1] return DistName + def GetVersion(): # Building dist name # reading the last Version information - [FCVersionMajor,FCVersionMinor,FCVersionBuild,FCVersionDisDa] = open("../Version.h",'r').readlines() - return FCVersionMajor[23:-1] + '.' +FCVersionMinor[23:-1] + [FCVersionMajor, FCVersionMinor, FCVersionBuild, FCVersionDisDa] = open( + "../Version.h", "r" + ).readlines() + return FCVersionMajor[23:-1] + "." + FCVersionMinor[23:-1] + def GetBuildNbr(): # Building dist name # reading the last Version information - [FCVersionMajor,FCVersionMinor,FCVersionBuild,FCVersionDisDa] = open("../Version.h",'r').readlines() - return FCVersionBuild[23:-1] + [FCVersionMajor, FCVersionMinor, FCVersionBuild, FCVersionDisDa] = open( + "../Version.h", "r" + ).readlines() + return FCVersionBuild[23:-1] + def GetBuildDate(): # Building dist name # reading the last Version information - [FCVersionMajor,FCVersionMinor,FCVersionBuild,FCVersionDisDa] = open("../Version.h",'r').readlines() - return FCVersionDisDa[23:-1] + [FCVersionMajor, FCVersionMinor, FCVersionBuild, FCVersionDisDa] = open( + "../Version.h", "r" + ).readlines() + return FCVersionDisDa[23:-1] + def EnsureDir(name): if not os.path.isdir(name): @@ -48,117 +70,122 @@ def EnsureDir(name): else: return 1 -SrcFilter = ["^.*\\.o$", - "^Debug$", - "^DebugCmd$", - "^DebugPy$", - "^Release$", - "^ReleaseCmd$", - "^ReleasePy$", - "^Attic$", - "^CVS$", - "^moc_\\.*$", - "^.*\\.opt$", - "^.*\\.ilg$", - "^.*\\.ps$", - "^.*\\.ind$", - "^.*\\.idx$", - "^.*\\.doc$", - "^.*\\.dvi$", - "^.*\\.ncb$", - "^.*\\.aux$", - "^.*\\.pdf$", - "^.*\\.toc$", - "^.*\\.exe$", - "^.*\\.png$", - "^.*\\.bak$", - "^.*\\.pyc$", - "^.*\\.dep$", - "^.*\\.log$", - "^.*\\.pyd$", - "^.*\\.ilk$", - "^.*\\.lib$", - "^.*\\.pdb$", - "^.*\\.exp$", - "^.*\\.bsc$", - "^.*\\.plg$",] -BinFilter = ["^Plugin\\.*$", - "^Standard\\.*$", - "^.*\\.xml$", - "^.*\\.log$", - "^.*\\.pdb$", - "^.*\\.ilk$", - "^.*\\.lib$", - "^.*\\.exp$", - "^.*\\.bsc$", - "^.*CADD.exe$", - "^.*CADAppD.dll$", - "^.*CmdD.exe$", - "^.*BaseD.dll$", - "^.*CADDCmdPy.dll$", - "^.*GuiD.dll$", - "^.*\\.bsc$", - "^.*\\.FCScript\\..*$", - "^.*\\.FCParam$", - "^.*\\.FCScript$"] +SrcFilter = [ + "^.*\\.o$", + "^Debug$", + "^DebugCmd$", + "^DebugPy$", + "^Release$", + "^ReleaseCmd$", + "^ReleasePy$", + "^Attic$", + "^CVS$", + "^moc_\\.*$", + "^.*\\.opt$", + "^.*\\.ilg$", + "^.*\\.ps$", + "^.*\\.ind$", + "^.*\\.idx$", + "^.*\\.doc$", + "^.*\\.dvi$", + "^.*\\.ncb$", + "^.*\\.aux$", + "^.*\\.pdf$", + "^.*\\.toc$", + "^.*\\.exe$", + "^.*\\.png$", + "^.*\\.bak$", + "^.*\\.pyc$", + "^.*\\.dep$", + "^.*\\.log$", + "^.*\\.pyd$", + "^.*\\.ilk$", + "^.*\\.lib$", + "^.*\\.pdb$", + "^.*\\.exp$", + "^.*\\.bsc$", + "^.*\\.plg$", +] -LibFilter = ["^Plugin\\.*$", - "^Standard\\.*$", - "^.*\\.xml$", - "^.*\\.log$", - "^.*\\.pdb$", - "^.*\\.ilk$", - "^.*\\.exe$", - "^.*\\.exp$", - "^.*\\.bsc$", - "^.*CADD.lib$", - "^.*CADAppD.lib$", - "^.*CmdD.lib$", - "^.*BaseD.lib$", - "^.*GuiD.lib$", - "^.*\\.FCScript\\..*$", - "^.*\\.FCParam$"] +BinFilter = [ + "^Plugin\\.*$", + "^Standard\\.*$", + "^.*\\.xml$", + "^.*\\.log$", + "^.*\\.pdb$", + "^.*\\.ilk$", + "^.*\\.lib$", + "^.*\\.exp$", + "^.*\\.bsc$", + "^.*CADD.exe$", + "^.*CADAppD.dll$", + "^.*CmdD.exe$", + "^.*BaseD.dll$", + "^.*CADDCmdPy.dll$", + "^.*GuiD.dll$", + "^.*\\.bsc$", + "^.*\\.FCScript\\..*$", + "^.*\\.FCParam$", + "^.*\\.FCScript$", +] -LibPackFilter = ["^.*\\.o$", - "^Debug$"] +LibFilter = [ + "^Plugin\\.*$", + "^Standard\\.*$", + "^.*\\.xml$", + "^.*\\.log$", + "^.*\\.pdb$", + "^.*\\.ilk$", + "^.*\\.exe$", + "^.*\\.exp$", + "^.*\\.bsc$", + "^.*CADD.lib$", + "^.*CADAppD.lib$", + "^.*CmdD.lib$", + "^.*BaseD.lib$", + "^.*GuiD.lib$", + "^.*\\.FCScript\\..*$", + "^.*\\.FCParam$", +] -ModFilter = ["^.*\\.o$", - "^Debug$", - "^DebugCmd$", - "^DebugPy$", - "^Release$", - "^ReleaseCmd$", - "^App$", - "^Gui$", - "^CVS$", - "^Attic$", - "^.*\\.opt$", - "^.*_d\.pyd$", - "^.*\\.opt$", - "^.*\\.ilg$", - "^.*\\.ps$", - "^.*\\.ind$", - "^.*\\.idx$", - "^.*\\.doc$", - "^.*\\.dvi$", - "^.*\\.ncb$", - "^.*\\.aux$", - "^.*\\.pdf$", - "^.*\\.toc$", - "^.*\\.bak$", - "^.*\\.pyc$", - "^.*\\.dep$", - "^.*\\.log$", - "^.*\\.ilk$", - "^.*\\.pdb$", - "^.*\\.exp$", - "^.*\\.lib$", - "^.*\\.ui$", - "^.*Makefile$", - "^.*\\.plg$",] - -DocFilter = ["^.*\\.o$", - "^Debug$"] +LibPackFilter = ["^.*\\.o$", "^Debug$"] +ModFilter = [ + "^.*\\.o$", + "^Debug$", + "^DebugCmd$", + "^DebugPy$", + "^Release$", + "^ReleaseCmd$", + "^App$", + "^Gui$", + "^CVS$", + "^Attic$", + "^.*\\.opt$", + "^.*_d\.pyd$", + "^.*\\.opt$", + "^.*\\.ilg$", + "^.*\\.ps$", + "^.*\\.ind$", + "^.*\\.idx$", + "^.*\\.doc$", + "^.*\\.dvi$", + "^.*\\.ncb$", + "^.*\\.aux$", + "^.*\\.pdf$", + "^.*\\.toc$", + "^.*\\.bak$", + "^.*\\.pyc$", + "^.*\\.dep$", + "^.*\\.log$", + "^.*\\.ilk$", + "^.*\\.pdb$", + "^.*\\.exp$", + "^.*\\.lib$", + "^.*\\.ui$", + "^.*Makefile$", + "^.*\\.plg$", +] +DocFilter = ["^.*\\.o$", "^Debug$"] diff --git a/src/Tools/fcbt/FileTools.py b/src/Tools/fcbt/FileTools.py index f559705356..1178e46ba1 100644 --- a/src/Tools/fcbt/FileTools.py +++ b/src/Tools/fcbt/FileTools.py @@ -1,30 +1,32 @@ # shell and operating system import os, sys, re + verbose = 0 dcount = fcount = 0 maxfileload = 100000 blksize = 1024 * 8 + def cpfile(pathFrom, pathTo, maxfileload=maxfileload): """ copy file pathFrom to pathTo, byte for byte """ if os.path.getsize(pathFrom) <= maxfileload: - bytesFrom = open(pathFrom, 'rb').read() # read small file all at once - bytesTo = open(pathTo, 'wb') - bytesTo.write(bytesFrom) # need b mode on Windows - #bytesTo.close() - #bytesFrom.close() + bytesFrom = open(pathFrom, "rb").read() # read small file all at once + bytesTo = open(pathTo, "wb") + bytesTo.write(bytesFrom) # need b mode on Windows + # bytesTo.close() + # bytesFrom.close() else: - fileFrom = open(pathFrom, 'rb') # read big files in chunks - fileTo = open(pathTo, 'wb') # need b mode here too + fileFrom = open(pathFrom, "rb") # read big files in chunks + fileTo = open(pathTo, "wb") # need b mode here too while 1: - bytesFrom = fileFrom.read(blksize) # get one block, less at end - if not bytesFrom: break # empty after last chunk + bytesFrom = fileFrom.read(blksize) # get one block, less at end + if not bytesFrom: + break # empty after last chunk fileTo.write(bytesFrom) - #fileFrom.close() - #fileTo.close() - + # fileFrom.close() + # fileTo.close() def cpall(dirFrom, dirTo): @@ -32,28 +34,31 @@ def cpall(dirFrom, dirTo): copy contents of dirFrom and below to dirTo """ global dcount, fcount - for file in os.listdir(dirFrom): # for files/dirs here - #print file + for file in os.listdir(dirFrom): # for files/dirs here + # print file pathFrom = os.path.join(dirFrom, file) - pathTo = os.path.join(dirTo, file) # extend both paths - if not os.path.isdir(pathFrom): # copy simple files + pathTo = os.path.join(dirTo, file) # extend both paths + if not os.path.isdir(pathFrom): # copy simple files try: - if verbose > 1: print('copying', pathFrom, 'to', pathTo) + if verbose > 1: + print("copying", pathFrom, "to", pathTo) cpfile(pathFrom, pathTo) - fcount = fcount+1 + fcount = fcount + 1 except Exception: - print('Error copying', pathFrom, 'to', pathTo, '--skipped') + print("Error copying", pathFrom, "to", pathTo, "--skipped") print(sys.exc_type, sys.exc_value) else: - if verbose: print('copying dir', pathFrom, 'to', pathTo) + if verbose: + print("copying dir", pathFrom, "to", pathTo) try: - os.mkdir(pathTo) # make new subdir - cpall(pathFrom, pathTo) # recur into subdirs - dcount = dcount+1 + os.mkdir(pathTo) # make new subdir + cpall(pathFrom, pathTo) # recur into subdirs + dcount = dcount + 1 except Exception: - print('Error creating', pathTo, '--skipped') + print("Error creating", pathTo, "--skipped") print(sys.exc_type, sys.exc_value) + def SetUpFilter(MatchList): RegList = [] for regexp in MatchList: @@ -61,58 +66,62 @@ def SetUpFilter(MatchList): RegList.append(a) return RegList -def cpallWithFilter(dirFrom, dirTo,MatchList): + +def cpallWithFilter(dirFrom, dirTo, MatchList): """ copy contents of dirFrom and below to dirTo without match """ global dcount, fcount - for file in os.listdir(dirFrom): # for files/dirs here + for file in os.listdir(dirFrom): # for files/dirs here hitt = 0 for matchpat in MatchList: - if(re.match(matchpat,file)): - hitt = 1 -# print 'Refuse: '+file + if re.match(matchpat, file): + hitt = 1 + # print 'Refuse: '+file if hitt == 0: pathFrom = os.path.join(dirFrom, file) - pathTo = os.path.join(dirTo, file) # extend both paths - if not os.path.isdir(pathFrom): # copy simple files + pathTo = os.path.join(dirTo, file) # extend both paths + if not os.path.isdir(pathFrom): # copy simple files try: - if verbose > 1: print('copying', pathFrom, 'to', pathTo) + if verbose > 1: + print("copying", pathFrom, "to", pathTo) cpfile(pathFrom, pathTo) - fcount = fcount+1 + fcount = fcount + 1 except Exception: - print('Error copying', pathFrom, 'to', pathTo, '--skipped') + print("Error copying", pathFrom, "to", pathTo, "--skipped") print(sys.exc_type, sys.exc_value) else: - if verbose: print('copying dir', pathFrom, 'to', pathTo) + if verbose: + print("copying dir", pathFrom, "to", pathTo) try: - os.mkdir(pathTo) # make new subdir - cpallWithFilter(pathFrom, pathTo,MatchList) # recur into subdirs - dcount = dcount+1 + os.mkdir(pathTo) # make new subdir + cpallWithFilter(pathFrom, pathTo, MatchList) # recur into subdirs + dcount = dcount + 1 except Exception: - print('Error creating', pathTo, '--skipped') + print("Error creating", pathTo, "--skipped") print(sys.exc_type, sys.exc_value) + ################################################################ # Use: "python rmall.py directoryPath directoryPath..." -# recursive directory tree deletion: removes all files and +# recursive directory tree deletion: removes all files and # directories at and below directoryPaths; recurs into subdirs -# and removes parent dir last, because os.rmdir requires that -# directory is empty; like a Unix "rm -rf directoryPath" -################################################################ +# and removes parent dir last, because os.rmdir requires that +# directory is empty; like a Unix "rm -rf directoryPath" +################################################################ fcount = dcount = 0 -def rmall(dirPath): # delete dirPath and below + +def rmall(dirPath): # delete dirPath and below global fcount, dcount namesHere = os.listdir(dirPath) - for name in namesHere: # remove all contents first + for name in namesHere: # remove all contents first path = os.path.join(dirPath, name) - if not os.path.isdir(path): # remove simple files + if not os.path.isdir(path): # remove simple files os.remove(path) fcount = fcount + 1 - else: # recur to remove subdirs + else: # recur to remove subdirs rmall(path) - os.rmdir(dirPath) # remove now-empty dirPath + os.rmdir(dirPath) # remove now-empty dirPath dcount = dcount + 1 - diff --git a/src/Tools/fcbt/NextBuildNumber.py b/src/Tools/fcbt/NextBuildNumber.py index 3faefee4a0..0c531b2d09 100644 --- a/src/Tools/fcbt/NextBuildNumber.py +++ b/src/Tools/fcbt/NextBuildNumber.py @@ -1,25 +1,25 @@ -#*************************************************************************** -#* Copyright (c) 2002 Juergen Riegel * -#* * -#* This file is part of the FreeCAD CAx development system. * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* FreeCAD is distributed in the hope that it will be useful, * -#* but WITHOUT ANY WARRANTY; without even the implied warranty of * -#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -#* GNU Lesser General Public License for more details. * -#* * -#* You should have received a copy of the GNU Library General Public * -#* License along with FreeCAD; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#***************************************************************************/ +# *************************************************************************** +# * Copyright (c) 2002 Juergen Riegel * +# * * +# * This file is part of the FreeCAD CAx development system. * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * FreeCAD is distributed in the hope that it will be useful, * +# * but WITHOUT ANY WARRANTY; without even the implied warranty of * +# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +# * GNU Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Library General Public * +# * License along with FreeCAD; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# ***************************************************************************/ # FreeCAD MakeNewBuildNbr script # @@ -28,29 +28,47 @@ import time # reading the last Version information -[FCVersionMajor,FCVersionMinor,FCVersionBuild,FCVersionDisDa] = open("../Version.h",'r').readlines() +[FCVersionMajor, FCVersionMinor, FCVersionBuild, FCVersionDisDa] = open( + "../Version.h", "r" +).readlines() # increasing build number -BuildNumber = int(FCVersionBuild[23:-1]) +1 +BuildNumber = int(FCVersionBuild[23:-1]) + 1 print("New Buildnumber is:") print(BuildNumber) print("\n") # writing new Version.h File -open("../Version.h",'w').writelines([FCVersionMajor, - FCVersionMinor, - FCVersionBuild[:23]+str(BuildNumber)+'\n', - FCVersionDisDa[:23]+ '"'+time.asctime()+'" \n\n']) +open("../Version.h", "w").writelines( + [ + FCVersionMajor, + FCVersionMinor, + FCVersionBuild[:23] + str(BuildNumber) + "\n", + FCVersionDisDa[:23] + '"' + time.asctime() + '" \n\n', + ] +) # writing the ChangeLog.txt -open("../ChangeLog.txt",'a').write("\nVersion: V"+FCVersionMajor[23:-1]+"."+FCVersionMinor[23:-1]+"B"+ - str(BuildNumber)+" Date: "+time.asctime()+' +++++++++++++++++++++++++++++++\n') +open("../ChangeLog.txt", "a").write( + "\nVersion: V" + + FCVersionMajor[23:-1] + + "." + + FCVersionMinor[23:-1] + + "B" + + str(BuildNumber) + + " Date: " + + time.asctime() + + " +++++++++++++++++++++++++++++++\n" +) # writing new Version.wxi File -open("../Version.wxi",'w').writelines(["\n", - " \n", - " \n", - " \n", - " \n"]) - +open("../Version.wxi", "w").writelines( + [ + "\n", + " \n", + " \n", + " \n", + " \n", + ] +) diff --git a/src/Tools/fcinfo b/src/Tools/fcinfo index 07064d4c68..7c64dad318 100755 --- a/src/Tools/fcinfo +++ b/src/Tools/fcinfo @@ -2,32 +2,32 @@ # -*- coding: utf8 -*- -#*************************************************************************** -#* * -#* Copyright (c) 2015 Yorik van Havre * -#* * -#* This program is free software; you can redistribute it and/or modify * -#* it under the terms of the GNU Lesser General Public License (LGPL) * -#* as published by the Free Software Foundation; either version 2 of * -#* the License, or (at your option) any later version. * -#* for detail see the LICENCE text file. * -#* * -#* This program is distributed in the hope that it will be useful, * -#* but WITHOUT ANY WARRANTY; without even the implied warranty of * -#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -#* GNU Library General Public License for more details. * -#* * -#* You should have received a copy of the GNU Library General Public * -#* License along with this program; if not, write to the Free Software * -#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * -#* USA * -#* * -#*************************************************************************** +# *************************************************************************** +# * * +# * Copyright (c) 2015 Yorik van Havre * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * This program is distributed in the hope that it will be useful, * +# * but WITHOUT ANY WARRANTY; without even the implied warranty of * +# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * +# * GNU Library General Public License for more details. * +# * * +# * You should have received a copy of the GNU Library General Public * +# * License along with this program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** -__title__="FreeCAD File info utility" +__title__ = "FreeCAD File info utility" __author__ = "Yorik van Havre" __url__ = ["http://www.freecadweb.org"] -__doc__ = ''' +__doc__ = """ This utility prints information about a given FreeCAD file (*.FCStd) on screen, including document properties, number of included objects, object sizes and properties and values. Its main use is to compare @@ -70,7 +70,7 @@ Git usage: With this, when committing a .FCStd file with Git, 'git diff' will show you the difference between the two texts obtained by fcinfo -''' +""" import sys @@ -81,12 +81,8 @@ import hashlib import re - class FreeCADFileHandler(xml.sax.ContentHandler): - - - - def __init__(self, zfile, short = 0): # short: 0=normal, 1=short, 2=veryshort + def __init__(self, zfile, short=0): # short: 0=normal, 1=short, 2=veryshort xml.sax.ContentHandler.__init__(self) self.zfile = zfile @@ -105,14 +101,14 @@ class FreeCADFileHandler(xml.sax.ContentHandler): self.contents["FileVersion"] = attributes["FileVersion"] elif tag == "Object": - if ("name" in attributes): + if "name" in attributes: name = self.clean(attributes["name"]) self.obj = name - if ("type" in attributes): + if "type" in attributes: self.contents[name] = attributes["type"] elif tag == "ViewProvider": - if ("name" in attributes): + if "name" in attributes: self.obj = self.clean(attributes["name"]) elif tag == "Part": @@ -120,53 +116,97 @@ class FreeCADFileHandler(xml.sax.ContentHandler): r = self.zfile.read(attributes["file"]) s = r.__sizeof__() if s < 1024: - s = str(s)+"B" + s = str(s) + "B" elif s > 1048576: - s = str(s/1048576)+"M" + s = str(s / 1048576) + "M" else: - s = str(s/1024)+"K" + s = str(s / 1024) + "K" s += " " + str(hashlib.sha1(r).hexdigest()[:12]) self.contents[self.obj] += " (" + s + ")" elif tag == "Property": self.prop = None # skip "internal" properties, useless for a diff - if attributes["name"] not in ["Symbol","AttacherType","MapMode","MapPathParameter","MapReversed", - "AttachmentOffset","SelectionStyle","TightGrid","GridSize","GridSnap", - "GridStyle","Lighting","Deviation","AngularDeflection","BoundingBox", - "Selectable","ShowGrid"]: + if attributes["name"] not in [ + "Symbol", + "AttacherType", + "MapMode", + "MapPathParameter", + "MapReversed", + "AttachmentOffset", + "SelectionStyle", + "TightGrid", + "GridSize", + "GridSnap", + "GridStyle", + "Lighting", + "Deviation", + "AngularDeflection", + "BoundingBox", + "Selectable", + "ShowGrid", + ]: self.prop = attributes["name"] - elif tag in ["String","Uuid","Float","Integer","Bool","Link"]: + elif tag in ["String", "Uuid", "Float", "Integer", "Bool", "Link"]: if self.prop and ("value" in attributes): if self.obj == "Document": self.contents[self.prop] = attributes["value"] elif self.short == 0: if tag == "Float": - self.contents[self.obj+"00000000::"+self.prop] = str(float(attributes["value"])) + self.contents[self.obj + "00000000::" + self.prop] = str( + float(attributes["value"]) + ) else: - self.contents[self.obj+"00000000::"+self.prop] = attributes["value"] + self.contents[self.obj + "00000000::" + self.prop] = attributes["value"] elif tag in ["PropertyVector"]: if self.prop and self.obj and (self.short == 0): - val = "("+str(float(attributes["valueX"]))+","+str(float(attributes["valueY"]))+","+str(float(attributes["valueZ"]))+")" - self.contents[self.obj+"00000000::"+self.prop] = val + val = ( + "(" + + str(float(attributes["valueX"])) + + "," + + str(float(attributes["valueY"])) + + "," + + str(float(attributes["valueZ"])) + + ")" + ) + self.contents[self.obj + "00000000::" + self.prop] = val elif tag in ["PropertyPlacement"]: if self.prop and self.obj and (self.short == 0): - val = "("+str(float(attributes["Px"]))+","+str(float(attributes["Py"]))+","+str(float(attributes["Pz"]))+")" - val += " ("+str(round(float(attributes["Q0"]),4))+","+str(round(float(attributes["Q1"]),4))+"," - val += str(round(float(attributes["Q2"]),4))+","+str(round(float(attributes["Q3"]),4))+")" - self.contents[self.obj+"00000000::"+self.prop] = val + val = ( + "(" + + str(float(attributes["Px"])) + + "," + + str(float(attributes["Py"])) + + "," + + str(float(attributes["Pz"])) + + ")" + ) + val += ( + " (" + + str(round(float(attributes["Q0"]), 4)) + + "," + + str(round(float(attributes["Q1"]), 4)) + + "," + ) + val += ( + str(round(float(attributes["Q2"]), 4)) + + "," + + str(round(float(attributes["Q3"]), 4)) + + ")" + ) + self.contents[self.obj + "00000000::" + self.prop] = val elif tag in ["PropertyColor"]: if self.prop and self.obj and (self.short == 0): c = int(attributes["value"]) - r = float((c>>24)&0xFF)/255.0 - g = float((c>>16)&0xFF)/255.0 - b = float((c>>8)&0xFF)/255.0 - val = str((r,g,b)) - self.contents[self.obj+"00000000::"+self.prop] = val + r = float((c >> 24) & 0xFF) / 255.0 + g = float((c >> 16) & 0xFF) / 255.0 + b = float((c >> 8) & 0xFF) / 255.0 + val = str((r, g, b)) + self.contents[self.obj + "00000000::" + self.prop] = val elif tag == "Objects": self.count = attributes["Count"] @@ -175,11 +215,11 @@ class FreeCADFileHandler(xml.sax.ContentHandler): # Print all the contents of the document properties items = self.contents.items() items = sorted(items) - for key,value in items: + for key, value in items: key = self.clean(key) value = self.clean(value) print(" " + key + " : " + value) - print(" Objects: ("+self.count+")") + print(" Objects: (" + self.count + ")") self.contents = {} def endElement(self, tag): @@ -187,21 +227,21 @@ class FreeCADFileHandler(xml.sax.ContentHandler): if (tag == "Document") and (self.short != 2): items = self.contents.items() items = sorted(items) - for key,value in items: + for key, value in items: key = self.clean(key) if "00000000::" in key: - key = " "+key.split("00000000::")[1] + key = " " + key.split("00000000::")[1] value = self.clean(value) if value: print(" " + key + " : " + value) - def clean(self,value): + def clean(self, value): value = value.strip() return value -if __name__ == '__main__': +if __name__ == "__main__": if len(sys.argv) < 2: print(__doc__) @@ -235,19 +275,19 @@ if __name__ == '__main__': doc = zfile.read("Document.xml") if gui and "GuiDocument.xml" in zfile.namelist(): guidoc = zfile.read("GuiDocument.xml") - guidoc = re.sub(b"<\?xml.*?-->",b" ",guidoc,flags=re.MULTILINE|re.DOTALL) + guidoc = re.sub(b"<\?xml.*?-->", b" ", guidoc, flags=re.MULTILINE | re.DOTALL) # a valid xml doc can have only one root element. So we need to insert # all the contents of the GUiDocument tag into the main one - doc = re.sub(b"<\/Document>",b"",doc,flags=re.MULTILINE|re.DOTALL) - guidoc = re.sub(b"",b" ",guidoc,flags=re.MULTILINE|re.DOTALL) + doc = re.sub(b"<\/Document>", b"", doc, flags=re.MULTILINE | re.DOTALL) + guidoc = re.sub(b"", b" ", guidoc, flags=re.MULTILINE | re.DOTALL) doc += guidoc s = os.path.getsize(sys.argv[-1]) if s < 1024: - s = str(s)+"B" + s = str(s) + "B" elif s > 1048576: - s = str(s/1048576)+"M" + s = str(s / 1048576) + "M" else: - s = str(s/1024)+"K" - print("Document: "+sys.argv[-1]+" ("+s+")") - print(" SHA1: "+str(hashlib.sha1(open(sys.argv[-1],'rb').read()).hexdigest())) - xml.sax.parseString(doc,FreeCADFileHandler(zfile,short)) + s = str(s / 1024) + "K" + print("Document: " + sys.argv[-1] + " (" + s + ")") + print(" SHA1: " + str(hashlib.sha1(open(sys.argv[-1], "rb").read()).hexdigest())) + xml.sax.parseString(doc, FreeCADFileHandler(zfile, short)) diff --git a/src/Tools/freecad-thumbnailer b/src/Tools/freecad-thumbnailer index 56b9f20d31..480dc47f30 100644 --- a/src/Tools/freecad-thumbnailer +++ b/src/Tools/freecad-thumbnailer @@ -34,7 +34,7 @@ import sys import zipfile import getopt -opt, par = getopt.getopt(sys.argv[1:], '-s:') +opt, par = getopt.getopt(sys.argv[1:], "-s:") input_file = par[0] output_file = par[1] diff --git a/src/Tools/generate.py b/src/Tools/generate.py index 9020f782ba..fdfbf31d99 100644 --- a/src/Tools/generate.py +++ b/src/Tools/generate.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- # (c) 2006 Jürgen Riegel GPL -import os,sys,getopt +import os, sys, getopt import generateBase.generateModel_Module import generateTemplates.templateModule import generateTemplates.templateClassPyExport @@ -11,13 +11,13 @@ Usage = """generate - generates a FreeCAD Module out of an XML model Usage: generate [Optionen] Model.xml Model2.xml Model3.xml ... - + Options: -h, --help print this help -o, --outputPath specify the output path if differs from source path - + Generate source code out of an model definition. - + Author: (c) 2006 Juergen Riegel juergen.riegel@web.de @@ -30,41 +30,40 @@ Version: # Globals -def generate(filename,path): - # load model - GenerateModelInst = generateBase.generateModel_Module.parse(filename) - if(len(GenerateModelInst.Module)!=0): - Module= generateTemplates.templateModule.TemplateModule() - Module.path = path - Module.module = GenerateModelInst.Module[0] - Module.Generate() - print("Done generating: " + GenerateModelInst.Module[0].Name) - else: - Export = generateTemplates.templateClassPyExport.TemplateClassPyExport() - Export.path = path+"/" - Export.dirname = os.path.dirname(filename)+"/" - Export.export = GenerateModelInst.PythonExport[0] - Export.Generate() - print("Done generating: " + GenerateModelInst.PythonExport[0].Name) - - - - - +def generate(filename, path): + # load model + GenerateModelInst = generateBase.generateModel_Module.parse(filename) + + if len(GenerateModelInst.Module) != 0: + Module = generateTemplates.templateModule.TemplateModule() + Module.path = path + Module.module = GenerateModelInst.Module[0] + Module.Generate() + print("Done generating: " + GenerateModelInst.Module[0].Name) + else: + Export = generateTemplates.templateClassPyExport.TemplateClassPyExport() + Export.path = path + "/" + Export.dirname = os.path.dirname(filename) + "/" + Export.export = GenerateModelInst.PythonExport[0] + Export.Generate() + print("Done generating: " + GenerateModelInst.PythonExport[0].Name) def main(): defaultPath = "" + class generateOutput: def write(self, data): - pass - def flush(self): # mandatory for file-like objects pass - sys.stdout=generateOutput() - + + def flush(self): # mandatory for file-like objects + pass + + sys.stdout = generateOutput() + try: - opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help","outputPath="]) + opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help", "outputPath="]) except getopt.GetoptError: # print help information and exit: sys.stderr.write(Usage) @@ -78,19 +77,18 @@ def main(): if o in ("-o", "--outputPath"): defaultPath = a - # running through the files - if (len(args) ==0): + if len(args) == 0: sys.stderr.write(Usage) else: for i in args: filename = os.path.abspath(i) - if(defaultPath == ""): - head,tail = os.path.split(filename) - print(head,tail) - generate(filename,head) + if defaultPath == "": + head, tail = os.path.split(filename) + print(head, tail) + generate(filename, head) else: - generate(filename,defaultPath) + generate(filename, defaultPath) if __name__ == "__main__": diff --git a/src/Tools/generateBase/generateDS.py b/src/Tools/generateBase/generateDS.py index 3889571cbd..3969ffc4c5 100644 --- a/src/Tools/generateBase/generateDS.py +++ b/src/Tools/generateBase/generateDS.py @@ -58,11 +58,11 @@ SaxElementDict = {} ElementDebugList = [] Force = 0 NameTable = { - 'class': 'klass', - 'import': 'emport', - 'type': 'ttype', - } -SubclassSuffix = 'Sub' + "class": "klass", + "import": "emport", + "type": "ttype", +} +SubclassSuffix = "Sub" RootElement = None AttributeGroups = {} SubstitutionGroups = {} @@ -72,54 +72,46 @@ SubstitutionGroups = {} # These are simple types defined at top level. SimpleElementDict = {} + def set_type_constants(nameSpace): - global StringType, TokenType, \ - IntegerType, DecimalType, \ - ShortType, LongType, \ - PositiveIntegerType, NegativeIntegerType, \ - NonPositiveIntegerType, NonNegativeIntegerType, \ - BooleanType, FloatType, DoubleType, \ - ElementType, ComplexTypeType, SequenceType, ChoiceType, \ - AttributeGroupType, AttributeType, SchemaType, \ - DateTimeType, DateType, \ - ComplexContentType, ExtensionType, \ - IDType, IDREFType, IDREFSType, \ - AnyAttributeType - AttributeGroupType = nameSpace + 'attributeGroup' - AttributeType = nameSpace + 'attribute' - BooleanType = nameSpace + 'boolean' - ChoiceType = nameSpace + 'choice' - ComplexContentType = nameSpace + 'complexContent' - ComplexTypeType = nameSpace + 'complexType' - AnyAttributeType = nameSpace + 'anyAttribute' - DateTimeType = nameSpace + 'dateTime' - DateType = nameSpace + 'date' - IntegerType = (nameSpace + 'integer', - nameSpace + 'xs:unsignedShort', - nameSpace + 'short', - nameSpace + 'long', - ) - #ShortType = nameSpace + 'short' - #LongType = nameSpace + 'long' - DecimalType = nameSpace + 'decimal' - PositiveIntegerType = nameSpace + 'positiveInteger' - NegativeIntegerType = nameSpace + 'negativeInteger' - NonPositiveIntegerType = nameSpace + 'nonPositiveInteger' - NonNegativeIntegerType = nameSpace + 'nonNegativeInteger' - DoubleType = nameSpace + 'double' - ElementType = nameSpace + 'element' - ExtensionType = nameSpace + 'extension' - FloatType = nameSpace + 'float' - IDREFSType = nameSpace + 'IDREFS' - IDREFType = nameSpace + 'IDREF' - IDType = nameSpace + 'ID' - SchemaType = nameSpace + 'schema' - SequenceType = nameSpace + 'sequence' - StringType = (nameSpace + 'string', - nameSpace + 'duration', - nameSpace + 'anyURI', - ) - TokenType = nameSpace + 'token' + global StringType, TokenType, IntegerType, DecimalType, ShortType, LongType, PositiveIntegerType, NegativeIntegerType, NonPositiveIntegerType, NonNegativeIntegerType, BooleanType, FloatType, DoubleType, ElementType, ComplexTypeType, SequenceType, ChoiceType, AttributeGroupType, AttributeType, SchemaType, DateTimeType, DateType, ComplexContentType, ExtensionType, IDType, IDREFType, IDREFSType, AnyAttributeType + AttributeGroupType = nameSpace + "attributeGroup" + AttributeType = nameSpace + "attribute" + BooleanType = nameSpace + "boolean" + ChoiceType = nameSpace + "choice" + ComplexContentType = nameSpace + "complexContent" + ComplexTypeType = nameSpace + "complexType" + AnyAttributeType = nameSpace + "anyAttribute" + DateTimeType = nameSpace + "dateTime" + DateType = nameSpace + "date" + IntegerType = ( + nameSpace + "integer", + nameSpace + "xs:unsignedShort", + nameSpace + "short", + nameSpace + "long", + ) + # ShortType = nameSpace + 'short' + # LongType = nameSpace + 'long' + DecimalType = nameSpace + "decimal" + PositiveIntegerType = nameSpace + "positiveInteger" + NegativeIntegerType = nameSpace + "negativeInteger" + NonPositiveIntegerType = nameSpace + "nonPositiveInteger" + NonNegativeIntegerType = nameSpace + "nonNegativeInteger" + DoubleType = nameSpace + "double" + ElementType = nameSpace + "element" + ExtensionType = nameSpace + "extension" + FloatType = nameSpace + "float" + IDREFSType = nameSpace + "IDREFS" + IDREFType = nameSpace + "IDREF" + IDType = nameSpace + "ID" + SchemaType = nameSpace + "schema" + SequenceType = nameSpace + "sequence" + StringType = ( + nameSpace + "string", + nameSpace + "duration", + nameSpace + "anyURI", + ) + TokenType = nameSpace + "token" # @@ -128,39 +120,43 @@ def set_type_constants(nameSpace): # Print only if DEBUG is true. DEBUG = 1 + + def dbgprint(level, msg): if DEBUG and level > 0: - print (msg) + print(msg) + def pplist(lst): for count, item in enumerate(lst): - print ('%d. %s' % (count, item)) - + print("%d. %s" % (count, item)) # # Representation of element definition. # + def showLevel(outfile, level): for idx in range(level): - outfile.write(' ') + outfile.write(" ") + class XschemaElement: def __init__(self, attrs): - self.cleanName = '' + self.cleanName = "" self.attrs = dict(attrs) - name_val = '' - type_val = '' - ref_val = '' - if 'name' in self.attrs: - name_val = strip_namespace(self.attrs['name']) - if 'type' in self.attrs: + name_val = "" + type_val = "" + ref_val = "" + if "name" in self.attrs: + name_val = strip_namespace(self.attrs["name"]) + if "type" in self.attrs: # fix - #type_val = strip_namespace(self.attrs['type']) - type_val = self.attrs['type'] - if 'ref' in self.attrs: - ref_val = strip_namespace(self.attrs['ref']) + # type_val = strip_namespace(self.attrs['type']) + type_val = self.attrs["type"] + if "ref" in self.attrs: + ref_val = strip_namespace(self.attrs["ref"]) if type_val and not name_val: name_val = type_val if ref_val and not name_val: @@ -168,17 +164,17 @@ class XschemaElement: if ref_val and not type_val: type_val = ref_val if name_val: - self.attrs['name'] = name_val + self.attrs["name"] = name_val if type_val: - self.attrs['type'] = type_val + self.attrs["type"] = type_val if ref_val: - self.attrs['ref'] = ref_val + self.attrs["ref"] = ref_val self.name = name_val self.children = [] self.maxOccurs = 1 self.complex = 0 self.complexType = 0 - self.type = 'NoneType' + self.type = "NoneType" self.mixed = 0 self.base = None self.mixedExtensionError = 0 @@ -196,74 +192,124 @@ class XschemaElement: def addChild(self, element): self.children.append(element) - def getChildren(self): return self.children - def getName(self): return self.name - def getCleanName(self): return self.cleanName - def getUnmappedCleanName(self): return self.unmappedCleanName - def setName(self, name): self.name = name - def getAttrs(self): return self.attrs - def setAttrs(self, attrs): self.attrs = attrs - def getMaxOccurs(self): return self.maxOccurs - def getRawType(self): return self.type + + def getChildren(self): + return self.children + + def getName(self): + return self.name + + def getCleanName(self): + return self.cleanName + + def getUnmappedCleanName(self): + return self.unmappedCleanName + + def setName(self, name): + self.name = name + + def getAttrs(self): + return self.attrs + + def setAttrs(self, attrs): + self.attrs = attrs + + def getMaxOccurs(self): + return self.maxOccurs + + def getRawType(self): + return self.type + def getType(self): returnType = self.type if self.type in ElementDict: typeObj = ElementDict[self.type] typeObjType = typeObj.getRawType() - if typeObjType in StringType or \ - typeObjType == TokenType or \ - typeObjType == DateTimeType or \ - typeObjType == DateType or \ - typeObjType in IntegerType or \ - typeObjType == DecimalType or \ - typeObjType == PositiveIntegerType or \ - typeObjType == NegativeIntegerType or \ - typeObjType == NonPositiveIntegerType or \ - typeObjType == NonNegativeIntegerType or \ - typeObjType == BooleanType or \ - typeObjType == FloatType or \ - typeObjType == DoubleType: + if ( + typeObjType in StringType + or typeObjType == TokenType + or typeObjType == DateTimeType + or typeObjType == DateType + or typeObjType in IntegerType + or typeObjType == DecimalType + or typeObjType == PositiveIntegerType + or typeObjType == NegativeIntegerType + or typeObjType == NonPositiveIntegerType + or typeObjType == NonNegativeIntegerType + or typeObjType == BooleanType + or typeObjType == FloatType + or typeObjType == DoubleType + ): returnType = typeObjType return returnType - def isComplex(self): return self.complex - def addAttributeDefs(self, attrs): self.attributeDefs.append(attrs) - def getAttributeDefs(self): return self.attributeDefs - def isMixed(self): return self.mixed - def setMixed(self, mixed): self.mixed = mixed - def setBase(self, base): self.base = base - def getBase(self): return self.base - def getMixedExtensionError(self): return self.mixedExtensionError - def getAttributeGroups(self): return self.attributeGroups + + def isComplex(self): + return self.complex + + def addAttributeDefs(self, attrs): + self.attributeDefs.append(attrs) + + def getAttributeDefs(self): + return self.attributeDefs + + def isMixed(self): + return self.mixed + + def setMixed(self, mixed): + self.mixed = mixed + + def setBase(self, base): + self.base = base + + def getBase(self): + return self.base + + def getMixedExtensionError(self): + return self.mixedExtensionError + + def getAttributeGroups(self): + return self.attributeGroups + def addAttribute(self, name, attribute): self.attributeGroups[name] = attribute - def setAttributeGroup(self, attributeGroup): self.attributeGroup = attributeGroup - def getAttributeGroup(self): return self.attributeGroup - def setTopLevel(self, topLevel): self.topLevel = topLevel - def getTopLevel(self): return self.topLevel - def setAnyAttribute(self, anyAttribute): self.anyAttribute = anyAttribute - def getAnyAttribute(self): return self.anyAttribute + + def setAttributeGroup(self, attributeGroup): + self.attributeGroup = attributeGroup + + def getAttributeGroup(self): + return self.attributeGroup + + def setTopLevel(self, topLevel): + self.topLevel = topLevel + + def getTopLevel(self): + return self.topLevel + + def setAnyAttribute(self, anyAttribute): + self.anyAttribute = anyAttribute + + def getAnyAttribute(self): + return self.anyAttribute def show(self, outfile, level): showLevel(outfile, level) - outfile.write('Name: %s Type: %s\n' % (self.name, self.getType())) + outfile.write("Name: %s Type: %s\n" % (self.name, self.getType())) showLevel(outfile, level) - outfile.write(' - Complex: %d MaxOccurs: %d\n' % \ - (self.complex, self.maxOccurs)) + outfile.write(" - Complex: %d MaxOccurs: %d\n" % (self.complex, self.maxOccurs)) showLevel(outfile, level) - outfile.write(' - Attrs: %s\n' % self.attrs) + outfile.write(" - Attrs: %s\n" % self.attrs) showLevel(outfile, level) - outfile.write(' - AttributeDefs: %s\n' % self.attributeDefs) - #ipshell('(visit_title) Entering ipshell.\nHit Ctrl-D to exit') - + outfile.write(" - AttributeDefs: %s\n" % self.attributeDefs) + # ipshell('(visit_title) Entering ipshell.\nHit Ctrl-D to exit') + for attr in self.getAttributeDefs(): - key = attr['name'] + key = attr["name"] try: - value = attr['value'] + value = attr["value"] except: - value = '' + value = "" showLevel(outfile, level + 1) - outfile.write('key: %s value: %s\n' % \ - (key, value)) + outfile.write("key: %s value: %s\n" % (key, value)) for child in self.children: child.show(outfile, level + 1) @@ -277,8 +323,12 @@ class XschemaElement: def collect_element_dict(self): base = self.getBase() - if self.getTopLevel() or len(self.getChildren()) > 0 or \ - len(self.getAttributeDefs()) > 0 or base: + if ( + self.getTopLevel() + or len(self.getChildren()) > 0 + or len(self.getAttributeDefs()) > 0 + or base + ): ElementDict[self.name] = self for child in self.children: child.collect_element_dict() @@ -315,36 +365,40 @@ class XschemaElement: if type_val in ElementDict: element = ElementDict[type_val] type_val1 = element.resolve_type_1() - if type_val1 in StringType or \ - type_val1 == TokenType or \ - type_val1 == DateTimeType or \ - type_val1 == DateType or \ - type_val1 in IntegerType or \ - type_val1 == DecimalType or \ - type_val1 == PositiveIntegerType or \ - type_val1 == NonPositiveIntegerType or \ - type_val1 == NegativeIntegerType or \ - type_val1 == NonNegativeIntegerType or \ - type_val1 == BooleanType or \ - type_val1 == FloatType or \ - type_val1 == DoubleType: + if ( + type_val1 in StringType + or type_val1 == TokenType + or type_val1 == DateTimeType + or type_val1 == DateType + or type_val1 in IntegerType + or type_val1 == DecimalType + or type_val1 == PositiveIntegerType + or type_val1 == NonPositiveIntegerType + or type_val1 == NegativeIntegerType + or type_val1 == NonNegativeIntegerType + or type_val1 == BooleanType + or type_val1 == FloatType + or type_val1 == DoubleType + ): type_val = type_val1 else: self.complex = 1 else: - if type_val in StringType or \ - type_val == TokenType or \ - type_val == DateTimeType or \ - type_val == DateType or \ - type_val in IntegerType or \ - type_val == DecimalType or \ - type_val == PositiveIntegerType or \ - type_val == NonPositiveIntegerType or \ - type_val == NegativeIntegerType or \ - type_val == NonNegativeIntegerType or \ - type_val == BooleanType or \ - type_val == FloatType or \ - type_val == DoubleType: + if ( + type_val in StringType + or type_val == TokenType + or type_val == DateTimeType + or type_val == DateType + or type_val in IntegerType + or type_val == DecimalType + or type_val == PositiveIntegerType + or type_val == NonPositiveIntegerType + or type_val == NegativeIntegerType + or type_val == NonNegativeIntegerType + or type_val == BooleanType + or type_val == FloatType + or type_val == DoubleType + ): pass else: type_val = StringType[0] @@ -353,26 +407,26 @@ class XschemaElement: return type_val def resolve_type_1(self): - type_val = '' - if 'type' in self.attrs: + type_val = "" + if "type" in self.attrs: # fix - #type_val = strip_namespace(self.attrs['type']) - type_val = self.attrs['type'] - elif 'ref' in self.attrs: + # type_val = strip_namespace(self.attrs['type']) + type_val = self.attrs["type"] + elif "ref" in self.attrs: # fix - type_val = strip_namespace(self.attrs['ref']) - #type_val = self.attrs['ref'] - elif 'name' in self.attrs: + type_val = strip_namespace(self.attrs["ref"]) + # type_val = self.attrs['ref'] + elif "name" in self.attrs: # fix - type_val = strip_namespace(self.attrs['name']) - #type_val = self.attrs['name'] + type_val = strip_namespace(self.attrs["name"]) + # type_val = self.attrs['name'] return type_val def annotate_find_type(self): type_val = self.resolve_type() - #dbgprint(1, '(aft) n: %s t: %s c: %s id: %s' % \ + # dbgprint(1, '(aft) n: %s t: %s c: %s id: %s' % \ # (self.name, type_val, self.complex, id(self), )) - self.attrs['type'] = type_val + self.attrs["type"] = type_val self.type = type_val if not self.complex: SimpleElementDict[self.name] = self.name @@ -387,30 +441,30 @@ class XschemaElement: self.cleanName = mapName(self.unmappedCleanName) SaxElementDict[self.cleanName] = self self.replace_attributeGroup_names() - if 'maxOccurs' in self.attrs.keys(): - maxOccurs = self.attrs['maxOccurs'] - if maxOccurs == 'unbounded': + if "maxOccurs" in self.attrs.keys(): + maxOccurs = self.attrs["maxOccurs"] + if maxOccurs == "unbounded": maxOccurs = 99999 else: try: - maxOccurs = int(self.attrs['maxOccurs']) + maxOccurs = int(self.attrs["maxOccurs"]) except ValueError: - sys.stderr.write('*** %s maxOccurs must be integer or "unbounded".' % \ - (self.getName(), ) - ) + sys.stderr.write( + '*** %s maxOccurs must be integer or "unbounded".' % (self.getName(),) + ) sys.exit(-1) else: maxOccurs = 1 self.maxOccurs = maxOccurs - #if self.cleanName == 'Reason_XXX': + # if self.cleanName == 'Reason_XXX': # ipshell('(annotate_tree) -- Entering ipshell.\\nHit Ctrl-D to exit') # If it does not have a type, then make the type the same as the name. - if self.type == 'NoneType' and self.name: + if self.type == "NoneType" and self.name: self.type = self.name # Is it a mixed-content element definition? - if 'mixed' in self.attrs.keys(): - mixed = self.attrs['mixed'].strip() - if mixed == '1' or mixed.lower() == 'true': + if "mixed" in self.attrs.keys(): + mixed = self.attrs["mixed"].strip() + if mixed == "1" or mixed.lower() == "true": self.mixed = 1 # Do it recursively for all descendents. for child in self.children: @@ -428,16 +482,14 @@ class XschemaElement: attr = attrGroup.get(name) self.attributeDefs[name] = attr else: - print ('*** Error. attributeGroup %s not defined.' % groupName) + print("*** Error. attributeGroup %s not defined." % groupName) def __str__(self): - s1 = '<"%s" XschemaElement instance at 0x%x>' % \ - (self.getName(), id(self)) + s1 = '<"%s" XschemaElement instance at 0x%x>' % (self.getName(), id(self)) return s1 def __repr__(self): - s1 = '<"%s" XschemaElement instance at 0x%x>' % \ - (self.getName(), id(self)) + s1 = '<"%s" XschemaElement instance at 0x%x>' % (self.getName(), id(self)) return s1 def fix_dup_names(self): @@ -455,7 +507,7 @@ class XschemaElement: attr = attrDefs[key] name = attr.getName() if name in elementNames: - newName = name + '_attr' + newName = name + "_attr" newAttr = XschemaAttribute(newName) attrDefs[newName] = newAttr replaced.append(name) @@ -479,35 +531,47 @@ class XschemaElement: for idx, name in enumerate(attrDefs): attr = attrDefs[name] attrType = attr.getData_type() - if attrType == IDType or \ - attrType == IDREFType or \ - attrType == IDREFSType: + if attrType == IDType or attrType == IDREFType or attrType == IDREFSType: attr.setData_type(StringType[0]) for child in self.children: child.coerce_attr_types() + + # end class XschemaElement class XschemaAttributeGroup: - def __init__(self, name='', group=None): + def __init__(self, name="", group=None): self.name = name if group: self.group = group else: self.group = {} - def setName(self, name): self.name = name - def getName(self): return self.name - def setGroup(self, group): self.group = group - def getGroup(self): return self.group + + def setName(self, name): + self.name = name + + def getName(self): + return self.name + + def setGroup(self, group): + self.group = group + + def getGroup(self): + return self.group + def get(self, name, default=None): if name in self.group: return self.group[name] else: return default + def getKeys(self): return self.group.keys() + def add(self, name, attr): self.group[name] = attr + def delete(self, name): # if has_key(self.group, name): if name in self.group: @@ -515,19 +579,36 @@ class XschemaAttributeGroup: return 1 else: return 0 + + # end class XschemaAttributeGroup + class XschemaAttribute: - def __init__(self, name, data_type='xs:string', use='optional'): + def __init__(self, name, data_type="xs:string", use="optional"): self.name = name self.data_type = data_type self.use = use - def setName(self, name): self.name = name - def getName(self): return self.name - def setData_type(self, data_type): self.data_type = data_type - def getData_type(self): return self.data_type - def setUse(self, use): self.use = use - def getUse(self): return self.use + + def setName(self, name): + self.name = name + + def getName(self): + return self.name + + def setData_type(self, data_type): + self.data_type = data_type + + def getData_type(self): + return self.data_type + + def setUse(self, use): + self.use = use + + def getUse(self): + return self.use + + # end class XschemaAttribute @@ -547,15 +628,16 @@ class XschemaHandler(handler.ContentHandler): self.inAttribute = 0 self.inAttributeGroup = 0 self.inSimpleElement = 0 -## self.dbgcount = 1 -## self.dbgnames = [] + + ## self.dbgcount = 1 + ## self.dbgnames = [] def getRoot(self): - #ipshell('Returning root -- Entering ipshell.\\nHit Ctrl-D to exit') + # ipshell('Returning root -- Entering ipshell.\\nHit Ctrl-D to exit') return self.root def showError(self, msg): - print (msg) + print(msg) sys.exit(-1) def startElement(self, name, attrs): @@ -571,9 +653,8 @@ class XschemaHandler(handler.ContentHandler): # "http://www.w3.org/2001/XMLSchema", then remember and # use that namespace prefix. for name, value in attrs.items(): - if name[:6] == 'xmlns:' and \ - value == 'http://www.w3.org/2001/XMLSchema': - nameSpace = name[6:] + ':' + if name[:6] == "xmlns:" and value == "http://www.w3.org/2001/XMLSchema": + nameSpace = name[6:] + ":" set_type_constants(nameSpace) elif name == ElementType or ((name == ComplexTypeType) and (len(self.stack) == 1)): self.inElement = 1 @@ -581,13 +662,13 @@ class XschemaHandler(handler.ContentHandler): element = XschemaElement(attrs) if len(self.stack) == 1: element.setTopLevel(1) - if 'substitutionGroup' in attrs.keys()and 'name' in attrs.keys(): - substituteName = attrs['name'] - headName = attrs['substitutionGroup'] + if "substitutionGroup" in attrs.keys() and "name" in attrs.keys(): + substituteName = attrs["name"] + headName = attrs["substitutionGroup"] if headName not in SubstitutionGroups: SubstitutionGroups[headName] = [] SubstitutionGroups[headName].append(substituteName) - #dbgprint(1, '(startElement) added %s to %s' % (substituteName, headName)) + # dbgprint(1, '(startElement) added %s to %s' % (substituteName, headName)) if name == ComplexTypeType: element.complexType = 1 self.stack.append(element) @@ -605,21 +686,21 @@ class XschemaHandler(handler.ContentHandler): self.inChoice = 1 elif name == AttributeType: self.inAttribute = 1 - if 'name' in attrs.keys(): - name = attrs['name'] + if "name" in attrs.keys(): + name = attrs["name"] # fix-attribute-ref - elif 'ref' in attrs.keys(): - name = strip_namespace(attrs['ref']) + elif "ref" in attrs.keys(): + name = strip_namespace(attrs["ref"]) else: - name = 'no_attribute_name' - if 'type' in attrs.keys(): - data_type = attrs['type'] + name = "no_attribute_name" + if "type" in attrs.keys(): + data_type = attrs["type"] else: data_type = StringType[0] - if 'use' in attrs.keys(): - use = attrs['use'] + if "use" in attrs.keys(): + use = attrs["use"] else: - use = 'optional' + use = "optional" if self.stack[-1].attributeGroup: # Add this attribute to a current attributeGroup. attribute = XschemaAttribute(name, data_type, use) @@ -632,8 +713,8 @@ class XschemaHandler(handler.ContentHandler): self.inAttributeGroup = 1 # If it has attribute 'name', then it's a definition. # Prepare to save it as an attributeGroup. - if 'name' in attrs.keys(): - name = strip_namespace(attrs['name']) + if "name" in attrs.keys(): + name = strip_namespace(attrs["name"]) attributeGroup = XschemaAttributeGroup(name) element = XschemaElement(attrs) if len(self.stack) == 1: @@ -642,26 +723,28 @@ class XschemaHandler(handler.ContentHandler): self.stack.append(element) # If it has attribute 'ref', add it to the list of # attributeGroups for this element/complexType. - if 'ref' in attrs.keys(): - self.stack[-1].attributeGroupNameList.append(attrs['ref']) + if "ref" in attrs.keys(): + self.stack[-1].attributeGroupNameList.append(attrs["ref"]) elif name == ComplexContentType: pass elif name == ExtensionType: - if 'base' in attrs.keys() and len(self.stack) > 0: - extensionBase = attrs['base'] - if extensionBase in StringType or \ - extensionBase == TokenType or \ - extensionBase == DateTimeType or \ - extensionBase == DateType or \ - extensionBase in IntegerType or \ - extensionBase == DecimalType or \ - extensionBase == PositiveIntegerType or \ - extensionBase == NegativeIntegerType or \ - extensionBase == NonPositiveIntegerType or \ - extensionBase == NonNegativeIntegerType or \ - extensionBase == BooleanType or \ - extensionBase == FloatType or \ - extensionBase == DoubleType: + if "base" in attrs.keys() and len(self.stack) > 0: + extensionBase = attrs["base"] + if ( + extensionBase in StringType + or extensionBase == TokenType + or extensionBase == DateTimeType + or extensionBase == DateType + or extensionBase in IntegerType + or extensionBase == DecimalType + or extensionBase == PositiveIntegerType + or extensionBase == NegativeIntegerType + or extensionBase == NonPositiveIntegerType + or extensionBase == NonNegativeIntegerType + or extensionBase == BooleanType + or extensionBase == FloatType + or extensionBase == DoubleType + ): pass else: self.stack[-1].setBase(extensionBase) @@ -705,7 +788,7 @@ class XschemaHandler(handler.ContentHandler): elif name == SchemaType: self.inSchema = 0 if len(self.stack) != 1: - print ('*** error stack. len(self.stack): %d' % len(self.stack)) + print("*** error stack. len(self.stack): %d" % len(self.stack)) sys.exit(-1) self.root = self.stack[0] elif name == ComplexContentType: @@ -728,50 +811,72 @@ class XschemaHandler(handler.ContentHandler): # Code generation # + def generateExportFn_1(outfile, child, name, fill): cleanName = cleanupName(name) - if child.getType() in StringType or \ - child.getType() == TokenType or \ - child.getType() == DateTimeType or \ - child.getType() == DateType: - s1 = '%s showIndent(outfile, level)\n' % fill + if ( + child.getType() in StringType + or child.getType() == TokenType + or child.getType() == DateTimeType + or child.getType() == DateType + ): + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('<%s>%%s\\n' %% quote_xml(self.get%s()))\n" % \ - (fill, name, name, cleanName.capitalize()) + s1 = "%s outfile.write('<%s>%%s\\n' %% quote_xml(self.get%s()))\n" % ( + fill, + name, + name, + cleanName.capitalize(), + ) outfile.write(s1) - elif child.getType() in IntegerType or \ - child.getType() == BooleanType or \ - child.getType() == PositiveIntegerType or \ - child.getType() == NonPositiveIntegerType or \ - child.getType() == NegativeIntegerType or \ - child.getType() == NonNegativeIntegerType: - s1 = '%s showIndent(outfile, level)\n' % fill + elif ( + child.getType() in IntegerType + or child.getType() == BooleanType + or child.getType() == PositiveIntegerType + or child.getType() == NonPositiveIntegerType + or child.getType() == NegativeIntegerType + or child.getType() == NonNegativeIntegerType + ): + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('<%s>%%d\\n' %% self.get%s())\n" % \ - (fill, name, name, cleanName.capitalize()) + s1 = "%s outfile.write('<%s>%%d\\n' %% self.get%s())\n" % ( + fill, + name, + name, + cleanName.capitalize(), + ) outfile.write(s1) - elif child.getType() == FloatType or \ - child.getType() == DecimalType: - s1 = '%s showIndent(outfile, level)\n' % fill + elif child.getType() == FloatType or child.getType() == DecimalType: + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('<%s>%%f\\n' %% self.get%s())\n" % \ - (fill, name, name, cleanName.capitalize()) + s1 = "%s outfile.write('<%s>%%f\\n' %% self.get%s())\n" % ( + fill, + name, + name, + cleanName.capitalize(), + ) outfile.write(s1) elif child.getType() == DoubleType: - s1 = '%s showIndent(outfile, level)\n' % fill + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('<%s>%%e\\n' %% self.get%s())\n" % \ - (fill, name, name, cleanName.capitalize()) + s1 = "%s outfile.write('<%s>%%e\\n' %% self.get%s())\n" % ( + fill, + name, + name, + cleanName.capitalize(), + ) outfile.write(s1) else: s1 = "%s if self.%s:\n" % (fill, cleanName) outfile.write(s1) if name == child.getType(): - s1 = "%s self.%s.export(outfile, level)\n" % \ - (fill, cleanName) + s1 = "%s self.%s.export(outfile, level)\n" % (fill, cleanName) else: - s1 = "%s self.%s.export(outfile, level, name_='%s')\n" % \ - (fill, cleanName, name) + s1 = "%s self.%s.export(outfile, level, name_='%s')\n" % ( + fill, + cleanName, + name, + ) outfile.write(s1) @@ -779,45 +884,67 @@ def generateExportFn_2(outfile, child, name, fill): cleanName = cleanupName(name) s1 = "%s for %s_ in self.get%s():\n" % (fill, cleanName, cleanName.capitalize()) outfile.write(s1) - if child.getType() in StringType or \ - child.getType() == TokenType or \ - child.getType() == DateTimeType or \ - child.getType() == DateType: - s1 = '%s showIndent(outfile, level)\n' % fill + if ( + child.getType() in StringType + or child.getType() == TokenType + or child.getType() == DateTimeType + or child.getType() == DateType + ): + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('<%s>%%s\\n' %% quote_xml(%s_))\n" % \ - (fill, name, name, cleanName,) + s1 = "%s outfile.write('<%s>%%s\\n' %% quote_xml(%s_))\n" % ( + fill, + name, + name, + cleanName, + ) outfile.write(s1) - elif child.getType() in IntegerType or \ - child.getType() == BooleanType or \ - child.getType() == PositiveIntegerType or \ - child.getType() == NonPositiveIntegerType or \ - child.getType() == NegativeIntegerType or \ - child.getType() == NonNegativeIntegerType: - s1 = '%s showIndent(outfile, level)\n' % fill + elif ( + child.getType() in IntegerType + or child.getType() == BooleanType + or child.getType() == PositiveIntegerType + or child.getType() == NonPositiveIntegerType + or child.getType() == NegativeIntegerType + or child.getType() == NonNegativeIntegerType + ): + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('<%s>%%d\\n' %% %s_)\n" % \ - (fill, name, name, cleanName, ) + s1 = "%s outfile.write('<%s>%%d\\n' %% %s_)\n" % ( + fill, + name, + name, + cleanName, + ) outfile.write(s1) - elif child.getType() == FloatType or \ - child.getType() == DecimalType: - s1 = '%s showIndent(outfile, level)\n' % fill + elif child.getType() == FloatType or child.getType() == DecimalType: + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('<%s>%%f\\n' %% %s_)\n" % \ - (fill, name, name, cleanName, ) + s1 = "%s outfile.write('<%s>%%f\\n' %% %s_)\n" % ( + fill, + name, + name, + cleanName, + ) outfile.write(s1) elif child.getType() == DoubleType: - s1 = '%s showIndent(outfile, level)\n' % fill + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('<%s>%%e\\n' %% %s_)\n" % \ - (fill, name, name, cleanName) + s1 = "%s outfile.write('<%s>%%e\\n' %% %s_)\n" % ( + fill, + name, + name, + cleanName, + ) outfile.write(s1) else: if name == child.getType(): s1 = "%s %s_.export(outfile, level)\n" % (fill, cleanName) else: - s1 = "%s %s_.export(outfile, level, name_='%s')\n" % \ - (fill, cleanName, cleanName, ) + s1 = "%s %s_.export(outfile, level, name_='%s')\n" % ( + fill, + cleanName, + cleanName, + ) outfile.write(s1) @@ -830,18 +957,22 @@ def generateExportAttributes(outfile, element, hasAttributes): name = attrDef.getName() cleanName = cleanupName(name) capName = cleanName.capitalize() - if attrDef.getUse() == 'optional': - s1 = " if self.get%s() is not None:\n" % (capName, ) + if attrDef.getUse() == "optional": + s1 = " if self.get%s() is not None:\n" % (capName,) outfile.write(s1) - s1 = " outfile.write(' %s=\"%%s\"' %% (self.get%s(), ))\n" % \ - (name, capName, ) + s1 = " outfile.write(' %s=\"%%s\"' %% (self.get%s(), ))\n" % ( + name, + capName, + ) outfile.write(s1) else: - s1 = " outfile.write(' %s=\"%%s\"' %% (self.get%s(), ))\n" % \ - (name, capName, ) + s1 = " outfile.write(' %s=\"%%s\"' %% (self.get%s(), ))\n" % ( + name, + capName, + ) outfile.write(s1) if element.getAnyAttribute(): - s1 = ' for name, value in self.anyAttributes_.items():\n' + s1 = " for name, value in self.anyAttributes_.items():\n" outfile.write(s1) s1 = " outfile.write(' %s=\"%s\"' % (name, value, ))\n" outfile.write(s1) @@ -860,13 +991,13 @@ def generateExportChildren(outfile, element, hasChildren): for child in element.getChildren(): name = child.getName() if child.getMaxOccurs() > 1: - generateExportFn_2(outfile, child, name, ' ') + generateExportFn_2(outfile, child, name, " ") else: - generateExportFn_1(outfile, child, name, '') -## base = element.getBase() -## if base and base in ElementDict: -## parent = ElementDict[base] -## hasAttributes = generateExportChildren(outfile, parent, hasChildren) + generateExportFn_1(outfile, child, name, "") + ## base = element.getBase() + ## if base and base in ElementDict: + ## parent = ElementDict[base] + ## hasAttributes = generateExportChildren(outfile, parent, hasChildren) return hasChildren @@ -881,17 +1012,15 @@ def countChildren(element, count): def generateExportFn(outfile, prefix, element): base = element.getBase() - s1 = " def export(self, outfile, level, name_='%s'):\n" % \ - element.getName() + s1 = " def export(self, outfile, level, name_='%s'):\n" % element.getName() outfile.write(s1) - s1 = ' showIndent(outfile, level)\n' + s1 = " showIndent(outfile, level)\n" outfile.write(s1) if len(element.getAttributeDefs()) > 0: s1 = " outfile.write('<%s' % (name_, ))\n" outfile.write(s1) - s1 = " self.exportAttributes(outfile, level, name_='%s')\n" % \ - element.getName() + s1 = " self.exportAttributes(outfile, level, name_='%s')\n" % element.getName() outfile.write(s1) if element.isMixed(): s1 = " outfile.write('>')\n" @@ -907,34 +1036,34 @@ def generateExportFn(outfile, prefix, element): s1 = " self.exportChildren(outfile, level + 1, name_)\n" outfile.write(s1) - s1 = ' showIndent(outfile, level)\n' + s1 = " showIndent(outfile, level)\n" outfile.write(s1) s1 = " outfile.write('\\n' % name_)\n" outfile.write(s1) - s1 = " def exportAttributes(self, outfile, level, name_='%s'):\n" % \ - element.getName() + s1 = " def exportAttributes(self, outfile, level, name_='%s'):\n" % element.getName() outfile.write(s1) hasAttributes = 0 hasAttributes = generateExportAttributes(outfile, element, hasAttributes) if base: hasAttributes += 1 - s1 = " %s.exportAttributes(self, outfile, level, name_='%s')\n" % \ - (base, element.getName(), ) + s1 = " %s.exportAttributes(self, outfile, level, name_='%s')\n" % ( + base, + element.getName(), + ) outfile.write(s1) if hasAttributes == 0: s1 = " pass\n" outfile.write(s1) -## if len(element.getChildren()) > 0 and not element.isMixed(): -## s1 = ' showIndent(outfile, level)\n' -## outfile.write(s1) - s1 = " def exportChildren(self, outfile, level, name_='%s'):\n" % \ - element.getName() + ## if len(element.getChildren()) > 0 and not element.isMixed(): + ## s1 = ' showIndent(outfile, level)\n' + ## outfile.write(s1) + s1 = " def exportChildren(self, outfile, level, name_='%s'):\n" % element.getName() outfile.write(s1) hasChildren = 0 hasChildren = generateExportChildren(outfile, element, hasChildren) if base: hasChildren += 1 - s1 = " %s.exportChildren(self, outfile, level, name_)\n" % (base, ) + s1 = " %s.exportChildren(self, outfile, level, name_)\n" % (base,) outfile.write(s1) count = countChildren(element, 0) if count == 0: @@ -946,111 +1075,139 @@ def generateExportFn(outfile, prefix, element): # Generate exportLiteral method. # + def generateExportLiteralFn_1(outfile, child, name, fill): mappedName = mapName(name) - if child.getType() in StringType or \ - child.getType() == TokenType or \ - child.getType() == DateTimeType or \ - child.getType() == DateType: - s1 = '%s showIndent(outfile, level)\n' % fill + if ( + child.getType() in StringType + or child.getType() == TokenType + or child.getType() == DateTimeType + or child.getType() == DateType + ): + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('%s=%%s,\\n' %% quote_python(self.get%s()))\n" % \ - (fill, mappedName, name.capitalize()) + s1 = "%s outfile.write('%s=%%s,\\n' %% quote_python(self.get%s()))\n" % ( + fill, + mappedName, + name.capitalize(), + ) outfile.write(s1) - elif child.getType() in IntegerType or \ - child.getType() == BooleanType or \ - child.getType() == PositiveIntegerType or \ - child.getType() == NonPositiveIntegerType or \ - child.getType() == NegativeIntegerType or \ - child.getType() == NonNegativeIntegerType: - s1 = '%s showIndent(outfile, level)\n' % fill + elif ( + child.getType() in IntegerType + or child.getType() == BooleanType + or child.getType() == PositiveIntegerType + or child.getType() == NonPositiveIntegerType + or child.getType() == NegativeIntegerType + or child.getType() == NonNegativeIntegerType + ): + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('%s=%%d,\\n' %% self.get%s())\n" % \ - (fill, mappedName, name.capitalize()) + s1 = "%s outfile.write('%s=%%d,\\n' %% self.get%s())\n" % ( + fill, + mappedName, + name.capitalize(), + ) outfile.write(s1) - elif child.getType() == FloatType or \ - child.getType() == DecimalType: - s1 = '%s showIndent(outfile, level)\n' % fill + elif child.getType() == FloatType or child.getType() == DecimalType: + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('%s=%%f,\\n' %% self.get%s())\n" % \ - (fill, mappedName, name.capitalize()) + s1 = "%s outfile.write('%s=%%f,\\n' %% self.get%s())\n" % ( + fill, + mappedName, + name.capitalize(), + ) outfile.write(s1) elif child.getType() == DoubleType: - s1 = '%s showIndent(outfile, level)\n' % fill + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('%s=%%e,\\n' %% self.get%s())\n" % \ - (fill, name, name.capitalize()) + s1 = "%s outfile.write('%s=%%e,\\n' %% self.get%s())\n" % ( + fill, + name, + name.capitalize(), + ) outfile.write(s1) else: s1 = "%s if self.%s:\n" % (fill, name) outfile.write(s1) - s1 = '%s showIndent(outfile, level)\n' % fill + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('%s=%s(\\n')\n" % \ - (fill, name, child.getType()) + s1 = "%s outfile.write('%s=%s(\\n')\n" % ( + fill, + name, + child.getType(), + ) outfile.write(s1) if name == child.getType(): - s1 = "%s self.%s.exportLiteral(outfile, level)\n" % \ - (fill, name) + s1 = "%s self.%s.exportLiteral(outfile, level)\n" % (fill, name) else: - s1 = "%s self.%s.exportLiteral(outfile, level, name_='%s')\n" % \ - (fill, name, name) + s1 = "%s self.%s.exportLiteral(outfile, level, name_='%s')\n" % ( + fill, + name, + name, + ) outfile.write(s1) - s1 = '%s showIndent(outfile, level)\n' % fill + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('),\\n')\n" % (fill, ) + s1 = "%s outfile.write('),\\n')\n" % (fill,) outfile.write(s1) def generateExportLiteralFn_2(outfile, child, name, fill): - if child.getType() in StringType or \ - child.getType() == TokenType or \ - child.getType() == DateTimeType or \ - child.getType() == DateType: - s1 = '%s showIndent(outfile, level)\n' % fill + if ( + child.getType() in StringType + or child.getType() == TokenType + or child.getType() == DateTimeType + or child.getType() == DateType + ): + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('%%s,\\n' %% quote_python(%s))\n" % \ - (fill, name) + s1 = "%s outfile.write('%%s,\\n' %% quote_python(%s))\n" % (fill, name) outfile.write(s1) - elif child.getType() in IntegerType or \ - child.getType() == BooleanType or \ - child.getType() == PositiveIntegerType or \ - child.getType() == NonPositiveIntegerType or \ - child.getType() == NegativeIntegerType or \ - child.getType() == NonNegativeIntegerType: - s1 = '%s showIndent(outfile, level)\n' % fill + elif ( + child.getType() in IntegerType + or child.getType() == BooleanType + or child.getType() == PositiveIntegerType + or child.getType() == NonPositiveIntegerType + or child.getType() == NegativeIntegerType + or child.getType() == NonNegativeIntegerType + ): + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('%%d,\\n' %% %s)\n" % \ - (fill, name) + s1 = "%s outfile.write('%%d,\\n' %% %s)\n" % (fill, name) outfile.write(s1) - elif child.getType() == FloatType or \ - child.getType() == DecimalType: - s1 = '%s showIndent(outfile, level)\n' % fill + elif child.getType() == FloatType or child.getType() == DecimalType: + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('%%f,\\n' %% %s)\n" % \ - (fill, name) + s1 = "%s outfile.write('%%f,\\n' %% %s)\n" % (fill, name) outfile.write(s1) elif child.getType() == DoubleType: - s1 = '%s showIndent(outfile, level)\n' % fill + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('%%e,\\n' %% %s)\n" % \ - (fill, name) + s1 = "%s outfile.write('%%e,\\n' %% %s)\n" % (fill, name) outfile.write(s1) else: - s1 = '%s showIndent(outfile, level)\n' % fill + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('%s(\\n')\n" % \ - (fill, cleanupName(child.getType())) + s1 = "%s outfile.write('%s(\\n')\n" % ( + fill, + cleanupName(child.getType()), + ) outfile.write(s1) if name == child.getType(): - s1 = "%s %s.exportLiteral(outfile, level)\n" % (fill, child.getType()) + s1 = "%s %s.exportLiteral(outfile, level)\n" % ( + fill, + child.getType(), + ) else: - s1 = "%s %s.exportLiteral(outfile, level, name_='%s')\n" % \ - (fill, name, name) + s1 = "%s %s.exportLiteral(outfile, level, name_='%s')\n" % ( + fill, + name, + name, + ) outfile.write(s1) - s1 = '%s showIndent(outfile, level)\n' % fill + s1 = "%s showIndent(outfile, level)\n" % fill outfile.write(s1) - s1 = "%s outfile.write('),\\n')\n" % (fill, ) + s1 = "%s outfile.write('),\\n')\n" % (fill,) outfile.write(s1) @@ -1077,27 +1234,30 @@ def generateExportLiteralFn(outfile, prefix, element): mappedName = mapName(cleanName) s1 = " showIndent(outfile, level)\n" outfile.write(s1) -## ipshell('(generateExportLiteral) -- Entering ipshell.\\nHit Ctrl-D to exit') + ## ipshell('(generateExportLiteral) -- Entering ipshell.\\nHit Ctrl-D to exit') stringType = 0 data_type = attrDef.getData_type() - if data_type.find('string') >= 0: + if data_type.find("string") >= 0: stringType = 1 else: stringType = 1 if stringType: - s1 = " outfile.write('%s = \"%%s\",\\n' %% (self.get%s(),))\n" % \ - (mappedName, capName,) + s1 = " outfile.write('%s = \"%%s\",\\n' %% (self.get%s(),))\n" % ( + mappedName, + capName, + ) else: - s1 = " outfile.write('%s = %%s,\\n' %% (self.get%s(),))\n" % \ - (mappedName, capName,) + s1 = " outfile.write('%s = %%s,\\n' %% (self.get%s(),))\n" % ( + mappedName, + capName, + ) outfile.write(s1) - if element.getAnyAttribute(): count += 1 - s1 = ' for name, value in self.anyAttributes_.items():\n' + s1 = " for name, value in self.anyAttributes_.items():\n" outfile.write(s1) - s1 = ' showIndent(outfile, level)\n' + s1 = " showIndent(outfile, level)\n" outfile.write(s1) s1 = " outfile.write('%s = \"%s\",\\n' % (name, value,))\n" outfile.write(s1) @@ -1105,25 +1265,24 @@ def generateExportLiteralFn(outfile, prefix, element): s1 = " pass\n" outfile.write(s1) if base: - s1 = " %s.exportLiteralAttributes(self, outfile, level, name_)\n" % \ - (base, ) + s1 = " %s.exportLiteralAttributes(self, outfile, level, name_)\n" % (base,) outfile.write(s1) s1 = " def exportLiteralChildren(self, outfile, level, name_):\n" outfile.write(s1) for child in element.getChildren(): name = child.getName() name = cleanupName(name) - #unmappedName = child.getUnmappedCleanName() - #cleanName = cleanupName(name) - #mappedName = mapName(cleanName) + # unmappedName = child.getUnmappedCleanName() + # cleanName = cleanupName(name) + # mappedName = mapName(cleanName) if element.isMixed(): s1 = " showIndent(outfile, level)\n" outfile.write(s1) s1 = " outfile.write('content_ = [\\n')\n" outfile.write(s1) - s1 = ' for item_ in self.content_:\n' + s1 = " for item_ in self.content_:\n" outfile.write(s1) - s1 = ' item_.exportLiteral(outfile, level, name_)\n' + s1 = " item_.exportLiteral(outfile, level, name_)\n" outfile.write(s1) s1 = " showIndent(outfile, level)\n" outfile.write(s1) @@ -1139,7 +1298,7 @@ def generateExportLiteralFn(outfile, prefix, element): outfile.write(s1) s1 = " for %s in self.%s:\n" % (name, name) outfile.write(s1) - generateExportLiteralFn_2(outfile, child, name, ' ') + generateExportLiteralFn_2(outfile, child, name, " ") s1 = " level -= 1\n" outfile.write(s1) s1 = " showIndent(outfile, level)\n" @@ -1147,24 +1306,24 @@ def generateExportLiteralFn(outfile, prefix, element): s1 = " outfile.write('],\\n')\n" outfile.write(s1) else: - generateExportLiteralFn_1(outfile, child, name, '') + generateExportLiteralFn_1(outfile, child, name, "") if len(element.getChildren()) == 0: s1 = " showIndent(outfile, level)\n" outfile.write(s1) s1 = " outfile.write('valueOf_ = \"%s\",\\n' % (self.valueOf_,))\n" outfile.write(s1) if base: - s1 = " %s.exportLiteralChildren(self, outfile, level, name_)\n" % \ - (base, ) + s1 = " %s.exportLiteralChildren(self, outfile, level, name_)\n" % (base,) outfile.write(s1) - #s1 = " level -= 1\n" - #outfile.write(s1) + # s1 = " level -= 1\n" + # outfile.write(s1) # # Generate build method. # + def generateBuildAttributes(outfile, element, hasAttributes): attrDefs = element.getAttributeDefs() for key in attrDefs: @@ -1174,96 +1333,103 @@ def generateBuildAttributes(outfile, element, hasAttributes): cleanName = cleanupName(name) mappedName = mapName(cleanName) atype = attrDef.getData_type() - if atype in IntegerType or \ - atype == PositiveIntegerType or \ - atype == NonPositiveIntegerType or \ - atype == NegativeIntegerType or \ - atype == NonNegativeIntegerType: + if ( + atype in IntegerType + or atype == PositiveIntegerType + or atype == NonPositiveIntegerType + or atype == NegativeIntegerType + or atype == NonNegativeIntegerType + ): s1 = " if attrs.get('%s'):\n" % name outfile.write(s1) - s1 = ' try:\n' + s1 = " try:\n" outfile.write(s1) - s1 = " self.%s = int(attrs.get('%s').value)\n" % \ - (mappedName, name) + s1 = " self.%s = int(attrs.get('%s').value)\n" % ( + mappedName, + name, + ) outfile.write(s1) - s1 = ' except ValueError:\n' + s1 = " except ValueError:\n" outfile.write(s1) - s1 = " raise ValueError('Bad integer attribute (%s)')\n" % \ - (name, ) + s1 = " raise ValueError('Bad integer attribute (%s)')\n" % (name,) outfile.write(s1) if atype == PositiveIntegerType: - s1 = ' if self.%s <= 0:\n' % mappedName - outfile.write(s1) + s1 = " if self.%s <= 0:\n" % mappedName + outfile.write(s1) s1 = " raise ValueError('Invalid PositiveInteger (%s)')\n" % name outfile.write(s1) elif atype == NonPositiveIntegerType: - s1 = ' if self.%s > 0:\n' % mappedName + s1 = " if self.%s > 0:\n" % mappedName outfile.write(s1) s1 = " raise ValueError('Invalid NonPositiveInteger (%s)')\n" % name outfile.write(s1) elif atype == NegativeIntegerType: - s1 = ' if self.%s >= 0:\n' % mappedName + s1 = " if self.%s >= 0:\n" % mappedName outfile.write(s1) s1 = " raise ValueError('Invalid NegativeInteger (%s)')\n" % name outfile.write(s1) elif atype == NonNegativeIntegerType: - s1 = ' if self.%s < 0:\n' % mappedName + s1 = " if self.%s < 0:\n" % mappedName outfile.write(s1) s1 = " raise ValueError('Invalid NonNegativeInteger (%s)')\n" % name outfile.write(s1) elif atype == BooleanType: - s1 = " if attrs.get('%s'):\n" % (name, ) + s1 = " if attrs.get('%s'):\n" % (name,) outfile.write(s1) - s1 = " if attrs.get('%s').value in ('true', '1'):\n" % \ - (name, ) + s1 = " if attrs.get('%s').value in ('true', '1'):\n" % (name,) outfile.write(s1) - s1 = " self.%s = 1\n" % (mappedName, ) + s1 = " self.%s = 1\n" % (mappedName,) outfile.write(s1) - s1 = " elif attrs.get('%s').value in ('false', '0'):\n" % \ - (name, ) + s1 = " elif attrs.get('%s').value in ('false', '0'):\n" % (name,) outfile.write(s1) - s1 = " self.%s = 0\n" % (mappedName, ) + s1 = " self.%s = 0\n" % (mappedName,) outfile.write(s1) - s1 = ' else:\n' + s1 = " else:\n" outfile.write(s1) - s1 = " raise ValueError('Bad boolean attribute (%s)')\n" % \ - (name, ) + s1 = " raise ValueError('Bad boolean attribute (%s)')\n" % (name,) outfile.write(s1) elif atype == FloatType or atype == DoubleType or atype == DecimalType: - s1 = " if attrs.get('%s'):\n" % (name, ) + s1 = " if attrs.get('%s'):\n" % (name,) outfile.write(s1) - s1 = ' try:\n' + s1 = " try:\n" outfile.write(s1) - s1 = " self.%s = float(attrs.get('%s').value)\n" % \ - (mappedName, name, ) + s1 = " self.%s = float(attrs.get('%s').value)\n" % ( + mappedName, + name, + ) outfile.write(s1) - s1 = ' except:\n' + s1 = " except:\n" outfile.write(s1) - s1 = " raise ValueError('Bad float/double attribute (%s)')\n" % \ - (name, ) + s1 = " raise ValueError('Bad float/double attribute (%s)')\n" % (name,) outfile.write(s1) elif atype == TokenType: - s1 = " if attrs.get('%s'):\n" % (name, ) + s1 = " if attrs.get('%s'):\n" % (name,) outfile.write(s1) - s1 = " self.%s = attrs.get('%s').value\n" % \ - (mappedName, name, ) + s1 = " self.%s = attrs.get('%s').value\n" % ( + mappedName, + name, + ) outfile.write(s1) - s1 = " self.%s = ' '.join(self.%s.split())\n" % \ - (mappedName, mappedName, ) + s1 = " self.%s = ' '.join(self.%s.split())\n" % ( + mappedName, + mappedName, + ) outfile.write(s1) else: # Assume attr['type'] in StringType or attr['type'] == DateTimeType: - s1 = " if attrs.get('%s'):\n" % (name, ) + s1 = " if attrs.get('%s'):\n" % (name,) outfile.write(s1) - s1 = " self.%s = attrs.get('%s').value\n" % \ - (mappedName, name, ) + s1 = " self.%s = attrs.get('%s').value\n" % ( + mappedName, + name, + ) outfile.write(s1) if element.getAnyAttribute(): - s1 = ' self.anyAttributes_ = {}\n' + s1 = " self.anyAttributes_ = {}\n" outfile.write(s1) - s1 = ' for name, value in attrs.items():\n' + s1 = " for name, value in attrs.items():\n" outfile.write(s1) - s1List = [' if'] + s1List = [" if"] firstTime = 1 for key in attrDefs: if firstTime: @@ -1271,10 +1437,10 @@ def generateBuildAttributes(outfile, element, hasAttributes): firstTime = 0 else: s1List.append(' and name != "%s"' % key) - s1List.append(':\n') - s1 = ''.join(s1List) + s1List.append(":\n") + s1 = "".join(s1List) outfile.write(s1) - s1 = ' self.anyAttributes_[name] = value\n' + s1 = " self.anyAttributes_[name] = value\n" outfile.write(s1) return hasAttributes @@ -1286,12 +1452,13 @@ def generateBuildMixed_1(outfile, prefix, child, headChild, keyword, delayed): name = child.getCleanName() headName = cleanupName(headChild.getName()) childType = child.getType() - if childType in StringType or \ - childType == TokenType or \ - childType == DateTimeType or \ - childType == DateType: - s1 = ' %s child_.nodeType == Node.ELEMENT_NODE and \\\n' % \ - keyword + if ( + childType in StringType + or childType == TokenType + or childType == DateTimeType + or childType == DateType + ): + s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword outfile.write(s1) s1 = " nodeName_ == '%s':\n" % origName outfile.write(s1) @@ -1308,18 +1475,18 @@ def generateBuildMixed_1(outfile, prefix, child, headChild, keyword, delayed): outfile.write(s1) s1 = " obj_ = self.mixedclass_(MixedContainer.CategorySimple,\n" outfile.write(s1) - s1 = " MixedContainer.TypeString, '%s', valuestr_)\n" % \ - origName + s1 = " MixedContainer.TypeString, '%s', valuestr_)\n" % origName outfile.write(s1) s1 = " self.content_.append(obj_)\n" outfile.write(s1) - elif childType in IntegerType or \ - childType == PositiveIntegerType or \ - childType == NonPositiveIntegerType or \ - childType == NegativeIntegerType or \ - childType == NonNegativeIntegerType: - s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % \ - keyword + elif ( + childType in IntegerType + or childType == PositiveIntegerType + or childType == NonPositiveIntegerType + or childType == NegativeIntegerType + or childType == NonNegativeIntegerType + ): + s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword outfile.write(s1) s1 = " nodeName_ == '%s':\n" % origName outfile.write(s1) @@ -1361,14 +1528,12 @@ def generateBuildMixed_1(outfile, prefix, child, headChild, keyword, delayed): outfile.write(s1) s1 = " obj_ = self.mixedclass_(MixedContainer.CategorySimple,\n" outfile.write(s1) - s1 = " MixedContainer.TypeInteger, '%s', ival_)\n" % \ - origName + s1 = " MixedContainer.TypeInteger, '%s', ival_)\n" % origName outfile.write(s1) s1 = " self.content_.append(obj_)\n" outfile.write(s1) elif childType == BooleanType: - s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % \ - keyword + s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword outfile.write(s1) s1 = " nodeName_ == '%s':\n" % origName outfile.write(s1) @@ -1390,16 +1555,12 @@ def generateBuildMixed_1(outfile, prefix, child, headChild, keyword, delayed): outfile.write(s1) s1 = " obj_ = self.mixedclass_(MixedContainer.CategorySimple,\n" outfile.write(s1) - s1 = " MixedContainer.TypeInteger, '%s', ival_)\n" % \ - origName + s1 = " MixedContainer.TypeInteger, '%s', ival_)\n" % origName outfile.write(s1) s1 = " self.content_.append(obj_)\n" outfile.write(s1) - elif childType == FloatType or \ - childType == DoubleType or \ - childType == DecimalType: - s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % \ - keyword + elif childType == FloatType or childType == DoubleType or childType == DecimalType: + s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword outfile.write(s1) s1 = " nodeName_ == '%s':\n" % origName outfile.write(s1) @@ -1417,8 +1578,7 @@ def generateBuildMixed_1(outfile, prefix, child, headChild, keyword, delayed): outfile.write(s1) s1 = " obj_ = self.mixedclass_(MixedContainer.CategorySimple,\n" outfile.write(s1) - s1 = " MixedContainer.TypeFloat, '%s', fval_)\n" % \ - origName + s1 = " MixedContainer.TypeFloat, '%s', fval_)\n" % origName outfile.write(s1) s1 = " self.content_.append(obj_)\n" outfile.write(s1) @@ -1428,20 +1588,20 @@ def generateBuildMixed_1(outfile, prefix, child, headChild, keyword, delayed): if not delayed and not child in DelayedElements: DelayedElements.append(child) DelayedElements_subclass.append(child) - s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % \ - keyword + s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword outfile.write(s1) s1 = " nodeName_ == '%s':\n" % origName outfile.write(s1) - s1 = " childobj_ = %s%s.factory()\n" % \ - (prefix, cleanupName(mapName(childType))) + s1 = " childobj_ = %s%s.factory()\n" % ( + prefix, + cleanupName(mapName(childType)), + ) outfile.write(s1) s1 = " childobj_.build(child_)\n" outfile.write(s1) s1 = " obj_ = self.mixedclass_(MixedContainer.CategoryComplex,\n" outfile.write(s1) - s1 = " MixedContainer.TypeNone, '%s', childobj_)\n" % \ - origName + s1 = " MixedContainer.TypeNone, '%s', childobj_)\n" % origName outfile.write(s1) s1 = " self.content_.append(obj_)\n" outfile.write(s1) @@ -1451,15 +1611,14 @@ def generateBuildMixed(outfile, prefix, element, keyword, delayed, hasChildren): for child in element.getChildren(): generateBuildMixed_1(outfile, prefix, child, child, keyword, delayed) hasChildren += 1 - keyword = 'elif' + keyword = "elif" # Does this element have a substitutionGroup? # If so generate a clause for each element in the substitutionGroup. if child.getName() in SubstitutionGroups: for memberName in SubstitutionGroups[child.getName()]: if memberName in ElementDict: member = ElementDict[memberName] - generateBuildMixed_1(outfile, prefix, member, child, - keyword, delayed) + generateBuildMixed_1(outfile, prefix, member, child, keyword, delayed) s1 = " %s child_.nodeType == Node.TEXT_NODE:\n" % keyword outfile.write(s1) s1 = " obj_ = self.mixedclass_(MixedContainer.CategoryText,\n" @@ -1468,10 +1627,10 @@ def generateBuildMixed(outfile, prefix, element, keyword, delayed, hasChildren): outfile.write(s1) s1 = " self.content_.append(obj_)\n" outfile.write(s1) -## base = element.getBase() -## if base and base in ElementDict: -## parent = ElementDict[base] -## hasChildren = generateBuildMixed(outfile, prefix, parent, keyword, delayed, hasChildren) + ## base = element.getBase() + ## if base and base in ElementDict: + ## parent = ElementDict[base] + ## hasChildren = generateBuildMixed(outfile, prefix, parent, keyword, delayed, hasChildren) return hasChildren @@ -1482,17 +1641,16 @@ def generateBuildStandard_1(outfile, prefix, child, headChild, keyword, delayed) mappedName = mapName(name) headName = cleanupName(headChild.getName()) attrCount = len(child.getAttributeDefs()) - #dbgprint(1, '(gbs) name: %s type: %s complex: %s id: %s' % \ + # dbgprint(1, '(gbs) name: %s type: %s complex: %s id: %s' % \ # (child.getName(), child.getType(), child.isComplex(), id(child), )) childType = child.getType() - if attrCount == 0 and \ - (childType in StringType or \ - childType == TokenType or \ - childType == DateTimeType or \ - childType == DateType \ - ): - s1 = ' %s child_.nodeType == Node.ELEMENT_NODE and \\\n' % \ - keyword + if attrCount == 0 and ( + childType in StringType + or childType == TokenType + or childType == DateTimeType + or childType == DateType + ): + s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword outfile.write(s1) s1 = " nodeName_ == '%s':\n" % origName outfile.write(s1) @@ -1503,21 +1661,31 @@ def generateBuildStandard_1(outfile, prefix, child, headChild, keyword, delayed) s1 = " %s_ += text__content_.nodeValue\n" % name outfile.write(s1) if childType == TokenType: - s1 = " %s_ = ' '.join(%s_.split())\n" % (name, name, ) + s1 = " %s_ = ' '.join(%s_.split())\n" % ( + name, + name, + ) outfile.write(s1) if child.getMaxOccurs() > 1: - s1 = " self.%s.append(%s_)\n" % (mappedName, name, ) + s1 = " self.%s.append(%s_)\n" % ( + mappedName, + name, + ) outfile.write(s1) else: - s1 = " self.%s = %s_\n" % (mappedName, name, ) + s1 = " self.%s = %s_\n" % ( + mappedName, + name, + ) outfile.write(s1) - elif childType in IntegerType or \ - childType == PositiveIntegerType or \ - childType == NonPositiveIntegerType or \ - childType == NegativeIntegerType or \ - childType == NonNegativeIntegerType: - s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % \ - keyword + elif ( + childType in IntegerType + or childType == PositiveIntegerType + or childType == NonPositiveIntegerType + or childType == NegativeIntegerType + or childType == NonNegativeIntegerType + ): + s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword outfile.write(s1) s1 = " nodeName_ == '%s':\n" % origName outfile.write(s1) @@ -1554,14 +1722,13 @@ def generateBuildStandard_1(outfile, prefix, child, headChild, keyword, delayed) s1 = " raise ValueError('requires nonNegativeInteger -- %s' % child_.toxml())\n" outfile.write(s1) if child.getMaxOccurs() > 1: - s1 = " self.%s.append(ival_)\n" % (mappedName, ) + s1 = " self.%s.append(ival_)\n" % (mappedName,) outfile.write(s1) else: - s1 = " self.%s = ival_\n" % (mappedName, ) + s1 = " self.%s = ival_\n" % (mappedName,) outfile.write(s1) elif childType == BooleanType: - s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % \ - keyword + s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword outfile.write(s1) s1 = " nodeName_ == '%s':\n" % origName outfile.write(s1) @@ -1582,16 +1749,13 @@ def generateBuildStandard_1(outfile, prefix, child, headChild, keyword, delayed) s1 = " raise ValueError('requires boolean -- %s' % child_.toxml())\n" outfile.write(s1) if child.getMaxOccurs() > 1: - s1 = " self.%s.append(ival_)\n" % (mappedName, ) + s1 = " self.%s.append(ival_)\n" % (mappedName,) outfile.write(s1) else: - s1 = " self.%s = ival_\n" % (mappedName, ) + s1 = " self.%s = ival_\n" % (mappedName,) outfile.write(s1) - elif childType == FloatType or \ - childType == DoubleType or \ - childType == DecimalType: - s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % \ - keyword + elif childType == FloatType or childType == DoubleType or childType == DecimalType: + s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword outfile.write(s1) s1 = " nodeName_ == '%s':\n" % origName outfile.write(s1) @@ -1608,10 +1772,10 @@ def generateBuildStandard_1(outfile, prefix, child, headChild, keyword, delayed) s1 = " raise ValueError('requires float (or double) -- %s' % child_.toxml())\n" outfile.write(s1) if child.getMaxOccurs() > 1: - s1 = " self.%s.append(fval_)\n" % (mappedName, ) + s1 = " self.%s.append(fval_)\n" % (mappedName,) outfile.write(s1) else: - s1 = " self.%s = fval_\n" % (mappedName, ) + s1 = " self.%s = fval_\n" % (mappedName,) outfile.write(s1) else: # Perhaps it's a complexType that is defined right here. @@ -1619,13 +1783,14 @@ def generateBuildStandard_1(outfile, prefix, child, headChild, keyword, delayed) if not delayed and not child in DelayedElements: DelayedElements.append(child) DelayedElements_subclass.append(child) - s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % \ - keyword + s1 = " %s child_.nodeType == Node.ELEMENT_NODE and \\\n" % keyword outfile.write(s1) s1 = " nodeName_ == '%s':\n" % origName outfile.write(s1) - s1 = " obj_ = %s%s.factory()\n" % \ - (prefix, cleanupName(mapName(childType))) + s1 = " obj_ = %s%s.factory()\n" % ( + prefix, + cleanupName(mapName(childType)), + ) outfile.write(s1) s1 = " obj_.build(child_)\n" outfile.write(s1) @@ -1639,51 +1804,48 @@ def generateBuildStandard_1(outfile, prefix, child, headChild, keyword, delayed) def generateBuildStandard(outfile, prefix, element, keyword, delayed, hasChildren): for child in element.getChildren(): - #dbgprint(1, '(generateBuildStandard) %s type: %s' % (child.getName(), child.getType(),)) + # dbgprint(1, '(generateBuildStandard) %s type: %s' % (child.getName(), child.getType(),)) generateBuildStandard_1(outfile, prefix, child, child, keyword, delayed) hasChildren += 1 - keyword = 'elif' + keyword = "elif" # Does this element have a substitutionGroup? # If so generate a clause for each element in the substitutionGroup. childName = child.getName() if childName in SubstitutionGroups: - #dbgprint(1, '(BldStd) found: %s in %s' % (childName, SubstitutionGroups)) + # dbgprint(1, '(BldStd) found: %s in %s' % (childName, SubstitutionGroups)) for memberName in SubstitutionGroups[childName]: memberName = cleanupName(memberName) if memberName in ElementDict: member = ElementDict[memberName] - #dbgprint(1, '(BldStd) found subst: %s/%s' % (memberName, member)) - generateBuildStandard_1(outfile, prefix, member, child, - keyword, delayed) + # dbgprint(1, '(BldStd) found subst: %s/%s' % (memberName, member)) + generateBuildStandard_1(outfile, prefix, member, child, keyword, delayed) return hasChildren def generateBuildFn(outfile, prefix, element, delayed): base = element.getBase() - outfile.write(' def build(self, node_):\n') - outfile.write(' attrs = node_.attributes\n') - outfile.write(' self.buildAttributes(attrs)\n') -## if len(element.getChildren()) > 0: - outfile.write(' for child_ in node_.childNodes:\n') + outfile.write(" def build(self, node_):\n") + outfile.write(" attrs = node_.attributes\n") + outfile.write(" self.buildAttributes(attrs)\n") + ## if len(element.getChildren()) > 0: + outfile.write(" for child_ in node_.childNodes:\n") outfile.write(" nodeName_ = child_.nodeName.split(':')[-1]\n") outfile.write(" self.buildChildren(child_, nodeName_)\n") - outfile.write(' def buildAttributes(self, attrs):\n') + outfile.write(" def buildAttributes(self, attrs):\n") hasAttributes = generateBuildAttributes(outfile, element, 0) if base: hasAttributes += 1 - s1 = ' %s.buildAttributes(self, attrs)\n' % (base, ) + s1 = " %s.buildAttributes(self, attrs)\n" % (base,) outfile.write(s1) if hasAttributes == 0: - outfile.write(' pass\n') - outfile.write(' def buildChildren(self, child_, nodeName_):\n') - keyword = 'if' + outfile.write(" pass\n") + outfile.write(" def buildChildren(self, child_, nodeName_):\n") + keyword = "if" hasChildren = 0 if element.isMixed(): - hasChildren = generateBuildMixed(outfile, prefix, element, keyword, - delayed, hasChildren) - else: # not element.isMixed() - hasChildren = generateBuildStandard(outfile, prefix, element, keyword, - delayed, hasChildren) + hasChildren = generateBuildMixed(outfile, prefix, element, keyword, delayed, hasChildren) + else: # not element.isMixed() + hasChildren = generateBuildStandard(outfile, prefix, element, keyword, delayed, hasChildren) if hasChildren == 0: s1 = " self.valueOf_ = ''\n" outfile.write(s1) @@ -1696,7 +1858,7 @@ def generateBuildFn(outfile, prefix, element, delayed): if base and base in ElementDict: parent = ElementDict[base] if len(parent.getChildren()) > 0: - s1 = " %s.buildChildren(self, child_, nodeName_)\n" % (base, ) + s1 = " %s.buildChildren(self, child_, nodeName_)\n" % (base,) outfile.write(s1) @@ -1717,11 +1879,12 @@ def buildCtorArgs_multilevel(element): if count == 0: add(", valueOf_=''") if element.isMixed(): - add(', mixedclass_=None') - add(', content_=None') - s1 = ''.join(content) + add(", mixedclass_=None") + add(", content_=None") + s1 = "".join(content) return s1 + def buildCtorArgs_multilevel_aux(add, element): buildCtorArgs_aux(add, element) base = element.getBase() @@ -1737,7 +1900,7 @@ def buildCtorArgs_1_level(element): count = countElementChildren(element, 0) if count == 0: add(", valueOf_=''") - s1 = ''.join(content) + s1 = "".join(content) return s1 @@ -1746,66 +1909,63 @@ def buildCtorArgs_aux(add, element): for key in attrDefs: attrDef = attrDefs[key] name = attrDef.getName() - mappedName = name.replace(':', '_') + mappedName = name.replace(":", "_") mappedName = cleanupName(mapName(mappedName)) try: atype = attrDef.getData_type() except KeyError: atype = StringType - if atype in StringType or \ - atype == TokenType or \ - atype == DateTimeType or \ - atype == DateType: - add(', %s=\'\'' % mappedName) + if atype in StringType or atype == TokenType or atype == DateTimeType or atype == DateType: + add(", %s=''" % mappedName) elif atype in IntegerType: - add(', %s=-1' % mappedName) + add(", %s=-1" % mappedName) elif atype == PositiveIntegerType: - add(', %s=1' % mappedName) + add(", %s=1" % mappedName) elif atype == NonPositiveIntegerType: - add(', %s=0' % mappedName) + add(", %s=0" % mappedName) elif atype == NegativeIntegerType: - add(', %s=-1' % mappedName) + add(", %s=-1" % mappedName) elif atype == NonNegativeIntegerType: - add(', %s=0' % mappedName) + add(", %s=0" % mappedName) elif atype == BooleanType: - add(', %s=0' % mappedName) + add(", %s=0" % mappedName) elif atype == FloatType or atype == DoubleType or atype == DecimalType: - add(', %s=0.0' % mappedName) + add(", %s=0.0" % mappedName) else: - add(', %s=None' % mappedName) + add(", %s=None" % mappedName) nestedElements = 0 for child in element.getChildren(): nestedElements = 1 if child.getMaxOccurs() > 1: - add(', %s=None' % child.getCleanName()) + add(", %s=None" % child.getCleanName()) else: childType = child.getType() - if childType in StringType or \ - childType == TokenType or \ - childType == DateTimeType or \ - childType == DateType: - add(', %s=\'\'' % child.getCleanName()) + if ( + childType in StringType + or childType == TokenType + or childType == DateTimeType + or childType == DateType + ): + add(", %s=''" % child.getCleanName()) elif childType in IntegerType: - add(', %s=-1' % child.getCleanName()) + add(", %s=-1" % child.getCleanName()) elif childType == PositiveIntegerType: - add(', %s=1' % child.getCleanName()) + add(", %s=1" % child.getCleanName()) elif childType == NonPositiveIntegerType: - add(', %s=0' % child.getCleanName()) + add(", %s=0" % child.getCleanName()) elif childType == NegativeIntegerType: - add(', %s=-1' % child.getCleanName()) + add(", %s=-1" % child.getCleanName()) elif childType == NonNegativeIntegerType: - add(', %s=0' % child.getCleanName()) + add(", %s=0" % child.getCleanName()) elif childType == BooleanType: - add(', %s=0' % child.getCleanName()) - elif childType == FloatType or \ - childType == DoubleType or \ - childType == DecimalType: - add(', %s=0.0' % child.getCleanName()) + add(", %s=0" % child.getCleanName()) + elif childType == FloatType or childType == DoubleType or childType == DecimalType: + add(", %s=0.0" % child.getCleanName()) else: - add(', %s=None' % child.getCleanName()) + add(", %s=None" % child.getCleanName()) -MixedCtorInitializers = '''\ +MixedCtorInitializers = """\ if mixedclass_ is None: self.mixedclass_ = MixedContainer else: @@ -1814,25 +1974,28 @@ MixedCtorInitializers = '''\ self.content_ = [] else: self.content_ = content_ -''' +""" def generateCtor(outfile, element): s2 = buildCtorArgs_multilevel(element) - s1 = ' def __init__(self%s):\n' % s2 + s1 = " def __init__(self%s):\n" % s2 outfile.write(s1) base = element.getBase() if base and base in ElementDict: parent = ElementDict[base] s2 = buildCtorParams(parent) - s1 = ' %s.__init__(self%s)\n' % (base, s2, ) + s1 = " %s.__init__(self%s)\n" % ( + base, + s2, + ) outfile.write(s1) attrDefs = element.getAttributeDefs() for key in attrDefs: attrDef = attrDefs[key] mappedName = cleanupName(attrDef.getName()) mappedName = mapName(mappedName) - s1 = ' self.%s = %s\n' % (mappedName, mappedName) + s1 = " self.%s = %s\n" % (mappedName, mappedName) outfile.write(s1) member = 1 # Generate member initializers in ctor. @@ -1844,31 +2007,29 @@ def generateCtor(outfile, element): for child in element.getChildren(): name = cleanupName(child.getCleanName()) if child.getMaxOccurs() > 1: - s1 = ' if %s is None:\n' % (name, ) + s1 = " if %s is None:\n" % (name,) outfile.write(s1) - s1 = ' self.%s = []\n' % (name, ) + s1 = " self.%s = []\n" % (name,) outfile.write(s1) - s1 = ' else:\n' + s1 = " else:\n" outfile.write(s1) - s1 = ' self.%s = %s\n' % \ - (name, name) + s1 = " self.%s = %s\n" % (name, name) outfile.write(s1) else: - s1 = ' self.%s = %s\n' % \ - (name, name) + s1 = " self.%s = %s\n" % (name, name) outfile.write(s1) member = 1 nestedElements = 1 if not nestedElements: - s1 = ' self.valueOf_ = valueOf_\n' + s1 = " self.valueOf_ = valueOf_\n" outfile.write(s1) member = 1 if element.getAnyAttribute(): - s1 = ' self.anyAttributes_ = {}\n' + s1 = " self.anyAttributes_ = {}\n" outfile.write(s1) member = 1 if not member: - outfile.write(' pass\n') + outfile.write(" pass\n") # Generate get/set/add member functions. @@ -1879,59 +2040,67 @@ def generateGettersAndSetters(outfile, element): name = cleanupName(child.getCleanName()) unmappedName = cleanupName(child.getName()) capName = unmappedName.capitalize() - s1 = ' def get%s(self): return self.%s\n' % \ - (capName, name) + s1 = " def get%s(self): return self.%s\n" % (capName, name) outfile.write(s1) - s1 = ' def set%s(self, %s): self.%s = %s\n' % \ - (capName, name, name, name) + s1 = " def set%s(self, %s): self.%s = %s\n" % (capName, name, name, name) outfile.write(s1) if child.getMaxOccurs() > 1: - s1 = ' def add%s(self, value): self.%s.append(value)\n' % \ - (capName, name) + s1 = " def add%s(self, value): self.%s.append(value)\n" % (capName, name) outfile.write(s1) - s1 = ' def insert%s(self, index, value): self.%s[index] = value\n' % \ - (capName, name) + s1 = " def insert%s(self, index, value): self.%s[index] = value\n" % ( + capName, + name, + ) outfile.write(s1) if GenerateProperties: - s1 = ' %sProp = property(get%s, set%s)\n' % \ - (unmappedName, capName, capName) + s1 = " %sProp = property(get%s, set%s)\n" % ( + unmappedName, + capName, + capName, + ) outfile.write(s1) attrDefs = element.getAttributeDefs() for key in attrDefs: attrDef = attrDefs[key] - name = cleanupName(attrDef.getName().replace(':', '_')) + name = cleanupName(attrDef.getName().replace(":", "_")) mappedName = mapName(name) capName = mappedName.capitalize() - s1 = ' def get%s(self): return self.%s\n' % \ - (name.capitalize(), mappedName) + s1 = " def get%s(self): return self.%s\n" % (name.capitalize(), mappedName) outfile.write(s1) # # What? An attribute cannot occur multiple times on the same # element. No attribute is a list of values. Right? -## if element.getMaxOccurs() > 1: -## s1 = ' def add%s(self, %s): self.%s.append(%s)\n' % \ -## (capName, mappedName, mappedName, mappedName) -## outfile.write(s1) -## s1 = ' def set%s(self, %s, index): self.%s[index] = %s\n' % \ -## (name.capitalize(), mappedName, mappedName, mappedName) -## outfile.write(s1) -## else: - s1 = ' def set%s(self, %s): self.%s = %s\n' % \ - (name.capitalize(), mappedName, mappedName, mappedName) + ## if element.getMaxOccurs() > 1: + ## s1 = ' def add%s(self, %s): self.%s.append(%s)\n' % \ + ## (capName, mappedName, mappedName, mappedName) + ## outfile.write(s1) + ## s1 = ' def set%s(self, %s, index): self.%s[index] = %s\n' % \ + ## (name.capitalize(), mappedName, mappedName, mappedName) + ## outfile.write(s1) + ## else: + s1 = " def set%s(self, %s): self.%s = %s\n" % ( + name.capitalize(), + mappedName, + mappedName, + mappedName, + ) outfile.write(s1) if GenerateProperties: - s1 = ' %sProp = property(get%s, set%s)\n' % \ - (mappedName, capName, capName) + s1 = " %sProp = property(get%s, set%s)\n" % ( + mappedName, + capName, + capName, + ) outfile.write(s1) if not nestedElements: - s1 = ' def getValueOf_(self): return self.valueOf_\n' + s1 = " def getValueOf_(self): return self.valueOf_\n" outfile.write(s1) - s1 = ' def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_\n' + s1 = " def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_\n" outfile.write(s1) if element.getAnyAttribute(): - s1 = ' def getAnyAttributes_(self): return self.anyAttributes_\n' + s1 = " def getAnyAttributes_(self): return self.anyAttributes_\n" outfile.write(s1) - s1 = ' def setAnyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_\n' + s1 = " def setAnyAttributes_(self, anyAttributes_): self.anyAttributes_ = anyAttributes_\n" outfile.write(s1) @@ -1952,36 +2121,38 @@ def generateClasses(outfile, prefix, element, delayed): return AlreadyGenerated.append(element.getName()) if element.getMixedExtensionError(): - print ('*** Element %s extension chain contains mixed and non-mixed content. Not generated.' % \ - (element.getName(),)) + print( + "*** Element %s extension chain contains mixed and non-mixed content. Not generated." + % (element.getName(),) + ) return ElementsForSubclasses.append(element) name = element.getCleanName() if GenerateProperties: if base: - s1 = 'class %s%s(object, %s):\n' % (prefix, name, base) + s1 = "class %s%s(object, %s):\n" % (prefix, name, base) else: - s1 = 'class %s%s(object):\n' % (prefix, name) + s1 = "class %s%s(object):\n" % (prefix, name) else: if base: - s1 = 'class %s%s(%s):\n' % (prefix, name, base) + s1 = "class %s%s(%s):\n" % (prefix, name, base) else: - s1 = 'class %s%s:\n' % (prefix, name) + s1 = "class %s%s:\n" % (prefix, name) wrt(s1) - wrt(' subclass = None\n') + wrt(" subclass = None\n") generateCtor(outfile, element) - wrt(' def factory(*args_, **kwargs_):\n') - wrt(' if %s%s.subclass:\n' % (prefix, name)) - wrt(' return %s%s.subclass(*args_, **kwargs_)\n' % (prefix, name)) - wrt(' else:\n') - wrt(' return %s%s(*args_, **kwargs_)\n' % (prefix, name)) - wrt(' factory = staticmethod(factory)\n') + wrt(" def factory(*args_, **kwargs_):\n") + wrt(" if %s%s.subclass:\n" % (prefix, name)) + wrt(" return %s%s.subclass(*args_, **kwargs_)\n" % (prefix, name)) + wrt(" else:\n") + wrt(" return %s%s(*args_, **kwargs_)\n" % (prefix, name)) + wrt(" factory = staticmethod(factory)\n") generateGettersAndSetters(outfile, element) generateExportFn(outfile, prefix, element) generateExportLiteralFn(outfile, prefix, element) generateBuildFn(outfile, prefix, element, delayed) - wrt('# end class %s\n' % name) - wrt('\n\n') + wrt("# end class %s\n" % name) + wrt("\n\n") # @@ -2050,10 +2221,12 @@ SAX_ATTR_STRING = """\ obj.set%s(val) """ + def getClassName(element): name = element.getCleanName() return name + def generateSaxAttributes(wrt, element): attrDefs = element.getAttributeDefs() for key in attrDefs: @@ -2063,58 +2236,59 @@ def generateSaxAttributes(wrt, element): if atype in IntegerType: s1 = SAX_ATTR_INTEGER % (name, name.capitalize(), name) wrt(s1) -## s1 = " if attrs.get('%s'):\n" % name -## wrt(s1) -## s1 = ' try:\n' -## wrt(s1) -## s1 = " self.%s = int(attrs.get('%s').value)\n" % \ -## (name, name) -## wrt(s1) -## s1 = ' except ValueError:\n' -## wrt(s1) -## s1 = " raise ValueError('Bad integer')\n" -## wrt(s1) + ## s1 = " if attrs.get('%s'):\n" % name + ## wrt(s1) + ## s1 = ' try:\n' + ## wrt(s1) + ## s1 = " self.%s = int(attrs.get('%s').value)\n" % \ + ## (name, name) + ## wrt(s1) + ## s1 = ' except ValueError:\n' + ## wrt(s1) + ## s1 = " raise ValueError('Bad integer')\n" + ## wrt(s1) elif atype == BooleanType: - s1 = SAX_ATTR_BOOLEAN % (name, name.capitalize(), \ - name.capitalize(), name) + s1 = SAX_ATTR_BOOLEAN % (name, name.capitalize(), name.capitalize(), name) wrt(s1) -## wrt(s1) -## s1 = " if attrs.get('%s'):\n" % name -## wrt(s1) -## s1 = " if attrs.get('%s').value in ('true', '1'):\n" % \ -## name -## wrt(s1) -## s1 = " self.%s = 1\n" % \ -## name -## wrt(s1) -## s1 = " elif attrs.get('%s').value in ('false', '0'):\n" % \ -## name -## wrt(s1) -## s1 = " self.%s = 0\n" % \ -## name -## wrt(s1) -## s1 = ' else:\n' -## wrt(s1) -## s1 = " raise ValueError('Bad boolean')\n" -## wrt(s1) + ## wrt(s1) + ## s1 = " if attrs.get('%s'):\n" % name + ## wrt(s1) + ## s1 = " if attrs.get('%s').value in ('true', '1'):\n" % \ + ## name + ## wrt(s1) + ## s1 = " self.%s = 1\n" % \ + ## name + ## wrt(s1) + ## s1 = " elif attrs.get('%s').value in ('false', '0'):\n" % \ + ## name + ## wrt(s1) + ## s1 = " self.%s = 0\n" % \ + ## name + ## wrt(s1) + ## s1 = ' else:\n' + ## wrt(s1) + ## s1 = " raise ValueError('Bad boolean')\n" + ## wrt(s1) elif atype == FloatType or atype == DoubleType or atype == DecimalType: s1 = SAX_ATTR_FLOAT % (name, name.capitalize(), name) wrt(s1) -## s1 = " if attrs.get('%s'):\n" % name -## wrt(s1) -## s1 = ' try:\n' -## wrt(s1) -## s1 = " self.%s = float(attrs.get('%s').value)\n" % \ -## (name, name) -## wrt(s1) -## s1 = ' except:\n' -## wrt(s1) -## s1 = " raise ValueError('Bad float/double')\n" -## wrt(s1) + ## s1 = " if attrs.get('%s'):\n" % name + ## wrt(s1) + ## s1 = ' try:\n' + ## wrt(s1) + ## s1 = " self.%s = float(attrs.get('%s').value)\n" % \ + ## (name, name) + ## wrt(s1) + ## s1 = ' except:\n' + ## wrt(s1) + ## s1 = " raise ValueError('Bad float/double')\n" + ## wrt(s1) else: # Assume attr['type'] in StringType or attr['type'] == DateTimeType: s1 = SAX_ATTR_STRING % (name, name.capitalize()) wrt(s1) + + ## s1 = " if attrs.get('%s'):\n" % name ## wrt(s1) ## s1 = " self.%s = attrs.get('%s').value\n" % (name, name) @@ -2138,6 +2312,7 @@ def generateSAXStartElement_1(wrt, element): s1 = SAX_STARTELEMENT_3 % className wrt(s1) + def generateSAXStartElement(outfile, root, elementList): wrt = outfile.write name = root.getChildren()[0].getName() @@ -2147,7 +2322,7 @@ def generateSAXStartElement(outfile, root, elementList): generateSAXStartElement_1(wrt, element) s1 = SAX_STARTELEMENT_4 wrt(s1) - wrt('\n') + wrt("\n") SAX_ENDELEMENT_1 = """\ @@ -2207,9 +2382,12 @@ SAX_ENDELEMENT_4 = """\ self.reportError('"%s" element not allowed here.' % name) """ + def generateParentCheck(parent): s1 = "self.stack[-2].name == '%s'" % getClassName(parent) return s1 + + ## strList = [] ## for parent in parentList: ## strList.append("self.stack[-2].name == '%s'" % \ @@ -2219,6 +2397,7 @@ def generateParentCheck(parent): ## s1 = '(%s)' % s1 ## return s1 + def generateSAXEndElement(outfile, root, elementList): wrt = outfile.write s1 = " def endElement(self, name):\n" @@ -2226,17 +2405,17 @@ def generateSAXEndElement(outfile, root, elementList): s1 = " done = 0\n" wrt(s1) name = root.getChildren()[0].getName() - s1 = SAX_ENDELEMENT_1 % (name, ) + s1 = SAX_ENDELEMENT_1 % (name,) wrt(s1) for element, parent in elementList: - #s2 = generateParentCheck(parent) + # s2 = generateParentCheck(parent) name = element.getName() capName = element.getUnmappedCleanName().capitalize() if element.isComplex(): if element.getMaxOccurs() > 1: - s1 = SAX_ENDELEMENT_2 % (name, 'add', capName) + s1 = SAX_ENDELEMENT_2 % (name, "add", capName) else: - s1 = SAX_ENDELEMENT_2 % (name, 'set', capName) + s1 = SAX_ENDELEMENT_2 % (name, "set", capName) else: etype = element.getType() if etype in IntegerType: @@ -2246,15 +2425,15 @@ def generateSAXEndElement(outfile, root, elementList): elif etype == BooleanType: s3 = SAX_ENDELEMENT_BOOLEAN else: - s3 = '' + s3 = "" if element.getMaxOccurs() > 1: - s1 = SAX_ENDELEMENT_3 % (name, s3, 'add', capName) + s1 = SAX_ENDELEMENT_3 % (name, s3, "add", capName) else: - s1 = SAX_ENDELEMENT_3 % (name, s3, 'set', capName) + s1 = SAX_ENDELEMENT_3 % (name, s3, "set", capName) wrt(s1) s1 = SAX_ENDELEMENT_4 wrt(s1) - wrt('\n') + wrt("\n") SAX_HEADER = """\ @@ -2339,16 +2518,16 @@ def generateSAXHndlr(outfile, root): if element == root: continue elementList.append((element, parent)) -## print '(gsh) element: %s/%s/%d parent: %s/%s/%d' % \ -## (element.getUnmappedCleanName(), element.getType(), id(element), -## #(element.getName(), element.getType(), id(element), -## parent.getName(), parent.getType(), id(parent)) -## if parent.getName() == 'booster': -## ipshell('at booster -- Entering ipshell.\\nHit Ctrl-D to exit') -## if element in elementDict: -## elementDict[element].append(parent) -## else: -## elementDict[element] = [parent] + ## print '(gsh) element: %s/%s/%d parent: %s/%s/%d' % \ + ## (element.getUnmappedCleanName(), element.getType(), id(element), + ## #(element.getName(), element.getType(), id(element), + ## parent.getName(), parent.getType(), id(parent)) + ## if parent.getName() == 'booster': + ## ipshell('at booster -- Entering ipshell.\\nHit Ctrl-D to exit') + ## if element in elementDict: + ## elementDict[element].append(parent) + ## else: + ## elementDict[element] = [parent] elementList1 = [] alreadySeen = [] for element, parent in elementList: @@ -2358,12 +2537,12 @@ def generateSAXHndlr(outfile, root): continue alreadySeen.append(element.getName()) elementList1.append((element, parent)) -## print '+' * 20 -## for element, parent in elementList1: -## print '(gsh) element: %s/%s/%d parent: %s/%s/%d' % \ -## (element.getUnmappedCleanName(), element.getType(), id(element), -## #(element.getName(), element.getType(), id(element), -## parent.getName(), parent.getType(), id(parent)) + ## print '+' * 20 + ## for element, parent in elementList1: + ## print '(gsh) element: %s/%s/%d parent: %s/%s/%d' % \ + ## (element.getUnmappedCleanName(), element.getType(), id(element), + ## #(element.getName(), element.getType(), id(element), + ## parent.getName(), parent.getType(), id(parent)) generateSAXStartElement(outfile, root, elementList1) generateSAXEndElement(outfile, root, elementList1) s1 = SAX_FOOTER @@ -2371,7 +2550,7 @@ def generateSAXHndlr(outfile, root): def collect(element, elements): - if element.getName() != 'root': + if element.getName() != "root": elements.append(element) for child in element.getChildren(): collect(child, elements) @@ -2512,6 +2691,7 @@ class MixedContainer: # Fool (and straighten out) the syntax highlighting. # DUMMY = ''' + def generateHeader(outfile, prefix): s1 = TEMPLATE_HEADER % time.ctime() outfile.write(s1) @@ -2664,12 +2844,12 @@ def generateMain(outfile, prefix, root): else: rootElement = elType params = { - 'prefix': prefix, - 'cap_name': cleanupName(name.capitalize()), - 'name': cleanupName(name), - 'module_name': os.path.splitext(os.path.basename(outfile.name))[0], - 'root': rootElement, - } + "prefix": prefix, + "cap_name": cleanupName(name.capitalize()), + "name": cleanupName(name), + "module_name": os.path.splitext(os.path.basename(outfile.name))[0], + "root": rootElement, + } s1 = TEMPLATE_MAIN % params outfile.write(s1) @@ -2678,11 +2858,11 @@ def buildCtorParams(element): content = [] add = content.append if element.isMixed(): - add(', mixedclass_') - add(', content_') + add(", mixedclass_") + add(", content_") else: buildCtorParams_aux(add, element) - s1 = ''.join(content) + s1 = "".join(content) return s1 @@ -2692,9 +2872,9 @@ def buildCtorParams_aux(add, element): attrDef = attrDefs[key] name = attrDef.getName() cleanName = cleanupName(mapName(name)) - add(', %s' % cleanName) + add(", %s" % cleanName) for child in element.getChildren(): - add(', %s' % child.getCleanName()) + add(", %s" % child.getCleanName()) base = element.getBase() if base and base in ElementDict: parent = ElementDict[base] @@ -2705,10 +2885,10 @@ def get_class_behavior_args(classBehavior): argList = [] args = classBehavior.getArgs() args = args.getArg() - #print '(get_class_behavior_args) args:', args + # print '(get_class_behavior_args) args:', args for arg in args: argList.append(arg.getName()) - argString = ', '.join(argList) + argString = ", ".join(argList) return argString @@ -2720,18 +2900,19 @@ def get_class_behavior_args(classBehavior): # looks in the local file system is commented out below. # def get_impl_body(classBehavior, baseImplUrl, implUrl): - impl = ' pass\n' + impl = " pass\n" if implUrl: if baseImplUrl: - implUrl = '%s%s' % (baseImplUrl, implUrl) + implUrl = "%s%s" % (baseImplUrl, implUrl) try: implFile = urlopen(implUrl) impl = implFile.read() implFile.close() except HTTPError: - print ('*** Implementation at %s not found.' % implUrl) + print("*** Implementation at %s not found." % implUrl) return impl + ### ### This alternative implementation of get_impl_body() tries the URL ### via http first, then, if that fails, looks in a directory on @@ -2767,13 +2948,13 @@ def generateClassBehaviors(wrt, classBehaviors, baseImplUrl): # Generate the core behavior. argString = get_class_behavior_args(classBehavior) if argString: - wrt(' def %s(self, %s, *args):\n' % (behaviorName, argString)) + wrt(" def %s(self, %s, *args):\n" % (behaviorName, argString)) else: - wrt(' def %s(self, *args):\n' % (behaviorName, )) + wrt(" def %s(self, *args):\n" % (behaviorName,)) implUrl = classBehavior.getImpl_url() impl = get_impl_body(classBehavior, baseImplUrl, implUrl) wrt(impl) - wrt('\n') + wrt("\n") # # Generate the ancillaries for this behavior. ancillaries = classBehavior.getAncillaries() @@ -2783,43 +2964,43 @@ def generateClassBehaviors(wrt, classBehaviors, baseImplUrl): for ancillary in ancillaries: argString = get_class_behavior_args(ancillary) if argString: - wrt(' def %s(self, %s, *args):\n' % (ancillary.getName(), argString)) + wrt(" def %s(self, %s, *args):\n" % (ancillary.getName(), argString)) else: - wrt(' def %s(self, *args):\n' % (ancillary.getName(), )) + wrt(" def %s(self, *args):\n" % (ancillary.getName(),)) implUrl = ancillary.getImpl_url() impl = get_impl_body(classBehavior, baseImplUrl, implUrl) wrt(impl) - wrt('\n') + wrt("\n") # # Generate the wrapper method that calls the ancillaries and # the core behavior. argString = get_class_behavior_args(classBehavior) if argString: - wrt(' def %s_wrapper(self, %s, *args):\n' % (behaviorName, argString)) + wrt(" def %s_wrapper(self, %s, *args):\n" % (behaviorName, argString)) else: - wrt(' def %s_wrapper(self, *args):\n' % (behaviorName, )) + wrt(" def %s_wrapper(self, *args):\n" % (behaviorName,)) if ancillaries: for ancillary in ancillaries: role = ancillary.getRole() - if role == 'DBC-precondition': - wrt(' if not self.%s(*args)\n' % (ancillary.getName(), )) - wrt(' return False\n') + if role == "DBC-precondition": + wrt(" if not self.%s(*args)\n" % (ancillary.getName(),)) + wrt(" return False\n") if argString: - wrt(' result = self.%s(%s, *args)\n' % (behaviorName, argString)) + wrt(" result = self.%s(%s, *args)\n" % (behaviorName, argString)) else: - wrt(' result = self.%s(*args)\n' % (behaviorName, )) + wrt(" result = self.%s(*args)\n" % (behaviorName,)) if ancillaries: for ancillary in ancillaries: role = ancillary.getRole() - if role == 'DBC-postcondition': - wrt(' if not self.%s(*args)\n' % (ancillary.getName(), )) - wrt(' return False\n') - wrt(' return result\n') - wrt('\n') + if role == "DBC-postcondition": + wrt(" if not self.%s(*args)\n" % (ancillary.getName(),)) + wrt(" return False\n") + wrt(" return result\n") + wrt("\n") -def generateSubclass(outfile, element, prefix, xmlbehavior, behaviors, baseUrl): - wrt= outfile.write +def generateSubclass(outfile, element, prefix, xmlbehavior, behaviors, baseUrl): + wrt = outfile.write if not element.isComplex(): return if (not element.getChildren()) and (not element.getAttributeDefs()): @@ -2828,16 +3009,16 @@ def generateSubclass(outfile, element, prefix, xmlbehavior, behaviors, baseUrl) return AlreadyGenerated_subclass.append(element.getName()) name = element.getCleanName() - wrt('class %s%s%s(supermod.%s):\n' % (prefix, name, SubclassSuffix, name)) + wrt("class %s%s%s(supermod.%s):\n" % (prefix, name, SubclassSuffix, name)) s1 = buildCtorArgs_multilevel(element) - wrt(' def __init__(self%s):\n' % s1) + wrt(" def __init__(self%s):\n" % s1) s1 = buildCtorParams(element) - wrt(' supermod.%s%s.__init__(self%s)\n' % (prefix, name, s1)) + wrt(" supermod.%s%s.__init__(self%s)\n" % (prefix, name, s1)) if xmlbehavior and behaviors: - wrt('\n') - wrt(' #\n') - wrt(' # XMLBehaviors\n') - wrt(' #\n') + wrt("\n") + wrt(" #\n") + wrt(" # XMLBehaviors\n") + wrt(" #\n") # Get a list of behaviors for this class/subclass. classDictionary = behaviors.get_class_dictionary() if name in classDictionary: @@ -2846,9 +3027,9 @@ def generateSubclass(outfile, element, prefix, xmlbehavior, behaviors, baseUrl) classBehaviors = None if classBehaviors: generateClassBehaviors(wrt, classBehaviors, baseUrl) - wrt('supermod.%s.subclass = %s%s\n' % (name, name, SubclassSuffix)) - wrt('# end class %s%s%s\n' % (prefix, name, SubclassSuffix)) - wrt('\n\n') + wrt("supermod.%s.subclass = %s%s\n" % (name, name, SubclassSuffix)) + wrt("# end class %s%s%s\n" % (prefix, name, SubclassSuffix)) + wrt("\n\n") TEMPLATE_SUBCLASS_HEADER = """\ @@ -3008,8 +3189,7 @@ if __name__ == '__main__': ## return False -def generateSubclasses(root, subclassFilename, behaviorFilename, - prefix, superModule='xxx'): +def generateSubclasses(root, subclassFilename, behaviorFilename, prefix, superModule="xxx"): name = root.getChildren()[0].getName() subclassFile = makeFile(subclassFilename) if subclassFile: @@ -3021,12 +3201,12 @@ def generateSubclasses(root, subclassFilename, behaviorFilename, try: # Add the correct working directory to the path so that # we use the user/developers local copy. - sys.path.insert(0, '.') + sys.path.insert(0, ".") import xmlbehavior_sub as xmlbehavior except ImportError: - print ('*** You have requested generation of extended methods.') - print ('*** But, no xmlbehavior module is available.') - print ('*** Generation of extended behavior methods is omitted.') + print("*** You have requested generation of extended methods.") + print("*** But, no xmlbehavior module is available.") + print("*** Generation of extended behavior methods is omitted.") if xmlbehavior: behaviors = xmlbehavior.parse(behaviorFilename) behaviors.make_class_dictionary(cleanupName) @@ -3035,20 +3215,20 @@ def generateSubclasses(root, subclassFilename, behaviorFilename, wrt(TEMPLATE_SUBCLASS_HEADER % (time.ctime(), superModule)) for element in ElementsForSubclasses: generateSubclass(subclassFile, element, prefix, xmlbehavior, behaviors, baseUrl) -## processed = [] -## for element in root.getChildren(): -## name = element.getCleanName() -## if name not in processed: -## processed.append(name) -## generateSubclass(subclassFile, element, prefix, xmlbehavior, behaviors, baseUrl) -## while 1: -## if len(DelayedElements_subclass) <= 0: -## break -## element = DelayedElements_subclass.pop() -## name = element.getCleanName() -## if name not in processed: -## processed.append(name) -## generateSubclass(subclassFile, element, prefix, xmlbehavior, behaviors, baseUrl) + ## processed = [] + ## for element in root.getChildren(): + ## name = element.getCleanName() + ## if name not in processed: + ## processed.append(name) + ## generateSubclass(subclassFile, element, prefix, xmlbehavior, behaviors, baseUrl) + ## while 1: + ## if len(DelayedElements_subclass) <= 0: + ## break + ## element = DelayedElements_subclass.pop() + ## name = element.getCleanName() + ## if name not in processed: + ## processed.append(name) + ## generateSubclass(subclassFile, element, prefix, xmlbehavior, behaviors, baseUrl) name = root.getChildren()[0].getName() elType = cleanupName(root.getChildren()[0].getType()) if RootElement: @@ -3056,12 +3236,12 @@ def generateSubclasses(root, subclassFilename, behaviorFilename, else: rootElement = elType params = { - 'cap_name': cleanupName(name).capitalize(), - 'name': cleanupName(name), - 'module_name': os.path.splitext(os.path.basename(subclassFilename))[0], - 'root': rootElement, - 'super': superModule, - } + "cap_name": cleanupName(name).capitalize(), + "name": cleanupName(name), + "module_name": os.path.splitext(os.path.basename(subclassFilename))[0], + "root": rootElement, + "super": superModule, + } wrt(TEMPLATE_SUBCLASS_FOOTER % params) subclassFile.close() @@ -3069,7 +3249,7 @@ def generateSubclasses(root, subclassFilename, behaviorFilename, def generateFromTree(outfile, prefix, elements, processed): for element in elements: name = element.getCleanName() - if 1: # if name not in processed: + if 1: # if name not in processed: processed.append(name) generateClasses(outfile, prefix, element, 0) children = element.getChildren() @@ -3077,8 +3257,7 @@ def generateFromTree(outfile, prefix, elements, processed): generateFromTree(outfile, prefix, element.getChildren(), processed) -def generate(outfileName, subclassFilename, behaviorFilename, - prefix, root, superModule): +def generate(outfileName, subclassFilename, behaviorFilename, prefix, root, superModule): global DelayedElements, DelayedElements_subclass # Create an output file. # Note that even if the user does not request an output file, @@ -3130,19 +3309,18 @@ def generate(outfileName, subclassFilename, behaviorFilename, generateMain(outfile, prefix, root) outfile.close() if subclassFilename: - generateSubclasses(root, subclassFilename, behaviorFilename, - prefix, superModule) + generateSubclasses(root, subclassFilename, behaviorFilename, prefix, superModule) def makeFile(outFileName): global Force outFile = None if (not Force) and os.path.exists(outFileName): - reply = input('File %s exists. Overwrite? (y/n): ' % outFileName) - if reply == 'y': - outFile = open(outFileName, 'w') + reply = input("File %s exists. Overwrite? (y/n): " % outFileName) + if reply == "y": + outFile = open(outFileName, "w") else: - outFile = open(outFileName, 'w') + outFile = open(outFileName, "w") return outFile @@ -3154,50 +3332,55 @@ def mapName(oldName): newName = NameTable[oldName] return newName + def cleanupName(oldName): - newName = oldName.replace(':', '_') - newName = newName.replace('-', '_') + newName = oldName.replace(":", "_") + newName = newName.replace("-", "_") return newName + ## def mapName(oldName): ## return '_X_%s' % oldName def strip_namespace(val): - return val.split(':')[-1] + return val.split(":")[-1] -def parseAndGenerate(outfileName, subclassFilename, prefix, \ - xschemaFileName, behaviorFilename, superModule='???'): - global DelayedElements, DelayedElements_subclass, AlreadyGenerated, SaxDelayedElements, \ - AlreadyGenerated_subclass +def parseAndGenerate( + outfileName, + subclassFilename, + prefix, + xschemaFileName, + behaviorFilename, + superModule="???", +): + global DelayedElements, DelayedElements_subclass, AlreadyGenerated, SaxDelayedElements, AlreadyGenerated_subclass DelayedElements = [] DelayedElements_subclass = [] AlreadyGenerated = [] AlreadyGenerated_subclass = [] -## parser = saxexts.make_parser("xml.sax.drivers2.drv_pyexpat") + ## parser = saxexts.make_parser("xml.sax.drivers2.drv_pyexpat") parser = make_parser() -## print 'dir(parser):', dir(parser) -## print "Parser: %s" % parser + ## print 'dir(parser):', dir(parser) + ## print "Parser: %s" % parser dh = XschemaHandler() -## parser.setDocumentHandler(dh) + ## parser.setDocumentHandler(dh) parser.setContentHandler(dh) parser.parse(xschemaFileName) root = dh.getRoot() root.annotate() -## print 'ElementDict:', ElementDict -## for name, obj in ElementDict.items(): -## print ' ', name, obj.getName(), obj.type -## print '=' * 50 -## root.show(sys.stdout, 0) -## print '=' * 50 -## response = input('Press Enter') -## root.show(sys.stdout, 0) -## print '=' * 50 -## print ']]] root: ', root, '[[[' - generate(outfileName, subclassFilename, behaviorFilename, - prefix, root, superModule) - + ## print 'ElementDict:', ElementDict + ## for name, obj in ElementDict.items(): + ## print ' ', name, obj.getName(), obj.type + ## print '=' * 50 + ## root.show(sys.stdout, 0) + ## print '=' * 50 + ## response = input('Press Enter') + ## root.show(sys.stdout, 0) + ## print '=' * 50 + ## print ']]] root: ', root, '[[[' + generate(outfileName, subclassFilename, behaviorFilename, prefix, root, superModule) USAGE_TEXT = """ @@ -3220,47 +3403,55 @@ Example: python generateDS.py -o generateModel_Module.py generateMetaModel_Module.xsd """ + def usage(): - print (USAGE_TEXT) + print(USAGE_TEXT) sys.exit(-1) def main(): global Force, GenerateProperties, SubclassSuffix, RootElement args = sys.argv[1:] - options, args = getopt.getopt(args, 'fyo:s:p:a:b:m', - ['subclass-suffix=', 'root-element=', 'super=', ]) - prefix = '' + options, args = getopt.getopt( + args, + "fyo:s:p:a:b:m", + [ + "subclass-suffix=", + "root-element=", + "super=", + ], + ) + prefix = "" outFilename = None subclassFilename = None behaviorFilename = None - nameSpace = 'xs:' + nameSpace = "xs:" debug = 0 - superModule = '???' + superModule = "???" for option in options: - if option[0] == '-p': + if option[0] == "-p": prefix = option[1] - elif option[0] == '-o': + elif option[0] == "-o": outFilename = option[1] - elif option[0] == '-s': + elif option[0] == "-s": subclassFilename = option[1] - elif option[0] == '-f': + elif option[0] == "-f": Force = 1 - elif option[0] == '-a': + elif option[0] == "-a": nameSpace = option[1] - elif option[0] == '-b': + elif option[0] == "-b": behaviorFilename = option[1] - elif option[0] == '-m': + elif option[0] == "-m": GenerateProperties = 1 - elif option[0] == '--subclass-suffix': + elif option[0] == "--subclass-suffix": SubclassSuffix = option[1] - elif option[0] == '--root-element': + elif option[0] == "--root-element": RootElement = option[1] - elif option[0] == '--super': + elif option[0] == "--super": superModule = option[1] set_type_constants(nameSpace) if behaviorFilename and not subclassFilename: - print ('\n*** Error. -b requires -s') + print("\n*** Error. -b requires -s") usage() if len(args) != 1: usage() @@ -3268,13 +3459,17 @@ def main(): if debug: pass else: - parseAndGenerate(outFilename, subclassFilename, prefix, \ - xschemaFileName, behaviorFilename, superModule=superModule) + parseAndGenerate( + outFilename, + subclassFilename, + prefix, + xschemaFileName, + behaviorFilename, + superModule=superModule, + ) -if __name__ == '__main__': +if __name__ == "__main__": main() ## import pdb ## pdb.run('main()') - - diff --git a/src/Tools/generateBase/generateModel_Module.py b/src/Tools/generateBase/generateModel_Module.py index 217916845c..be37255883 100644 --- a/src/Tools/generateBase/generateModel_Module.py +++ b/src/Tools/generateBase/generateModel_Module.py @@ -32,28 +32,31 @@ from xml.dom import Node # Support/utility functions. # + def showIndent(outfile, level): for idx in range(level): - outfile.write(' ') + outfile.write(" ") + def quote_xml(inStr): s1 = inStr - s1 = s1.replace('&', '&') - s1 = s1.replace('<', '<') - s1 = s1.replace('"', '"') + s1 = s1.replace("&", "&") + s1 = s1.replace("<", "<") + s1 = s1.replace('"', """) return s1 + def quote_python(inStr): s1 = inStr if s1.find("'") == -1: - if s1.find('\n') == -1: + if s1.find("\n") == -1: return "'%s'" % s1 else: return "'''%s'''" % s1 else: if s1.find('"') != -1: s1 = s1.replace('"', '\\"') - if s1.find('\n') == -1: + if s1.find("\n") == -1: return '"%s"' % s1 else: return '"""%s"""' % s1 @@ -74,61 +77,85 @@ class MixedContainer: TypeDecimal = 5 TypeDouble = 6 TypeBoolean = 7 + def __init__(self, category, content_type, name, value): self.category = category self.content_type = content_type self.name = name self.value = value + def getCategory(self): return self.category + def getContenttype(self, content_type): return self.content_type + def getValue(self): return self.value + def getName(self): return self.name + def export(self, outfile, level, name): if self.category == MixedContainer.CategoryText: outfile.write(self.value) elif self.category == MixedContainer.CategorySimple: self.exportSimple(outfile, level, name) - else: # category == MixedContainer.CategoryComplex + else: # category == MixedContainer.CategoryComplex self.value.export(outfile, level, name) + def exportSimple(self, outfile, level, name): if self.content_type == MixedContainer.TypeString: - outfile.write('<%s>%s' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeInteger or \ - self.content_type == MixedContainer.TypeBoolean: - outfile.write('<%s>%d' % (self.name, self.value, self.name)) - elif self.content_type == MixedContainer.TypeFloat or \ - self.content_type == MixedContainer.TypeDecimal: - outfile.write('<%s>%f' % (self.name, self.value, self.name)) + outfile.write("<%s>%s" % (self.name, self.value, self.name)) + elif ( + self.content_type == MixedContainer.TypeInteger + or self.content_type == MixedContainer.TypeBoolean + ): + outfile.write("<%s>%d" % (self.name, self.value, self.name)) + elif ( + self.content_type == MixedContainer.TypeFloat + or self.content_type == MixedContainer.TypeDecimal + ): + outfile.write("<%s>%f" % (self.name, self.value, self.name)) elif self.content_type == MixedContainer.TypeDouble: - outfile.write('<%s>%g' % (self.name, self.value, self.name)) + outfile.write("<%s>%g" % (self.name, self.value, self.name)) + def exportLiteral(self, outfile, level, name): if self.category == MixedContainer.CategoryText: showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) + outfile.write( + 'MixedContainer(%d, %d, "%s", "%s"),\n' + % (self.category, self.content_type, self.name, self.value) + ) elif self.category == MixedContainer.CategorySimple: showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s", "%s"),\n' % \ - (self.category, self.content_type, self.name, self.value)) - else: # category == MixedContainer.CategoryComplex + outfile.write( + 'MixedContainer(%d, %d, "%s", "%s"),\n' + % (self.category, self.content_type, self.name, self.value) + ) + else: # category == MixedContainer.CategoryComplex showIndent(outfile, level) - outfile.write('MixedContainer(%d, %d, "%s",\n' % \ - (self.category, self.content_type, self.name,)) + outfile.write( + 'MixedContainer(%d, %d, "%s",\n' + % ( + self.category, + self.content_type, + self.name, + ) + ) self.value.exportLiteral(outfile, level + 1) showIndent(outfile, level) - outfile.write(')\n') + outfile.write(")\n") # # Data representation classes. # + class GenerateModel: subclass = None + def __init__(self, Module=None, PythonExport=None): if Module is None: self.Module = [] @@ -138,89 +165,144 @@ class GenerateModel: self.PythonExport = [] else: self.PythonExport = PythonExport + def factory(*args_, **kwargs_): if GenerateModel.subclass: return GenerateModel.subclass(*args_, **kwargs_) else: return GenerateModel(*args_, **kwargs_) + factory = staticmethod(factory) - def getModule(self): return self.Module - def setModule(self, Module): self.Module = Module - def addModule(self, value): self.Module.append(value) - def insertModule(self, index, value): self.Module[index] = value - def getPythonexport(self): return self.PythonExport - def setPythonexport(self, PythonExport): self.PythonExport = PythonExport - def addPythonexport(self, value): self.PythonExport.append(value) - def insertPythonexport(self, index, value): self.PythonExport[index] = value - def export(self, outfile, level, name_='GenerateModel'): + + def getModule(self): + return self.Module + + def setModule(self, Module): + self.Module = Module + + def addModule(self, value): + self.Module.append(value) + + def insertModule(self, index, value): + self.Module[index] = value + + def getPythonexport(self): + return self.PythonExport + + def setPythonexport(self, PythonExport): + self.PythonExport = PythonExport + + def addPythonexport(self, value): + self.PythonExport.append(value) + + def insertPythonexport(self, index, value): + self.PythonExport[index] = value + + def export(self, outfile, level, name_="GenerateModel"): showIndent(outfile, level) - outfile.write('<%s>\n' % name_) + outfile.write("<%s>\n" % name_) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='GenerateModel'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="GenerateModel"): pass - def exportChildren(self, outfile, level, name_='GenerateModel'): + + def exportChildren(self, outfile, level, name_="GenerateModel"): for Module_ in self.getModule(): Module_.export(outfile, level) for PythonExport_ in self.getPythonexport(): PythonExport_.export(outfile, level) - def exportLiteral(self, outfile, level, name_='GenerateModel'): + + def exportLiteral(self, outfile, level, name_="GenerateModel"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('Module=[\n') + outfile.write("Module=[\n") level += 1 for Module in self.Module: showIndent(outfile, level) - outfile.write('Module(\n') + outfile.write("Module(\n") Module.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") showIndent(outfile, level) - outfile.write('PythonExport=[\n') + outfile.write("PythonExport=[\n") level += 1 for PythonExport in self.PythonExport: showIndent(outfile, level) - outfile.write('PythonExport(\n') + outfile.write("PythonExport(\n") PythonExport.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Module': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Module": obj_ = Module.factory() obj_.build(child_) self.Module.append(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'PythonExport': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "PythonExport": obj_ = PythonExport.factory() obj_.build(child_) self.PythonExport.append(obj_) + + # end class GenerateModel class PythonExport: subclass = None - def __init__(self, Name='', PythonName='', Include='', Father='', Twin='', Namespace='', FatherInclude='', FatherNamespace='', Constructor=0, NumberProtocol=0, RichCompare=0, TwinPointer='', Delete=0, Reference=0, Initialization=0, DisableNotify=0, DescriptorGetter=0, DescriptorSetter=0, Documentation=None, Methode=None, Attribute=None, Sequence=None, CustomAttributes='', ClassDeclarations='', ForwardDeclarations=''): + + def __init__( + self, + Name="", + PythonName="", + Include="", + Father="", + Twin="", + Namespace="", + FatherInclude="", + FatherNamespace="", + Constructor=0, + NumberProtocol=0, + RichCompare=0, + TwinPointer="", + Delete=0, + Reference=0, + Initialization=0, + DisableNotify=0, + DescriptorGetter=0, + DescriptorSetter=0, + Documentation=None, + Methode=None, + Attribute=None, + Sequence=None, + CustomAttributes="", + ClassDeclarations="", + ForwardDeclarations="", + ): self.Name = Name self.PythonName = PythonName self.Include = Include @@ -252,104 +334,217 @@ class PythonExport: self.CustomAttributes = CustomAttributes self.ClassDeclarations = ClassDeclarations self.ForwardDeclarations = ForwardDeclarations + def factory(*args_, **kwargs_): if PythonExport.subclass: return PythonExport.subclass(*args_, **kwargs_) else: return PythonExport(*args_, **kwargs_) + factory = staticmethod(factory) - def getDocumentation(self): return self.Documentation - def setDocumentation(self, Documentation): self.Documentation = Documentation - def getMethode(self): return self.Methode - def setMethode(self, Methode): self.Methode = Methode - def addMethode(self, value): self.Methode.append(value) - def insertMethode(self, index, value): self.Methode[index] = value - def getAttribute(self): return self.Attribute - def setAttribute(self, Attribute): self.Attribute = Attribute - def addAttribute(self, value): self.Attribute.append(value) - def insertAttribute(self, index, value): self.Attribute[index] = value - def getSequence(self): return self.Sequence - def setSequence(self, Sequence): self.Sequence = Sequence - def getCustomattributes(self): return self.CustomAttributes - def setCustomattributes(self, CustomAttributes): self.CustomAttributes = CustomAttributes - def getClassdeclarations(self): return self.ClassDeclarations - def setClassdeclarations(self, ClassDeclarations): self.ClassDeclarations = ClassDeclarations - def getForwarddeclarations(self): return self.ForwardDeclarations - def setForwarddeclarations(self, ForwardDeclarations): self.ForwardDeclarations = ForwardDeclarations - def getName(self): return self.Name - def setName(self, Name): self.Name = Name - def getPythonname(self): return self.PythonName - def setPythonname(self, PythonName): self.PythonName = PythonName - def getInclude(self): return self.Include - def setInclude(self, Include): self.Include = Include - def getFather(self): return self.Father - def setFather(self, Father): self.Father = Father - def getTwin(self): return self.Twin - def setTwin(self, Twin): self.Twin = Twin - def getNamespace(self): return self.Namespace - def setNamespace(self, Namespace): self.Namespace = Namespace - def getFatherinclude(self): return self.FatherInclude - def setFatherinclude(self, FatherInclude): self.FatherInclude = FatherInclude - def getFathernamespace(self): return self.FatherNamespace - def setFathernamespace(self, FatherNamespace): self.FatherNamespace = FatherNamespace - def getConstructor(self): return self.Constructor - def setConstructor(self, Constructor): self.Constructor = Constructor - def getNumberprotocol(self): return self.NumberProtocol - def setNumberprotocol(self, NumberProtocol): self.NumberProtocol = NumberProtocol - def getRichcompare(self): return self.RichCompare - def setRichcompare(self, RichCompare): self.RichCompare = RichCompare - def getTwinpointer(self): return self.TwinPointer - def setTwinpointer(self, TwinPointer): self.TwinPointer = TwinPointer - def getDelete(self): return self.Delete - def setDelete(self, Delete): self.Delete = Delete - def getReference(self): return self.Reference - def setReference(self, Reference): self.Reference = Reference - def getInitialization(self): return self.Initialization - def setInitialization(self, Initialization): self.Initialization = Initialization - def getDisablenotify(self): return self.DisableNotify - def setDisablenotify(self, DisableNotify): self.DisableNotify = DisableNotify - def getDescriptorgetter(self): return self.DescriptorGetter - def setDescriptorgetter(self, DescriptorGetter): self.DescriptorGetter = DescriptorGetter - def getDescriptorsetter(self): return self.DescriptorSetter - def setDescriptorsetter(self, DescriptorSetter): self.DescriptorSetter = DescriptorSetter - def export(self, outfile, level, name_='PythonExport'): + + def getDocumentation(self): + return self.Documentation + + def setDocumentation(self, Documentation): + self.Documentation = Documentation + + def getMethode(self): + return self.Methode + + def setMethode(self, Methode): + self.Methode = Methode + + def addMethode(self, value): + self.Methode.append(value) + + def insertMethode(self, index, value): + self.Methode[index] = value + + def getAttribute(self): + return self.Attribute + + def setAttribute(self, Attribute): + self.Attribute = Attribute + + def addAttribute(self, value): + self.Attribute.append(value) + + def insertAttribute(self, index, value): + self.Attribute[index] = value + + def getSequence(self): + return self.Sequence + + def setSequence(self, Sequence): + self.Sequence = Sequence + + def getCustomattributes(self): + return self.CustomAttributes + + def setCustomattributes(self, CustomAttributes): + self.CustomAttributes = CustomAttributes + + def getClassdeclarations(self): + return self.ClassDeclarations + + def setClassdeclarations(self, ClassDeclarations): + self.ClassDeclarations = ClassDeclarations + + def getForwarddeclarations(self): + return self.ForwardDeclarations + + def setForwarddeclarations(self, ForwardDeclarations): + self.ForwardDeclarations = ForwardDeclarations + + def getName(self): + return self.Name + + def setName(self, Name): + self.Name = Name + + def getPythonname(self): + return self.PythonName + + def setPythonname(self, PythonName): + self.PythonName = PythonName + + def getInclude(self): + return self.Include + + def setInclude(self, Include): + self.Include = Include + + def getFather(self): + return self.Father + + def setFather(self, Father): + self.Father = Father + + def getTwin(self): + return self.Twin + + def setTwin(self, Twin): + self.Twin = Twin + + def getNamespace(self): + return self.Namespace + + def setNamespace(self, Namespace): + self.Namespace = Namespace + + def getFatherinclude(self): + return self.FatherInclude + + def setFatherinclude(self, FatherInclude): + self.FatherInclude = FatherInclude + + def getFathernamespace(self): + return self.FatherNamespace + + def setFathernamespace(self, FatherNamespace): + self.FatherNamespace = FatherNamespace + + def getConstructor(self): + return self.Constructor + + def setConstructor(self, Constructor): + self.Constructor = Constructor + + def getNumberprotocol(self): + return self.NumberProtocol + + def setNumberprotocol(self, NumberProtocol): + self.NumberProtocol = NumberProtocol + + def getRichcompare(self): + return self.RichCompare + + def setRichcompare(self, RichCompare): + self.RichCompare = RichCompare + + def getTwinpointer(self): + return self.TwinPointer + + def setTwinpointer(self, TwinPointer): + self.TwinPointer = TwinPointer + + def getDelete(self): + return self.Delete + + def setDelete(self, Delete): + self.Delete = Delete + + def getReference(self): + return self.Reference + + def setReference(self, Reference): + self.Reference = Reference + + def getInitialization(self): + return self.Initialization + + def setInitialization(self, Initialization): + self.Initialization = Initialization + + def getDisablenotify(self): + return self.DisableNotify + + def setDisablenotify(self, DisableNotify): + self.DisableNotify = DisableNotify + + def getDescriptorgetter(self): + return self.DescriptorGetter + + def setDescriptorgetter(self, DescriptorGetter): + self.DescriptorGetter = DescriptorGetter + + def getDescriptorsetter(self): + return self.DescriptorSetter + + def setDescriptorsetter(self, DescriptorSetter): + self.DescriptorSetter = DescriptorSetter + + def export(self, outfile, level, name_="PythonExport"): showIndent(outfile, level) - outfile.write('<%s' % (name_, )) - self.exportAttributes(outfile, level, name_='PythonExport') - outfile.write('>\n') + outfile.write("<%s" % (name_,)) + self.exportAttributes(outfile, level, name_="PythonExport") + outfile.write(">\n") self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='PythonExport'): - outfile.write(' Name="%s"' % (self.getName(), )) + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="PythonExport"): + outfile.write(' Name="%s"' % (self.getName(),)) if self.getPythonname() is not None: - outfile.write(' PythonName="%s"' % (self.getPythonname(), )) - outfile.write(' Include="%s"' % (self.getInclude(), )) - outfile.write(' Father="%s"' % (self.getFather(), )) - outfile.write(' Twin="%s"' % (self.getTwin(), )) - outfile.write(' Namespace="%s"' % (self.getNamespace(), )) - outfile.write(' FatherInclude="%s"' % (self.getFatherinclude(), )) - outfile.write(' FatherNamespace="%s"' % (self.getFathernamespace(), )) + outfile.write(' PythonName="%s"' % (self.getPythonname(),)) + outfile.write(' Include="%s"' % (self.getInclude(),)) + outfile.write(' Father="%s"' % (self.getFather(),)) + outfile.write(' Twin="%s"' % (self.getTwin(),)) + outfile.write(' Namespace="%s"' % (self.getNamespace(),)) + outfile.write(' FatherInclude="%s"' % (self.getFatherinclude(),)) + outfile.write(' FatherNamespace="%s"' % (self.getFathernamespace(),)) if self.getConstructor() is not None: - outfile.write(' Constructor="%s"' % (self.getConstructor(), )) + outfile.write(' Constructor="%s"' % (self.getConstructor(),)) if self.getNumberprotocol() is not None: - outfile.write(' NumberProtocol="%s"' % (self.getNumberprotocol(), )) + outfile.write(' NumberProtocol="%s"' % (self.getNumberprotocol(),)) if self.getRichcompare() is not None: - outfile.write(' RichCompare="%s"' % (self.getRichcompare(), )) - outfile.write(' TwinPointer="%s"' % (self.getTwinpointer(), )) + outfile.write(' RichCompare="%s"' % (self.getRichcompare(),)) + outfile.write(' TwinPointer="%s"' % (self.getTwinpointer(),)) if self.getDelete() is not None: - outfile.write(' Delete="%s"' % (self.getDelete(), )) + outfile.write(' Delete="%s"' % (self.getDelete(),)) if self.getReference() is not None: - outfile.write(' Reference="%s"' % (self.getReference(), )) + outfile.write(' Reference="%s"' % (self.getReference(),)) if self.getInitialization() is not None: - outfile.write(' Initialization="%s"' % (self.getInitialization(), )) + outfile.write(' Initialization="%s"' % (self.getInitialization(),)) if self.getDisablenotify() is not None: - outfile.write(' DisableNotify="%s"' % (self.getDisablenotify(), )) + outfile.write(' DisableNotify="%s"' % (self.getDisablenotify(),)) if self.getDescriptorgetter() is not None: - outfile.write(' DescriptorGetter="%s"' % (self.getDescriptorgetter(), )) + outfile.write(' DescriptorGetter="%s"' % (self.getDescriptorgetter(),)) if self.getDescriptorsetter() is not None: - outfile.write(' DescriptorSetter="%s"' % (self.getDescriptorsetter(), )) - def exportChildren(self, outfile, level, name_='PythonExport'): + outfile.write(' DescriptorSetter="%s"' % (self.getDescriptorsetter(),)) + + def exportChildren(self, outfile, level, name_="PythonExport"): if self.Documentation: self.Documentation.export(outfile, level) for Methode_ in self.getMethode(): @@ -359,15 +554,24 @@ class PythonExport: if self.Sequence: self.Sequence.export(outfile, level) showIndent(outfile, level) - outfile.write('%s\n' % quote_xml(self.getCustomattributes())) + outfile.write( + "%s\n" % quote_xml(self.getCustomattributes()) + ) showIndent(outfile, level) - outfile.write('%s\n' % quote_xml(self.getClassdeclarations())) + outfile.write( + "%s\n" % quote_xml(self.getClassdeclarations()) + ) showIndent(outfile, level) - outfile.write('%s\n' % quote_xml(self.getForwarddeclarations())) - def exportLiteral(self, outfile, level, name_='PythonExport'): + outfile.write( + "%s\n" + % quote_xml(self.getForwarddeclarations()) + ) + + def exportLiteral(self, outfile, level, name_="PythonExport"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) @@ -405,182 +609,191 @@ class PythonExport: outfile.write('DescriptorGetter = "%s",\n' % (self.getDescriptorgetter(),)) showIndent(outfile, level) outfile.write('DescriptorSetter = "%s",\n' % (self.getDescriptorsetter(),)) + def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) - outfile.write('Documentation=Documentation(\n') + outfile.write("Documentation=Documentation(\n") self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") showIndent(outfile, level) - outfile.write('Methode=[\n') + outfile.write("Methode=[\n") level += 1 for Methode in self.Methode: showIndent(outfile, level) - outfile.write('Methode(\n') + outfile.write("Methode(\n") Methode.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") showIndent(outfile, level) - outfile.write('Attribute=[\n') + outfile.write("Attribute=[\n") level += 1 for Attribute in self.Attribute: showIndent(outfile, level) - outfile.write('Attribute(\n') + outfile.write("Attribute(\n") Attribute.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") if self.Sequence: showIndent(outfile, level) - outfile.write('Sequence=Sequence(\n') + outfile.write("Sequence=Sequence(\n") self.Sequence.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") showIndent(outfile, level) - outfile.write('CustomAttributes=%s,\n' % quote_python(self.getCustomattributes())) + outfile.write("CustomAttributes=%s,\n" % quote_python(self.getCustomattributes())) showIndent(outfile, level) - outfile.write('ClassDeclarations=%s,\n' % quote_python(self.getClassdeclarations())) + outfile.write("ClassDeclarations=%s,\n" % quote_python(self.getClassdeclarations())) showIndent(outfile, level) - outfile.write('ForwardDeclarations=%s,\n' % quote_python(self.getForwarddeclarations())) + outfile.write("ForwardDeclarations=%s,\n" % quote_python(self.getForwarddeclarations())) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): - if attrs.get('Name'): - self.Name = attrs.get('Name').value - if attrs.get('PythonName'): - self.PythonName = attrs.get('PythonName').value - if attrs.get('Include'): - self.Include = attrs.get('Include').value - if attrs.get('Father'): - self.Father = attrs.get('Father').value - if attrs.get('Twin'): - self.Twin = attrs.get('Twin').value - if attrs.get('Namespace'): - self.Namespace = attrs.get('Namespace').value - if attrs.get('FatherInclude'): - self.FatherInclude = attrs.get('FatherInclude').value - if attrs.get('FatherNamespace'): - self.FatherNamespace = attrs.get('FatherNamespace').value - if attrs.get('Constructor'): - if attrs.get('Constructor').value in ('true', '1'): + if attrs.get("Name"): + self.Name = attrs.get("Name").value + if attrs.get("PythonName"): + self.PythonName = attrs.get("PythonName").value + if attrs.get("Include"): + self.Include = attrs.get("Include").value + if attrs.get("Father"): + self.Father = attrs.get("Father").value + if attrs.get("Twin"): + self.Twin = attrs.get("Twin").value + if attrs.get("Namespace"): + self.Namespace = attrs.get("Namespace").value + if attrs.get("FatherInclude"): + self.FatherInclude = attrs.get("FatherInclude").value + if attrs.get("FatherNamespace"): + self.FatherNamespace = attrs.get("FatherNamespace").value + if attrs.get("Constructor"): + if attrs.get("Constructor").value in ("true", "1"): self.Constructor = 1 - elif attrs.get('Constructor').value in ('false', '0'): + elif attrs.get("Constructor").value in ("false", "0"): self.Constructor = 0 else: - raise ValueError('Bad boolean attribute (Constructor)') - if attrs.get('NumberProtocol'): - if attrs.get('NumberProtocol').value in ('true', '1'): + raise ValueError("Bad boolean attribute (Constructor)") + if attrs.get("NumberProtocol"): + if attrs.get("NumberProtocol").value in ("true", "1"): self.NumberProtocol = 1 - elif attrs.get('NumberProtocol').value in ('false', '0'): + elif attrs.get("NumberProtocol").value in ("false", "0"): self.NumberProtocol = 0 else: - raise ValueError('Bad boolean attribute (NumberProtocol)') - if attrs.get('RichCompare'): - if attrs.get('RichCompare').value in ('true', '1'): + raise ValueError("Bad boolean attribute (NumberProtocol)") + if attrs.get("RichCompare"): + if attrs.get("RichCompare").value in ("true", "1"): self.RichCompare = 1 - elif attrs.get('RichCompare').value in ('false', '0'): + elif attrs.get("RichCompare").value in ("false", "0"): self.RichCompare = 0 else: - raise ValueError('Bad boolean attribute (RichCompare)') - if attrs.get('TwinPointer'): - self.TwinPointer = attrs.get('TwinPointer').value - if attrs.get('Delete'): - if attrs.get('Delete').value in ('true', '1'): + raise ValueError("Bad boolean attribute (RichCompare)") + if attrs.get("TwinPointer"): + self.TwinPointer = attrs.get("TwinPointer").value + if attrs.get("Delete"): + if attrs.get("Delete").value in ("true", "1"): self.Delete = 1 - elif attrs.get('Delete').value in ('false', '0'): + elif attrs.get("Delete").value in ("false", "0"): self.Delete = 0 else: - raise ValueError('Bad boolean attribute (Delete)') - if attrs.get('Reference'): - if attrs.get('Reference').value in ('true', '1'): + raise ValueError("Bad boolean attribute (Delete)") + if attrs.get("Reference"): + if attrs.get("Reference").value in ("true", "1"): self.Reference = 1 - elif attrs.get('Reference').value in ('false', '0'): + elif attrs.get("Reference").value in ("false", "0"): self.Reference = 0 else: - raise ValueError('Bad boolean attribute (Reference)') - if attrs.get('Initialization'): - if attrs.get('Initialization').value in ('true', '1'): + raise ValueError("Bad boolean attribute (Reference)") + if attrs.get("Initialization"): + if attrs.get("Initialization").value in ("true", "1"): self.Initialization = 1 - elif attrs.get('Initialization').value in ('false', '0'): + elif attrs.get("Initialization").value in ("false", "0"): self.Initialization = 0 else: - raise ValueError('Bad boolean attribute (Initialization)') - if attrs.get('DisableNotify'): - if attrs.get('DisableNotify').value in ('true', '1'): + raise ValueError("Bad boolean attribute (Initialization)") + if attrs.get("DisableNotify"): + if attrs.get("DisableNotify").value in ("true", "1"): self.DisableNotify = 1 - elif attrs.get('DisableNotify').value in ('false', '0'): + elif attrs.get("DisableNotify").value in ("false", "0"): self.DisableNotify = 0 else: - raise ValueError('Bad boolean attribute (DisableNotify)') - if attrs.get('DescriptorGetter'): - if attrs.get('DescriptorGetter').value in ('true', '1'): + raise ValueError("Bad boolean attribute (DisableNotify)") + if attrs.get("DescriptorGetter"): + if attrs.get("DescriptorGetter").value in ("true", "1"): self.DescriptorGetter = 1 - elif attrs.get('DescriptorGetter').value in ('false', '0'): + elif attrs.get("DescriptorGetter").value in ("false", "0"): self.DescriptorGetter = 0 else: - raise ValueError('Bad boolean attribute (DescriptorGetter)') - if attrs.get('DescriptorSetter'): - if attrs.get('DescriptorSetter').value in ('true', '1'): + raise ValueError("Bad boolean attribute (DescriptorGetter)") + if attrs.get("DescriptorSetter"): + if attrs.get("DescriptorSetter").value in ("true", "1"): self.DescriptorSetter = 1 - elif attrs.get('DescriptorSetter').value in ('false', '0'): + elif attrs.get("DescriptorSetter").value in ("false", "0"): self.DescriptorSetter = 0 else: - raise ValueError('Bad boolean attribute (DescriptorSetter)') + raise ValueError("Bad boolean attribute (DescriptorSetter)") + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Documentation': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Documentation": obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Methode': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Methode": obj_ = Methode.factory() obj_.build(child_) self.Methode.append(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Attribute': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Attribute": obj_ = Attribute.factory() obj_.build(child_) self.Attribute.append(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Sequence': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Sequence": obj_ = Sequence.factory() obj_.build(child_) self.setSequence(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'CustomAttributes': - CustomAttributes_ = '' + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "CustomAttributes": + CustomAttributes_ = "" for text__content_ in child_.childNodes: CustomAttributes_ += text__content_.nodeValue self.CustomAttributes = CustomAttributes_ - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'ClassDeclarations': - ClassDeclarations_ = '' + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "ClassDeclarations": + ClassDeclarations_ = "" for text__content_ in child_.childNodes: ClassDeclarations_ += text__content_.nodeValue self.ClassDeclarations = ClassDeclarations_ - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'ForwardDeclarations': - ForwardDeclarations_ = '' + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "ForwardDeclarations": + ForwardDeclarations_ = "" for text__content_ in child_.childNodes: ForwardDeclarations_ += text__content_.nodeValue self.ForwardDeclarations = ForwardDeclarations_ + + # end class PythonExport class Methode: subclass = None - def __init__(self, Name='', Const=0, Keyword=0, Class=0, Static=0, Documentation=None, Parameter=None): + + def __init__( + self, + Name="", + Const=0, + Keyword=0, + Class=0, + Static=0, + Documentation=None, + Parameter=None, + ): self.Name = Name self.Const = Const self.Keyword = Keyword @@ -591,55 +804,94 @@ class Methode: self.Parameter = [] else: self.Parameter = Parameter + def factory(*args_, **kwargs_): if Methode.subclass: return Methode.subclass(*args_, **kwargs_) else: return Methode(*args_, **kwargs_) + factory = staticmethod(factory) - def getDocumentation(self): return self.Documentation - def setDocumentation(self, Documentation): self.Documentation = Documentation - def getParameter(self): return self.Parameter - def setParameter(self, Parameter): self.Parameter = Parameter - def addParameter(self, value): self.Parameter.append(value) - def insertParameter(self, index, value): self.Parameter[index] = value - def getName(self): return self.Name - def setName(self, Name): self.Name = Name - def getConst(self): return self.Const - def setConst(self, Const): self.Const = Const - def getKeyword(self): return self.Keyword - def setKeyword(self, Keyword): self.Keyword = Keyword - def getClass(self): return self.Class - def setClass(self, Class): self.Class = Class - def getStatic(self): return self.Static - def setStatic(self, Static): self.Static = Static - def export(self, outfile, level, name_='Methode'): + + def getDocumentation(self): + return self.Documentation + + def setDocumentation(self, Documentation): + self.Documentation = Documentation + + def getParameter(self): + return self.Parameter + + def setParameter(self, Parameter): + self.Parameter = Parameter + + def addParameter(self, value): + self.Parameter.append(value) + + def insertParameter(self, index, value): + self.Parameter[index] = value + + def getName(self): + return self.Name + + def setName(self, Name): + self.Name = Name + + def getConst(self): + return self.Const + + def setConst(self, Const): + self.Const = Const + + def getKeyword(self): + return self.Keyword + + def setKeyword(self, Keyword): + self.Keyword = Keyword + + def getClass(self): + return self.Class + + def setClass(self, Class): + self.Class = Class + + def getStatic(self): + return self.Static + + def setStatic(self, Static): + self.Static = Static + + def export(self, outfile, level, name_="Methode"): showIndent(outfile, level) - outfile.write('<%s' % (name_, )) - self.exportAttributes(outfile, level, name_='Methode') - outfile.write('>\n') + outfile.write("<%s" % (name_,)) + self.exportAttributes(outfile, level, name_="Methode") + outfile.write(">\n") self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Methode'): - outfile.write(' Name="%s"' % (self.getName(), )) + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Methode"): + outfile.write(' Name="%s"' % (self.getName(),)) if self.getConst() is not None: - outfile.write(' Const="%s"' % (self.getConst(), )) + outfile.write(' Const="%s"' % (self.getConst(),)) if self.getKeyword() is not None: - outfile.write(' Keyword="%s"' % (self.getKeyword(), )) + outfile.write(' Keyword="%s"' % (self.getKeyword(),)) if self.getClass() is not None: - outfile.write(' Class="%s"' % (self.getClass(), )) + outfile.write(' Class="%s"' % (self.getClass(),)) if self.getStatic() is not None: - outfile.write(' Static="%s"' % (self.getStatic(), )) - def exportChildren(self, outfile, level, name_='Methode'): + outfile.write(' Static="%s"' % (self.getStatic(),)) + + def exportChildren(self, outfile, level, name_="Methode"): if self.Documentation: self.Documentation.export(outfile, level) for Parameter_ in self.getParameter(): Parameter_.export(outfile, level) - def exportLiteral(self, outfile, level, name_='Methode'): + + def exportLiteral(self, outfile, level, name_="Methode"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) @@ -651,168 +903,214 @@ class Methode: outfile.write('Class = "%s",\n' % (self.getClass(),)) showIndent(outfile, level) outfile.write('Static = "%s",\n' % (self.getStatic(),)) + def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) - outfile.write('Documentation=Documentation(\n') + outfile.write("Documentation=Documentation(\n") self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") showIndent(outfile, level) - outfile.write('Parameter=[\n') + outfile.write("Parameter=[\n") level += 1 for Parameter in self.Parameter: showIndent(outfile, level) - outfile.write('Parameter(\n') + outfile.write("Parameter(\n") Parameter.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): - if attrs.get('Name'): - self.Name = attrs.get('Name').value - if attrs.get('Const'): - if attrs.get('Const').value in ('true', '1'): + if attrs.get("Name"): + self.Name = attrs.get("Name").value + if attrs.get("Const"): + if attrs.get("Const").value in ("true", "1"): self.Const = 1 - elif attrs.get('Const').value in ('false', '0'): + elif attrs.get("Const").value in ("false", "0"): self.Const = 0 else: - raise ValueError('Bad boolean attribute (Const)') - if attrs.get('Keyword'): - if attrs.get('Keyword').value in ('true', '1'): + raise ValueError("Bad boolean attribute (Const)") + if attrs.get("Keyword"): + if attrs.get("Keyword").value in ("true", "1"): self.Keyword = 1 - elif attrs.get('Keyword').value in ('false', '0'): + elif attrs.get("Keyword").value in ("false", "0"): self.Keyword = 0 else: - raise ValueError('Bad boolean attribute (Keyword)') - if attrs.get('Class'): - if attrs.get('Class').value in ('true', '1'): + raise ValueError("Bad boolean attribute (Keyword)") + if attrs.get("Class"): + if attrs.get("Class").value in ("true", "1"): self.Class = 1 - elif attrs.get('Class').value in ('false', '0'): + elif attrs.get("Class").value in ("false", "0"): self.Class = 0 else: - raise ValueError('Bad boolean attribute (Class)') - if attrs.get('Static'): - if attrs.get('Static').value in ('true', '1'): + raise ValueError("Bad boolean attribute (Class)") + if attrs.get("Static"): + if attrs.get("Static").value in ("true", "1"): self.Static = 1 - elif attrs.get('Static').value in ('false', '0'): + elif attrs.get("Static").value in ("false", "0"): self.Static = 0 else: - raise ValueError('Bad boolean attribute (Static)') + raise ValueError("Bad boolean attribute (Static)") + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Documentation': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Documentation": obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Parameter': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Parameter": obj_ = Parameter.factory() obj_.build(child_) self.Parameter.append(obj_) + + # end class Methode class Attribute: subclass = None - def __init__(self, Name='', ReadOnly=0, Documentation=None, Parameter=None): + + def __init__(self, Name="", ReadOnly=0, Documentation=None, Parameter=None): self.Name = Name self.ReadOnly = ReadOnly self.Documentation = Documentation self.Parameter = Parameter + def factory(*args_, **kwargs_): if Attribute.subclass: return Attribute.subclass(*args_, **kwargs_) else: return Attribute(*args_, **kwargs_) + factory = staticmethod(factory) - def getDocumentation(self): return self.Documentation - def setDocumentation(self, Documentation): self.Documentation = Documentation - def getParameter(self): return self.Parameter - def setParameter(self, Parameter): self.Parameter = Parameter - def getName(self): return self.Name - def setName(self, Name): self.Name = Name - def getReadonly(self): return self.ReadOnly - def setReadonly(self, ReadOnly): self.ReadOnly = ReadOnly - def export(self, outfile, level, name_='Attribute'): + + def getDocumentation(self): + return self.Documentation + + def setDocumentation(self, Documentation): + self.Documentation = Documentation + + def getParameter(self): + return self.Parameter + + def setParameter(self, Parameter): + self.Parameter = Parameter + + def getName(self): + return self.Name + + def setName(self, Name): + self.Name = Name + + def getReadonly(self): + return self.ReadOnly + + def setReadonly(self, ReadOnly): + self.ReadOnly = ReadOnly + + def export(self, outfile, level, name_="Attribute"): showIndent(outfile, level) - outfile.write('<%s' % (name_, )) - self.exportAttributes(outfile, level, name_='Attribute') - outfile.write('>\n') + outfile.write("<%s" % (name_,)) + self.exportAttributes(outfile, level, name_="Attribute") + outfile.write(">\n") self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Attribute'): - outfile.write(' Name="%s"' % (self.getName(), )) - outfile.write(' ReadOnly="%s"' % (self.getReadonly(), )) - def exportChildren(self, outfile, level, name_='Attribute'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Attribute"): + outfile.write(' Name="%s"' % (self.getName(),)) + outfile.write(' ReadOnly="%s"' % (self.getReadonly(),)) + + def exportChildren(self, outfile, level, name_="Attribute"): if self.Documentation: self.Documentation.export(outfile, level) if self.Parameter: self.Parameter.export(outfile, level) - def exportLiteral(self, outfile, level, name_='Attribute'): + + def exportLiteral(self, outfile, level, name_="Attribute"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) showIndent(outfile, level) outfile.write('ReadOnly = "%s",\n' % (self.getReadonly(),)) + def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) - outfile.write('Documentation=Documentation(\n') + outfile.write("Documentation=Documentation(\n") self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") if self.Parameter: showIndent(outfile, level) - outfile.write('Parameter=Parameter(\n') + outfile.write("Parameter=Parameter(\n") self.Parameter.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): - if attrs.get('Name'): - self.Name = attrs.get('Name').value - if attrs.get('ReadOnly'): - if attrs.get('ReadOnly').value in ('true', '1'): + if attrs.get("Name"): + self.Name = attrs.get("Name").value + if attrs.get("ReadOnly"): + if attrs.get("ReadOnly").value in ("true", "1"): self.ReadOnly = 1 - elif attrs.get('ReadOnly').value in ('false', '0'): + elif attrs.get("ReadOnly").value in ("false", "0"): self.ReadOnly = 0 else: - raise ValueError('Bad boolean attribute (ReadOnly)') + raise ValueError("Bad boolean attribute (ReadOnly)") + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Documentation': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Documentation": obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Parameter': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Parameter": obj_ = Parameter.factory() obj_.build(child_) self.setParameter(obj_) + + # end class Attribute class Sequence: subclass = None - def __init__(self, sq_length=0, sq_concat=0, sq_repeat=0, sq_item=0, mp_subscript=0, sq_ass_item=0, mp_ass_subscript=0, sq_contains=0, sq_inplace_concat=0, sq_inplace_repeat=0, valueOf_=''): + + def __init__( + self, + sq_length=0, + sq_concat=0, + sq_repeat=0, + sq_item=0, + mp_subscript=0, + sq_ass_item=0, + mp_ass_subscript=0, + sq_contains=0, + sq_inplace_concat=0, + sq_inplace_repeat=0, + valueOf_="", + ): self.sq_length = sq_length self.sq_concat = sq_concat self.sq_repeat = sq_repeat @@ -824,59 +1122,110 @@ class Sequence: self.sq_inplace_concat = sq_inplace_concat self.sq_inplace_repeat = sq_inplace_repeat self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if Sequence.subclass: return Sequence.subclass(*args_, **kwargs_) else: return Sequence(*args_, **kwargs_) + factory = staticmethod(factory) - def getSq_length(self): return self.sq_length - def setSq_length(self, sq_length): self.sq_length = sq_length - def getSq_concat(self): return self.sq_concat - def setSq_concat(self, sq_concat): self.sq_concat = sq_concat - def getSq_repeat(self): return self.sq_repeat - def setSq_repeat(self, sq_repeat): self.sq_repeat = sq_repeat - def getSq_item(self): return self.sq_item - def setSq_item(self, sq_item): self.sq_item = sq_item - def getMp_subscript(self): return self.mp_subscript - def setMp_subscript(self, mp_subscript): self.mp_subscript = mp_subscript - def getSq_ass_item(self): return self.sq_ass_item - def setSq_ass_item(self, sq_ass_item): self.sq_ass_item = sq_ass_item - def getMp_ass_subscript(self): return self.mp_ass_subscript - def setMp_ass_subscript(self, mp_ass_subscript): self.mp_ass_subscript = mp_ass_subscript - def getSq_contains(self): return self.sq_contains - def setSq_contains(self, sq_contains): self.sq_contains = sq_contains - def getSq_inplace_concat(self): return self.sq_inplace_concat - def setSq_inplace_concat(self, sq_inplace_concat): self.sq_inplace_concat = sq_inplace_concat - def getSq_inplace_repeat(self): return self.sq_inplace_repeat - def setSq_inplace_repeat(self, sq_inplace_repeat): self.sq_inplace_repeat = sq_inplace_repeat - def getValueOf_(self): return self.valueOf_ - def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, name_='Sequence'): + + def getSq_length(self): + return self.sq_length + + def setSq_length(self, sq_length): + self.sq_length = sq_length + + def getSq_concat(self): + return self.sq_concat + + def setSq_concat(self, sq_concat): + self.sq_concat = sq_concat + + def getSq_repeat(self): + return self.sq_repeat + + def setSq_repeat(self, sq_repeat): + self.sq_repeat = sq_repeat + + def getSq_item(self): + return self.sq_item + + def setSq_item(self, sq_item): + self.sq_item = sq_item + + def getMp_subscript(self): + return self.mp_subscript + + def setMp_subscript(self, mp_subscript): + self.mp_subscript = mp_subscript + + def getSq_ass_item(self): + return self.sq_ass_item + + def setSq_ass_item(self, sq_ass_item): + self.sq_ass_item = sq_ass_item + + def getMp_ass_subscript(self): + return self.mp_ass_subscript + + def setMp_ass_subscript(self, mp_ass_subscript): + self.mp_ass_subscript = mp_ass_subscript + + def getSq_contains(self): + return self.sq_contains + + def setSq_contains(self, sq_contains): + self.sq_contains = sq_contains + + def getSq_inplace_concat(self): + return self.sq_inplace_concat + + def setSq_inplace_concat(self, sq_inplace_concat): + self.sq_inplace_concat = sq_inplace_concat + + def getSq_inplace_repeat(self): + return self.sq_inplace_repeat + + def setSq_inplace_repeat(self, sq_inplace_repeat): + self.sq_inplace_repeat = sq_inplace_repeat + + def getValueOf_(self): + return self.valueOf_ + + def setValueOf_(self, valueOf_): + self.valueOf_ = valueOf_ + + def export(self, outfile, level, name_="Sequence"): showIndent(outfile, level) - outfile.write('<%s' % (name_, )) - self.exportAttributes(outfile, level, name_='Sequence') - outfile.write('>\n') + outfile.write("<%s" % (name_,)) + self.exportAttributes(outfile, level, name_="Sequence") + outfile.write(">\n") self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Sequence'): - outfile.write(' sq_length="%s"' % (self.getSq_length(), )) - outfile.write(' sq_concat="%s"' % (self.getSq_concat(), )) - outfile.write(' sq_repeat="%s"' % (self.getSq_repeat(), )) - outfile.write(' sq_item="%s"' % (self.getSq_item(), )) - outfile.write(' mp_subscript="%s"' % (self.getMp_subscript(), )) - outfile.write(' sq_ass_item="%s"' % (self.getSq_ass_item(), )) - outfile.write(' mp_ass_subscript="%s"' % (self.getMp_ass_subscript(), )) - outfile.write(' sq_contains="%s"' % (self.getSq_contains(), )) - outfile.write(' sq_inplace_concat="%s"' % (self.getSq_inplace_concat(), )) - outfile.write(' sq_inplace_repeat="%s"' % (self.getSq_inplace_repeat(), )) - def exportChildren(self, outfile, level, name_='Sequence'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Sequence"): + outfile.write(' sq_length="%s"' % (self.getSq_length(),)) + outfile.write(' sq_concat="%s"' % (self.getSq_concat(),)) + outfile.write(' sq_repeat="%s"' % (self.getSq_repeat(),)) + outfile.write(' sq_item="%s"' % (self.getSq_item(),)) + outfile.write(' mp_subscript="%s"' % (self.getMp_subscript(),)) + outfile.write(' sq_ass_item="%s"' % (self.getSq_ass_item(),)) + outfile.write(' mp_ass_subscript="%s"' % (self.getMp_ass_subscript(),)) + outfile.write(' sq_contains="%s"' % (self.getSq_contains(),)) + outfile.write(' sq_inplace_concat="%s"' % (self.getSq_inplace_concat(),)) + outfile.write(' sq_inplace_repeat="%s"' % (self.getSq_inplace_repeat(),)) + + def exportChildren(self, outfile, level, name_="Sequence"): outfile.write(self.valueOf_) - def exportLiteral(self, outfile, level, name_='Sequence'): + + def exportLiteral(self, outfile, level, name_="Sequence"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('sq_length = "%s",\n' % (self.getSq_length(),)) @@ -898,253 +1247,315 @@ class Sequence: outfile.write('sq_inplace_concat = "%s",\n' % (self.getSq_inplace_concat(),)) showIndent(outfile, level) outfile.write('sq_inplace_repeat = "%s",\n' % (self.getSq_inplace_repeat(),)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): - if attrs.get('sq_length'): - if attrs.get('sq_length').value in ('true', '1'): + if attrs.get("sq_length"): + if attrs.get("sq_length").value in ("true", "1"): self.sq_length = 1 - elif attrs.get('sq_length').value in ('false', '0'): + elif attrs.get("sq_length").value in ("false", "0"): self.sq_length = 0 else: - raise ValueError('Bad boolean attribute (sq_length)') - if attrs.get('sq_concat'): - if attrs.get('sq_concat').value in ('true', '1'): + raise ValueError("Bad boolean attribute (sq_length)") + if attrs.get("sq_concat"): + if attrs.get("sq_concat").value in ("true", "1"): self.sq_concat = 1 - elif attrs.get('sq_concat').value in ('false', '0'): + elif attrs.get("sq_concat").value in ("false", "0"): self.sq_concat = 0 else: - raise ValueError('Bad boolean attribute (sq_concat)') - if attrs.get('sq_repeat'): - if attrs.get('sq_repeat').value in ('true', '1'): + raise ValueError("Bad boolean attribute (sq_concat)") + if attrs.get("sq_repeat"): + if attrs.get("sq_repeat").value in ("true", "1"): self.sq_repeat = 1 - elif attrs.get('sq_repeat').value in ('false', '0'): + elif attrs.get("sq_repeat").value in ("false", "0"): self.sq_repeat = 0 else: - raise ValueError('Bad boolean attribute (sq_repeat)') - if attrs.get('sq_item'): - if attrs.get('sq_item').value in ('true', '1'): + raise ValueError("Bad boolean attribute (sq_repeat)") + if attrs.get("sq_item"): + if attrs.get("sq_item").value in ("true", "1"): self.sq_item = 1 - elif attrs.get('sq_item').value in ('false', '0'): + elif attrs.get("sq_item").value in ("false", "0"): self.sq_item = 0 else: - raise ValueError('Bad boolean attribute (sq_item)') - if attrs.get('mp_subscript'): - if attrs.get('mp_subscript').value in ('true', '1'): + raise ValueError("Bad boolean attribute (sq_item)") + if attrs.get("mp_subscript"): + if attrs.get("mp_subscript").value in ("true", "1"): self.mp_subscript = 1 - elif attrs.get('mp_subscript').value in ('false', '0'): + elif attrs.get("mp_subscript").value in ("false", "0"): self.mp_subscript = 0 else: - raise ValueError('Bad boolean attribute (mp_subscript)') - if attrs.get('sq_ass_item'): - if attrs.get('sq_ass_item').value in ('true', '1'): + raise ValueError("Bad boolean attribute (mp_subscript)") + if attrs.get("sq_ass_item"): + if attrs.get("sq_ass_item").value in ("true", "1"): self.sq_ass_item = 1 - elif attrs.get('sq_ass_item').value in ('false', '0'): + elif attrs.get("sq_ass_item").value in ("false", "0"): self.sq_ass_item = 0 else: - raise ValueError('Bad boolean attribute (sq_ass_item)') - if attrs.get('mp_ass_subscript'): - if attrs.get('mp_ass_subscript').value in ('true', '1'): + raise ValueError("Bad boolean attribute (sq_ass_item)") + if attrs.get("mp_ass_subscript"): + if attrs.get("mp_ass_subscript").value in ("true", "1"): self.mp_ass_subscript = 1 - elif attrs.get('mp_ass_subscript').value in ('false', '0'): + elif attrs.get("mp_ass_subscript").value in ("false", "0"): self.mp_ass_subscript = 0 else: - raise ValueError('Bad boolean attribute (mp_ass_subscript)') - if attrs.get('sq_contains'): - if attrs.get('sq_contains').value in ('true', '1'): + raise ValueError("Bad boolean attribute (mp_ass_subscript)") + if attrs.get("sq_contains"): + if attrs.get("sq_contains").value in ("true", "1"): self.sq_contains = 1 - elif attrs.get('sq_contains').value in ('false', '0'): + elif attrs.get("sq_contains").value in ("false", "0"): self.sq_contains = 0 else: - raise ValueError('Bad boolean attribute (sq_contains)') - if attrs.get('sq_inplace_concat'): - if attrs.get('sq_inplace_concat').value in ('true', '1'): + raise ValueError("Bad boolean attribute (sq_contains)") + if attrs.get("sq_inplace_concat"): + if attrs.get("sq_inplace_concat").value in ("true", "1"): self.sq_inplace_concat = 1 - elif attrs.get('sq_inplace_concat').value in ('false', '0'): + elif attrs.get("sq_inplace_concat").value in ("false", "0"): self.sq_inplace_concat = 0 else: - raise ValueError('Bad boolean attribute (sq_inplace_concat)') - if attrs.get('sq_inplace_repeat'): - if attrs.get('sq_inplace_repeat').value in ('true', '1'): + raise ValueError("Bad boolean attribute (sq_inplace_concat)") + if attrs.get("sq_inplace_repeat"): + if attrs.get("sq_inplace_repeat").value in ("true", "1"): self.sq_inplace_repeat = 1 - elif attrs.get('sq_inplace_repeat').value in ('false', '0'): + elif attrs.get("sq_inplace_repeat").value in ("false", "0"): self.sq_inplace_repeat = 0 else: - raise ValueError('Bad boolean attribute (sq_inplace_repeat)') + raise ValueError("Bad boolean attribute (sq_inplace_repeat)") + def buildChildren(self, child_, nodeName_): - self.valueOf_ = '' + self.valueOf_ = "" for child in child_.childNodes: if child.nodeType == Node.TEXT_NODE: self.valueOf_ += child.nodeValue + + # end class Sequence class Module: subclass = None - def __init__(self, Name='', Documentation=None, Dependencies=None, Content=None): + + def __init__(self, Name="", Documentation=None, Dependencies=None, Content=None): self.Name = Name self.Documentation = Documentation self.Dependencies = Dependencies self.Content = Content + def factory(*args_, **kwargs_): if Module.subclass: return Module.subclass(*args_, **kwargs_) else: return Module(*args_, **kwargs_) + factory = staticmethod(factory) - def getDocumentation(self): return self.Documentation - def setDocumentation(self, Documentation): self.Documentation = Documentation - def getDependencies(self): return self.Dependencies - def setDependencies(self, Dependencies): self.Dependencies = Dependencies - def getContent(self): return self.Content - def setContent(self, Content): self.Content = Content - def getName(self): return self.Name - def setName(self, Name): self.Name = Name - def export(self, outfile, level, name_='Module'): + + def getDocumentation(self): + return self.Documentation + + def setDocumentation(self, Documentation): + self.Documentation = Documentation + + def getDependencies(self): + return self.Dependencies + + def setDependencies(self, Dependencies): + self.Dependencies = Dependencies + + def getContent(self): + return self.Content + + def setContent(self, Content): + self.Content = Content + + def getName(self): + return self.Name + + def setName(self, Name): + self.Name = Name + + def export(self, outfile, level, name_="Module"): showIndent(outfile, level) - outfile.write('<%s' % (name_, )) - self.exportAttributes(outfile, level, name_='Module') - outfile.write('>\n') + outfile.write("<%s" % (name_,)) + self.exportAttributes(outfile, level, name_="Module") + outfile.write(">\n") self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Module'): - outfile.write(' Name="%s"' % (self.getName(), )) - def exportChildren(self, outfile, level, name_='Module'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Module"): + outfile.write(' Name="%s"' % (self.getName(),)) + + def exportChildren(self, outfile, level, name_="Module"): if self.Documentation: self.Documentation.export(outfile, level) if self.Dependencies: self.Dependencies.export(outfile, level) if self.Content: self.Content.export(outfile, level) - def exportLiteral(self, outfile, level, name_='Module'): + + def exportLiteral(self, outfile, level, name_="Module"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) + def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) - outfile.write('Documentation=Documentation(\n') + outfile.write("Documentation=Documentation(\n") self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") if self.Dependencies: showIndent(outfile, level) - outfile.write('Dependencies=Dependencies(\n') + outfile.write("Dependencies=Dependencies(\n") self.Dependencies.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") if self.Content: showIndent(outfile, level) - outfile.write('Content=Content(\n') + outfile.write("Content=Content(\n") self.Content.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): - if attrs.get('Name'): - self.Name = attrs.get('Name').value + if attrs.get("Name"): + self.Name = attrs.get("Name").value + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Documentation': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Documentation": obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Dependencies': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Dependencies": obj_ = Dependencies.factory() obj_.build(child_) self.setDependencies(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Content': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Content": obj_ = Content.factory() obj_.build(child_) self.setContent(obj_) + + # end class Module class Dependencies: subclass = None + def __init__(self, Module=None): if Module is None: self.Module = [] else: self.Module = Module + def factory(*args_, **kwargs_): if Dependencies.subclass: return Dependencies.subclass(*args_, **kwargs_) else: return Dependencies(*args_, **kwargs_) + factory = staticmethod(factory) - def getModule(self): return self.Module - def setModule(self, Module): self.Module = Module - def addModule(self, value): self.Module.append(value) - def insertModule(self, index, value): self.Module[index] = value - def export(self, outfile, level, name_='Dependencies'): + + def getModule(self): + return self.Module + + def setModule(self, Module): + self.Module = Module + + def addModule(self, value): + self.Module.append(value) + + def insertModule(self, index, value): + self.Module[index] = value + + def export(self, outfile, level, name_="Dependencies"): showIndent(outfile, level) - outfile.write('<%s>\n' % name_) + outfile.write("<%s>\n" % name_) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Dependencies'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Dependencies"): pass - def exportChildren(self, outfile, level, name_='Dependencies'): + + def exportChildren(self, outfile, level, name_="Dependencies"): for Module_ in self.getModule(): Module_.export(outfile, level) - def exportLiteral(self, outfile, level, name_='Dependencies'): + + def exportLiteral(self, outfile, level, name_="Dependencies"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('Module=[\n') + outfile.write("Module=[\n") level += 1 for Module in self.Module: showIndent(outfile, level) - outfile.write('Module(\n') + outfile.write("Module(\n") Module.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Module': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Module": obj_ = Module.factory() obj_.build(child_) self.Module.append(obj_) + + # end class Dependencies class Content: subclass = None - def __init__(self, Property=None, Feature=None, DocObject=None, GuiCommand=None, PreferencesPage=None): + + def __init__( + self, + Property=None, + Feature=None, + DocObject=None, + GuiCommand=None, + PreferencesPage=None, + ): if Property is None: self.Property = [] else: @@ -1165,41 +1576,86 @@ class Content: self.PreferencesPage = [] else: self.PreferencesPage = PreferencesPage + def factory(*args_, **kwargs_): if Content.subclass: return Content.subclass(*args_, **kwargs_) else: return Content(*args_, **kwargs_) + factory = staticmethod(factory) - def getProperty(self): return self.Property - def setProperty(self, Property): self.Property = Property - def addProperty(self, value): self.Property.append(value) - def insertProperty(self, index, value): self.Property[index] = value - def getFeature(self): return self.Feature - def setFeature(self, Feature): self.Feature = Feature - def addFeature(self, value): self.Feature.append(value) - def insertFeature(self, index, value): self.Feature[index] = value - def getDocobject(self): return self.DocObject - def setDocobject(self, DocObject): self.DocObject = DocObject - def addDocobject(self, value): self.DocObject.append(value) - def insertDocobject(self, index, value): self.DocObject[index] = value - def getGuicommand(self): return self.GuiCommand - def setGuicommand(self, GuiCommand): self.GuiCommand = GuiCommand - def addGuicommand(self, value): self.GuiCommand.append(value) - def insertGuicommand(self, index, value): self.GuiCommand[index] = value - def getPreferencespage(self): return self.PreferencesPage - def setPreferencespage(self, PreferencesPage): self.PreferencesPage = PreferencesPage - def addPreferencespage(self, value): self.PreferencesPage.append(value) - def insertPreferencespage(self, index, value): self.PreferencesPage[index] = value - def export(self, outfile, level, name_='Content'): + + def getProperty(self): + return self.Property + + def setProperty(self, Property): + self.Property = Property + + def addProperty(self, value): + self.Property.append(value) + + def insertProperty(self, index, value): + self.Property[index] = value + + def getFeature(self): + return self.Feature + + def setFeature(self, Feature): + self.Feature = Feature + + def addFeature(self, value): + self.Feature.append(value) + + def insertFeature(self, index, value): + self.Feature[index] = value + + def getDocobject(self): + return self.DocObject + + def setDocobject(self, DocObject): + self.DocObject = DocObject + + def addDocobject(self, value): + self.DocObject.append(value) + + def insertDocobject(self, index, value): + self.DocObject[index] = value + + def getGuicommand(self): + return self.GuiCommand + + def setGuicommand(self, GuiCommand): + self.GuiCommand = GuiCommand + + def addGuicommand(self, value): + self.GuiCommand.append(value) + + def insertGuicommand(self, index, value): + self.GuiCommand[index] = value + + def getPreferencespage(self): + return self.PreferencesPage + + def setPreferencespage(self, PreferencesPage): + self.PreferencesPage = PreferencesPage + + def addPreferencespage(self, value): + self.PreferencesPage.append(value) + + def insertPreferencespage(self, index, value): + self.PreferencesPage[index] = value + + def export(self, outfile, level, name_="Content"): showIndent(outfile, level) - outfile.write('<%s>\n' % name_) + outfile.write("<%s>\n" % name_) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Content'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Content"): pass - def exportChildren(self, outfile, level, name_='Content'): + + def exportChildren(self, outfile, level, name_="Content"): for Property_ in self.getProperty(): Property_.export(outfile, level) for Feature_ in self.getFeature(): @@ -1208,113 +1664,117 @@ class Content: DocObject_.export(outfile, level) for GuiCommand_ in self.getGuicommand(): showIndent(outfile, level) - outfile.write('%s\n' % quote_xml(GuiCommand_)) + outfile.write("%s\n" % quote_xml(GuiCommand_)) for PreferencesPage_ in self.getPreferencespage(): showIndent(outfile, level) - outfile.write('%s\n' % quote_xml(PreferencesPage_)) - def exportLiteral(self, outfile, level, name_='Content'): + outfile.write("%s\n" % quote_xml(PreferencesPage_)) + + def exportLiteral(self, outfile, level, name_="Content"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('Property=[\n') + outfile.write("Property=[\n") level += 1 for Property in self.Property: showIndent(outfile, level) - outfile.write('Property(\n') + outfile.write("Property(\n") Property.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") showIndent(outfile, level) - outfile.write('Feature=[\n') + outfile.write("Feature=[\n") level += 1 for Feature in self.Feature: showIndent(outfile, level) - outfile.write('Feature(\n') + outfile.write("Feature(\n") Feature.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") showIndent(outfile, level) - outfile.write('DocObject=[\n') + outfile.write("DocObject=[\n") level += 1 for DocObject in self.DocObject: showIndent(outfile, level) - outfile.write('DocObject(\n') + outfile.write("DocObject(\n") DocObject.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") showIndent(outfile, level) - outfile.write('GuiCommand=[\n') + outfile.write("GuiCommand=[\n") level += 1 for GuiCommand in self.GuiCommand: showIndent(outfile, level) - outfile.write('%s,\n' % quote_python(GuiCommand)) + outfile.write("%s,\n" % quote_python(GuiCommand)) level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") showIndent(outfile, level) - outfile.write('PreferencesPage=[\n') + outfile.write("PreferencesPage=[\n") level += 1 for PreferencesPage in self.PreferencesPage: showIndent(outfile, level) - outfile.write('%s,\n' % quote_python(PreferencesPage)) + outfile.write("%s,\n" % quote_python(PreferencesPage)) level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Property': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Property": obj_ = Property.factory() obj_.build(child_) self.Property.append(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Feature': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Feature": obj_ = Feature.factory() obj_.build(child_) self.Feature.append(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'DocObject': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "DocObject": obj_ = DocObject.factory() obj_.build(child_) self.DocObject.append(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'GuiCommand': - GuiCommand_ = '' + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "GuiCommand": + GuiCommand_ = "" for text__content_ in child_.childNodes: GuiCommand_ += text__content_.nodeValue self.GuiCommand.append(GuiCommand_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'PreferencesPage': - PreferencesPage_ = '' + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "PreferencesPage": + PreferencesPage_ = "" for text__content_ in child_.childNodes: PreferencesPage_ += text__content_.nodeValue self.PreferencesPage.append(PreferencesPage_) + + # end class Content class Feature: subclass = None - def __init__(self, Name='', Documentation=None, Property=None, ViewProvider=None): + + def __init__(self, Name="", Documentation=None, Property=None, ViewProvider=None): self.Name = Name self.Documentation = Documentation if Property is None: @@ -1322,227 +1782,309 @@ class Feature: else: self.Property = Property self.ViewProvider = ViewProvider + def factory(*args_, **kwargs_): if Feature.subclass: return Feature.subclass(*args_, **kwargs_) else: return Feature(*args_, **kwargs_) + factory = staticmethod(factory) - def getDocumentation(self): return self.Documentation - def setDocumentation(self, Documentation): self.Documentation = Documentation - def getProperty(self): return self.Property - def setProperty(self, Property): self.Property = Property - def addProperty(self, value): self.Property.append(value) - def insertProperty(self, index, value): self.Property[index] = value - def getViewprovider(self): return self.ViewProvider - def setViewprovider(self, ViewProvider): self.ViewProvider = ViewProvider - def getName(self): return self.Name - def setName(self, Name): self.Name = Name - def export(self, outfile, level, name_='Feature'): + + def getDocumentation(self): + return self.Documentation + + def setDocumentation(self, Documentation): + self.Documentation = Documentation + + def getProperty(self): + return self.Property + + def setProperty(self, Property): + self.Property = Property + + def addProperty(self, value): + self.Property.append(value) + + def insertProperty(self, index, value): + self.Property[index] = value + + def getViewprovider(self): + return self.ViewProvider + + def setViewprovider(self, ViewProvider): + self.ViewProvider = ViewProvider + + def getName(self): + return self.Name + + def setName(self, Name): + self.Name = Name + + def export(self, outfile, level, name_="Feature"): showIndent(outfile, level) - outfile.write('<%s' % (name_, )) - self.exportAttributes(outfile, level, name_='Feature') - outfile.write('>\n') + outfile.write("<%s" % (name_,)) + self.exportAttributes(outfile, level, name_="Feature") + outfile.write(">\n") self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Feature'): - outfile.write(' Name="%s"' % (self.getName(), )) - def exportChildren(self, outfile, level, name_='Feature'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Feature"): + outfile.write(' Name="%s"' % (self.getName(),)) + + def exportChildren(self, outfile, level, name_="Feature"): if self.Documentation: self.Documentation.export(outfile, level) for Property_ in self.getProperty(): Property_.export(outfile, level) if self.ViewProvider: self.ViewProvider.export(outfile, level) - def exportLiteral(self, outfile, level, name_='Feature'): + + def exportLiteral(self, outfile, level, name_="Feature"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) + def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) - outfile.write('Documentation=Documentation(\n') + outfile.write("Documentation=Documentation(\n") self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") showIndent(outfile, level) - outfile.write('Property=[\n') + outfile.write("Property=[\n") level += 1 for Property in self.Property: showIndent(outfile, level) - outfile.write('Property(\n') + outfile.write("Property(\n") Property.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") if self.ViewProvider: showIndent(outfile, level) - outfile.write('ViewProvider=ViewProvider(\n') + outfile.write("ViewProvider=ViewProvider(\n") self.ViewProvider.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): - if attrs.get('Name'): - self.Name = attrs.get('Name').value + if attrs.get("Name"): + self.Name = attrs.get("Name").value + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Documentation': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Documentation": obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Property': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Property": obj_ = Property.factory() obj_.build(child_) self.Property.append(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'ViewProvider': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "ViewProvider": obj_ = ViewProvider.factory() obj_.build(child_) self.setViewprovider(obj_) + + # end class Feature class DocObject: subclass = None - def __init__(self, Name='', Documentation=None, Property=None): + + def __init__(self, Name="", Documentation=None, Property=None): self.Name = Name self.Documentation = Documentation if Property is None: self.Property = [] else: self.Property = Property + def factory(*args_, **kwargs_): if DocObject.subclass: return DocObject.subclass(*args_, **kwargs_) else: return DocObject(*args_, **kwargs_) + factory = staticmethod(factory) - def getDocumentation(self): return self.Documentation - def setDocumentation(self, Documentation): self.Documentation = Documentation - def getProperty(self): return self.Property - def setProperty(self, Property): self.Property = Property - def addProperty(self, value): self.Property.append(value) - def insertProperty(self, index, value): self.Property[index] = value - def getName(self): return self.Name - def setName(self, Name): self.Name = Name - def export(self, outfile, level, name_='DocObject'): + + def getDocumentation(self): + return self.Documentation + + def setDocumentation(self, Documentation): + self.Documentation = Documentation + + def getProperty(self): + return self.Property + + def setProperty(self, Property): + self.Property = Property + + def addProperty(self, value): + self.Property.append(value) + + def insertProperty(self, index, value): + self.Property[index] = value + + def getName(self): + return self.Name + + def setName(self, Name): + self.Name = Name + + def export(self, outfile, level, name_="DocObject"): showIndent(outfile, level) - outfile.write('<%s' % (name_, )) - self.exportAttributes(outfile, level, name_='DocObject') - outfile.write('>\n') + outfile.write("<%s" % (name_,)) + self.exportAttributes(outfile, level, name_="DocObject") + outfile.write(">\n") self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='DocObject'): - outfile.write(' Name="%s"' % (self.getName(), )) - def exportChildren(self, outfile, level, name_='DocObject'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="DocObject"): + outfile.write(' Name="%s"' % (self.getName(),)) + + def exportChildren(self, outfile, level, name_="DocObject"): if self.Documentation: self.Documentation.export(outfile, level) for Property_ in self.getProperty(): Property_.export(outfile, level) - def exportLiteral(self, outfile, level, name_='DocObject'): + + def exportLiteral(self, outfile, level, name_="DocObject"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) + def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) - outfile.write('Documentation=Documentation(\n') + outfile.write("Documentation=Documentation(\n") self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") showIndent(outfile, level) - outfile.write('Property=[\n') + outfile.write("Property=[\n") level += 1 for Property in self.Property: showIndent(outfile, level) - outfile.write('Property(\n') + outfile.write("Property(\n") Property.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): - if attrs.get('Name'): - self.Name = attrs.get('Name').value + if attrs.get("Name"): + self.Name = attrs.get("Name").value + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Documentation': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Documentation": obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Property': + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Property": obj_ = Property.factory() obj_.build(child_) self.Property.append(obj_) + + # end class DocObject class Property: subclass = None - def __init__(self, Name='', Type='', StartValue='', Documentation=None): + + def __init__(self, Name="", Type="", StartValue="", Documentation=None): self.Name = Name self.Type = Type self.StartValue = StartValue self.Documentation = Documentation + def factory(*args_, **kwargs_): if Property.subclass: return Property.subclass(*args_, **kwargs_) else: return Property(*args_, **kwargs_) + factory = staticmethod(factory) - def getDocumentation(self): return self.Documentation - def setDocumentation(self, Documentation): self.Documentation = Documentation - def getName(self): return self.Name - def setName(self, Name): self.Name = Name - def getType(self): return self.Type - def setType(self, Type): self.Type = Type - def getStartvalue(self): return self.StartValue - def setStartvalue(self, StartValue): self.StartValue = StartValue - def export(self, outfile, level, name_='Property'): + + def getDocumentation(self): + return self.Documentation + + def setDocumentation(self, Documentation): + self.Documentation = Documentation + + def getName(self): + return self.Name + + def setName(self, Name): + self.Name = Name + + def getType(self): + return self.Type + + def setType(self, Type): + self.Type = Type + + def getStartvalue(self): + return self.StartValue + + def setStartvalue(self, StartValue): + self.StartValue = StartValue + + def export(self, outfile, level, name_="Property"): showIndent(outfile, level) - outfile.write('<%s' % (name_, )) - self.exportAttributes(outfile, level, name_='Property') - outfile.write('>\n') + outfile.write("<%s" % (name_,)) + self.exportAttributes(outfile, level, name_="Property") + outfile.write(">\n") self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Property'): - outfile.write(' Name="%s"' % (self.getName(), )) - outfile.write(' Type="%s"' % (self.getType(), )) + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Property"): + outfile.write(' Name="%s"' % (self.getName(),)) + outfile.write(' Type="%s"' % (self.getType(),)) if self.getStartvalue() is not None: - outfile.write(' StartValue="%s"' % (self.getStartvalue(), )) - def exportChildren(self, outfile, level, name_='Property'): + outfile.write(' StartValue="%s"' % (self.getStartvalue(),)) + + def exportChildren(self, outfile, level, name_="Property"): if self.Documentation: self.Documentation.export(outfile, level) - def exportLiteral(self, outfile, level, name_='Property'): + + def exportLiteral(self, outfile, level, name_="Property"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) @@ -1550,154 +2092,206 @@ class Property: outfile.write('Type = "%s",\n' % (self.getType(),)) showIndent(outfile, level) outfile.write('StartValue = "%s",\n' % (self.getStartvalue(),)) + def exportLiteralChildren(self, outfile, level, name_): if self.Documentation: showIndent(outfile, level) - outfile.write('Documentation=Documentation(\n') + outfile.write("Documentation=Documentation(\n") self.Documentation.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): - if attrs.get('Name'): - self.Name = attrs.get('Name').value - if attrs.get('Type'): - self.Type = attrs.get('Type').value - if attrs.get('StartValue'): - self.StartValue = attrs.get('StartValue').value + if attrs.get("Name"): + self.Name = attrs.get("Name").value + if attrs.get("Type"): + self.Type = attrs.get("Type").value + if attrs.get("StartValue"): + self.StartValue = attrs.get("StartValue").value + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Documentation': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Documentation": obj_ = Documentation.factory() obj_.build(child_) self.setDocumentation(obj_) + + # end class Property class Documentation: subclass = None - def __init__(self, Author=None, DeveloperDocu='', UserDocu=''): + + def __init__(self, Author=None, DeveloperDocu="", UserDocu=""): self.Author = Author self.DeveloperDocu = DeveloperDocu self.UserDocu = UserDocu + def factory(*args_, **kwargs_): if Documentation.subclass: return Documentation.subclass(*args_, **kwargs_) else: return Documentation(*args_, **kwargs_) + factory = staticmethod(factory) - def getAuthor(self): return self.Author - def setAuthor(self, Author): self.Author = Author - def getDeveloperdocu(self): return self.DeveloperDocu - def setDeveloperdocu(self, DeveloperDocu): self.DeveloperDocu = DeveloperDocu - def getUserdocu(self): return self.UserDocu - def setUserdocu(self, UserDocu): self.UserDocu = UserDocu - def export(self, outfile, level, name_='Documentation'): + + def getAuthor(self): + return self.Author + + def setAuthor(self, Author): + self.Author = Author + + def getDeveloperdocu(self): + return self.DeveloperDocu + + def setDeveloperdocu(self, DeveloperDocu): + self.DeveloperDocu = DeveloperDocu + + def getUserdocu(self): + return self.UserDocu + + def setUserdocu(self, UserDocu): + self.UserDocu = UserDocu + + def export(self, outfile, level, name_="Documentation"): showIndent(outfile, level) - outfile.write('<%s>\n' % name_) + outfile.write("<%s>\n" % name_) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Documentation'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Documentation"): pass - def exportChildren(self, outfile, level, name_='Documentation'): + + def exportChildren(self, outfile, level, name_="Documentation"): if self.Author: self.Author.export(outfile, level) showIndent(outfile, level) - outfile.write('%s\n' % quote_xml(self.getDeveloperdocu())) + outfile.write("%s\n" % quote_xml(self.getDeveloperdocu())) showIndent(outfile, level) - outfile.write('%s\n' % quote_xml(self.getUserdocu())) - def exportLiteral(self, outfile, level, name_='Documentation'): + outfile.write("%s\n" % quote_xml(self.getUserdocu())) + + def exportLiteral(self, outfile, level, name_="Documentation"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): if self.Author: showIndent(outfile, level) - outfile.write('Author=Author(\n') + outfile.write("Author=Author(\n") self.Author.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") showIndent(outfile, level) - outfile.write('DeveloperDocu=%s,\n' % quote_python(self.getDeveloperdocu())) + outfile.write("DeveloperDocu=%s,\n" % quote_python(self.getDeveloperdocu())) showIndent(outfile, level) - outfile.write('UserDocu=%s,\n' % quote_python(self.getUserdocu())) + outfile.write("UserDocu=%s,\n" % quote_python(self.getUserdocu())) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Author': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Author": obj_ = Author.factory() obj_.build(child_) self.setAuthor(obj_) - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'DeveloperDocu': - DeveloperDocu_ = '' + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "DeveloperDocu": + DeveloperDocu_ = "" for text__content_ in child_.childNodes: DeveloperDocu_ += text__content_.nodeValue self.DeveloperDocu = DeveloperDocu_ - elif child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'UserDocu': - UserDocu_ = '' + elif child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "UserDocu": + UserDocu_ = "" for text__content_ in child_.childNodes: UserDocu_ += text__content_.nodeValue self.UserDocu = UserDocu_ + + # end class Documentation class Author: subclass = None - def __init__(self, Name='', EMail='', Licence='', valueOf_=''): + + def __init__(self, Name="", EMail="", Licence="", valueOf_=""): self.Name = Name self.EMail = EMail self.Licence = Licence self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if Author.subclass: return Author.subclass(*args_, **kwargs_) else: return Author(*args_, **kwargs_) + factory = staticmethod(factory) - def getName(self): return self.Name - def setName(self, Name): self.Name = Name - def getEmail(self): return self.EMail - def setEmail(self, EMail): self.EMail = EMail - def getLicence(self): return self.Licence - def setLicence(self, Licence): self.Licence = Licence - def getValueOf_(self): return self.valueOf_ - def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, name_='Author'): + + def getName(self): + return self.Name + + def setName(self, Name): + self.Name = Name + + def getEmail(self): + return self.EMail + + def setEmail(self, EMail): + self.EMail = EMail + + def getLicence(self): + return self.Licence + + def setLicence(self, Licence): + self.Licence = Licence + + def getValueOf_(self): + return self.valueOf_ + + def setValueOf_(self, valueOf_): + self.valueOf_ = valueOf_ + + def export(self, outfile, level, name_="Author"): showIndent(outfile, level) - outfile.write('<%s' % (name_, )) - self.exportAttributes(outfile, level, name_='Author') - outfile.write('>\n') + outfile.write("<%s" % (name_,)) + self.exportAttributes(outfile, level, name_="Author") + outfile.write(">\n") self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Author'): - outfile.write(' Name="%s"' % (self.getName(), )) - outfile.write(' EMail="%s"' % (self.getEmail(), )) + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Author"): + outfile.write(' Name="%s"' % (self.getName(),)) + outfile.write(' EMail="%s"' % (self.getEmail(),)) if self.getLicence() is not None: - outfile.write(' Licence="%s"' % (self.getLicence(), )) - def exportChildren(self, outfile, level, name_='Author'): + outfile.write(' Licence="%s"' % (self.getLicence(),)) + + def exportChildren(self, outfile, level, name_="Author"): outfile.write(self.valueOf_) - def exportLiteral(self, outfile, level, name_='Author'): + + def exportLiteral(self, outfile, level, name_="Author"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) @@ -1705,163 +2299,218 @@ class Author: outfile.write('EMail = "%s",\n' % (self.getEmail(),)) showIndent(outfile, level) outfile.write('Licence = "%s",\n' % (self.getLicence(),)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): - if attrs.get('Name'): - self.Name = attrs.get('Name').value - if attrs.get('EMail'): - self.EMail = attrs.get('EMail').value - if attrs.get('Licence'): - self.Licence = attrs.get('Licence').value + if attrs.get("Name"): + self.Name = attrs.get("Name").value + if attrs.get("EMail"): + self.EMail = attrs.get("EMail").value + if attrs.get("Licence"): + self.Licence = attrs.get("Licence").value + def buildChildren(self, child_, nodeName_): - self.valueOf_ = '' + self.valueOf_ = "" for child in child_.childNodes: if child.nodeType == Node.TEXT_NODE: self.valueOf_ += child.nodeValue + + # end class Author class ViewProvider: subclass = None + def __init__(self, Property=None): if Property is None: self.Property = [] else: self.Property = Property + def factory(*args_, **kwargs_): if ViewProvider.subclass: return ViewProvider.subclass(*args_, **kwargs_) else: return ViewProvider(*args_, **kwargs_) + factory = staticmethod(factory) - def getProperty(self): return self.Property - def setProperty(self, Property): self.Property = Property - def addProperty(self, value): self.Property.append(value) - def insertProperty(self, index, value): self.Property[index] = value - def export(self, outfile, level, name_='ViewProvider'): + + def getProperty(self): + return self.Property + + def setProperty(self, Property): + self.Property = Property + + def addProperty(self, value): + self.Property.append(value) + + def insertProperty(self, index, value): + self.Property[index] = value + + def export(self, outfile, level, name_="ViewProvider"): showIndent(outfile, level) - outfile.write('<%s>\n' % name_) + outfile.write("<%s>\n" % name_) self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='ViewProvider'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="ViewProvider"): pass - def exportChildren(self, outfile, level, name_='ViewProvider'): + + def exportChildren(self, outfile, level, name_="ViewProvider"): for Property_ in self.getProperty(): Property_.export(outfile, level) - def exportLiteral(self, outfile, level, name_='ViewProvider'): + + def exportLiteral(self, outfile, level, name_="ViewProvider"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): pass + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) - outfile.write('Property=[\n') + outfile.write("Property=[\n") level += 1 for Property in self.Property: showIndent(outfile, level) - outfile.write('Property(\n') + outfile.write("Property(\n") Property.exportLiteral(outfile, level) showIndent(outfile, level) - outfile.write('),\n') + outfile.write("),\n") level -= 1 showIndent(outfile, level) - outfile.write('],\n') + outfile.write("],\n") + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): pass + def buildChildren(self, child_, nodeName_): - if child_.nodeType == Node.ELEMENT_NODE and \ - nodeName_ == 'Property': + if child_.nodeType == Node.ELEMENT_NODE and nodeName_ == "Property": obj_ = Property.factory() obj_.build(child_) self.Property.append(obj_) + + # end class ViewProvider class Parameter: subclass = None - def __init__(self, Name='', Type='', valueOf_=''): + + def __init__(self, Name="", Type="", valueOf_=""): self.Name = Name self.Type = Type self.valueOf_ = valueOf_ + def factory(*args_, **kwargs_): if Parameter.subclass: return Parameter.subclass(*args_, **kwargs_) else: return Parameter(*args_, **kwargs_) + factory = staticmethod(factory) - def getName(self): return self.Name - def setName(self, Name): self.Name = Name - def getType(self): return self.Type - def setType(self, Type): self.Type = Type - def getValueOf_(self): return self.valueOf_ - def setValueOf_(self, valueOf_): self.valueOf_ = valueOf_ - def export(self, outfile, level, name_='Parameter'): + + def getName(self): + return self.Name + + def setName(self, Name): + self.Name = Name + + def getType(self): + return self.Type + + def setType(self, Type): + self.Type = Type + + def getValueOf_(self): + return self.valueOf_ + + def setValueOf_(self, valueOf_): + self.valueOf_ = valueOf_ + + def export(self, outfile, level, name_="Parameter"): showIndent(outfile, level) - outfile.write('<%s' % (name_, )) - self.exportAttributes(outfile, level, name_='Parameter') - outfile.write('>\n') + outfile.write("<%s" % (name_,)) + self.exportAttributes(outfile, level, name_="Parameter") + outfile.write(">\n") self.exportChildren(outfile, level + 1, name_) showIndent(outfile, level) - outfile.write('\n' % name_) - def exportAttributes(self, outfile, level, name_='Parameter'): - outfile.write(' Name="%s"' % (self.getName(), )) - outfile.write(' Type="%s"' % (self.getType(), )) - def exportChildren(self, outfile, level, name_='Parameter'): + outfile.write("\n" % name_) + + def exportAttributes(self, outfile, level, name_="Parameter"): + outfile.write(' Name="%s"' % (self.getName(),)) + outfile.write(' Type="%s"' % (self.getType(),)) + + def exportChildren(self, outfile, level, name_="Parameter"): outfile.write(self.valueOf_) - def exportLiteral(self, outfile, level, name_='Parameter'): + + def exportLiteral(self, outfile, level, name_="Parameter"): level += 1 self.exportLiteralAttributes(outfile, level, name_) self.exportLiteralChildren(outfile, level, name_) + def exportLiteralAttributes(self, outfile, level, name_): showIndent(outfile, level) outfile.write('Name = "%s",\n' % (self.getName(),)) showIndent(outfile, level) outfile.write('Type = "%s",\n' % (self.getType(),)) + def exportLiteralChildren(self, outfile, level, name_): showIndent(outfile, level) outfile.write('valueOf_ = "%s",\n' % (self.valueOf_,)) + def build(self, node_): attrs = node_.attributes self.buildAttributes(attrs) for child_ in node_.childNodes: - nodeName_ = child_.nodeName.split(':')[-1] + nodeName_ = child_.nodeName.split(":")[-1] self.buildChildren(child_, nodeName_) + def buildAttributes(self, attrs): - if attrs.get('Name'): - self.Name = attrs.get('Name').value - if attrs.get('Type'): - self.Type = attrs.get('Type').value + if attrs.get("Name"): + self.Name = attrs.get("Name").value + if attrs.get("Type"): + self.Type = attrs.get("Type").value + def buildChildren(self, child_, nodeName_): - self.valueOf_ = '' + self.valueOf_ = "" for child in child_.childNodes: if child.nodeType == Node.TEXT_NODE: self.valueOf_ += child.nodeValue + + # end class Parameter from xml.sax import handler, make_parser + class SaxStackElement: - def __init__(self, name='', obj=None): + def __init__(self, name="", obj=None): self.name = name self.obj = obj - self.content = '' + self.content = "" + # # SAX handler @@ -1878,358 +2527,406 @@ class SaxGeneratemodelHandler(handler.ContentHandler): self.locator = locator def showError(self, msg): - print('*** (showError):', msg) + print("*** (showError):", msg) sys.exit(-1) def startElement(self, name, attrs): done = 0 - if name == 'GenerateModel': + if name == "GenerateModel": obj = GenerateModel.factory() - stackObj = SaxStackElement('GenerateModel', obj) + stackObj = SaxStackElement("GenerateModel", obj) self.stack.append(stackObj) done = 1 - elif name == 'Module': + elif name == "Module": obj = Module.factory() - stackObj = SaxStackElement('Module', obj) + stackObj = SaxStackElement("Module", obj) self.stack.append(stackObj) done = 1 - elif name == 'PythonExport': + elif name == "PythonExport": obj = PythonExport.factory() - val = attrs.get('Name', None) + val = attrs.get("Name", None) if val is not None: obj.setName(val) - val = attrs.get('PythonName', None) + val = attrs.get("PythonName", None) if val is not None: obj.setPythonname(val) - val = attrs.get('Include', None) + val = attrs.get("Include", None) if val is not None: obj.setInclude(val) - val = attrs.get('Father', None) + val = attrs.get("Father", None) if val is not None: obj.setFather(val) - val = attrs.get('Twin', None) + val = attrs.get("Twin", None) if val is not None: obj.setTwin(val) - val = attrs.get('Namespace', None) + val = attrs.get("Namespace", None) if val is not None: obj.setNamespace(val) - val = attrs.get('FatherInclude', None) + val = attrs.get("FatherInclude", None) if val is not None: obj.setFatherinclude(val) - val = attrs.get('FatherNamespace', None) + val = attrs.get("FatherNamespace", None) if val is not None: obj.setFathernamespace(val) - val = attrs.get('Constructor', None) + val = attrs.get("Constructor", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setConstructor(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setConstructor(0) else: - self.reportError('"Constructor" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('NumberProtocol', None) + self.reportError( + '"Constructor" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("NumberProtocol", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setNumberprotocol(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setNumberprotocol(0) else: - self.reportError('"NumberProtocol" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('RichCompare', None) + self.reportError( + '"NumberProtocol" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("RichCompare", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setRichcompare(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setRichcompare(0) else: - self.reportError('"RichCompare" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('TwinPointer', None) + self.reportError( + '"RichCompare" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("TwinPointer", None) if val is not None: obj.setTwinpointer(val) - val = attrs.get('Delete', None) + val = attrs.get("Delete", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setDelete(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setDelete(0) else: - self.reportError('"Delete" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('Reference', None) + self.reportError( + '"Delete" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("Reference", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setReference(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setReference(0) else: - self.reportError('"Reference" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('Initialization', None) + self.reportError( + '"Reference" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("Initialization", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setInitialization(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setInitialization(0) else: - self.reportError('"Initialization" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('DisableNotify', None) + self.reportError( + '"Initialization" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("DisableNotify", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setDisablenotify(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setDisablenotify(0) else: - self.reportError('"DisableNotify" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('DescriptorGetter', None) + self.reportError( + '"DisableNotify" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("DescriptorGetter", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setDescriptorgetter(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setDescriptorgetter(0) else: - self.reportError('"DescriptorGetter" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('DescriptorSetter', None) + self.reportError( + '"DescriptorGetter" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("DescriptorSetter", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setDescriptorsetter(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setDescriptorsetter(0) else: - self.reportError('"DescriptorSetter" attribute must be boolean ("true", "1", "false", "0")') - stackObj = SaxStackElement('PythonExport', obj) + self.reportError( + '"DescriptorSetter" attribute must be boolean ("true", "1", "false", "0")' + ) + stackObj = SaxStackElement("PythonExport", obj) self.stack.append(stackObj) done = 1 - elif name == 'Documentation': + elif name == "Documentation": obj = Documentation.factory() - stackObj = SaxStackElement('Documentation', obj) + stackObj = SaxStackElement("Documentation", obj) self.stack.append(stackObj) done = 1 - elif name == 'Methode': + elif name == "Methode": obj = Methode.factory() - val = attrs.get('Name', None) + val = attrs.get("Name", None) if val is not None: obj.setName(val) - val = attrs.get('Const', None) + val = attrs.get("Const", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setConst(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setConst(0) else: - self.reportError('"Const" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('Keyword', None) + self.reportError( + '"Const" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("Keyword", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setKeyword(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setKeyword(0) else: - self.reportError('"Keyword" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('Class', None) + self.reportError( + '"Keyword" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("Class", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setClass(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setClass(0) else: - self.reportError('"Class" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('Static', None) + self.reportError( + '"Class" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("Static", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setStatic(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setStatic(0) else: - self.reportError('"Static" attribute must be boolean ("true", "1", "false", "0")') - stackObj = SaxStackElement('Methode', obj) + self.reportError( + '"Static" attribute must be boolean ("true", "1", "false", "0")' + ) + stackObj = SaxStackElement("Methode", obj) self.stack.append(stackObj) done = 1 - elif name == 'Parameter': + elif name == "Parameter": obj = Parameter.factory() - val = attrs.get('Name', None) + val = attrs.get("Name", None) if val is not None: obj.setName(val) - val = attrs.get('Type', None) + val = attrs.get("Type", None) if val is not None: obj.setType(val) - stackObj = SaxStackElement('Parameter', obj) + stackObj = SaxStackElement("Parameter", obj) self.stack.append(stackObj) done = 1 - elif name == 'Attribute': + elif name == "Attribute": obj = Attribute.factory() - val = attrs.get('Name', None) + val = attrs.get("Name", None) if val is not None: obj.setName(val) - val = attrs.get('ReadOnly', None) + val = attrs.get("ReadOnly", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setReadonly(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setReadonly(0) else: - self.reportError('"ReadOnly" attribute must be boolean ("true", "1", "false", "0")') - stackObj = SaxStackElement('Attribute', obj) + self.reportError( + '"ReadOnly" attribute must be boolean ("true", "1", "false", "0")' + ) + stackObj = SaxStackElement("Attribute", obj) self.stack.append(stackObj) done = 1 - elif name == 'Sequence': + elif name == "Sequence": obj = Sequence.factory() - val = attrs.get('sq_length', None) + val = attrs.get("sq_length", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setSq_length(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setSq_length(0) else: - self.reportError('"sq_length" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('sq_concat', None) + self.reportError( + '"sq_length" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("sq_concat", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setSq_concat(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setSq_concat(0) else: - self.reportError('"sq_concat" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('sq_repeat', None) + self.reportError( + '"sq_concat" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("sq_repeat", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setSq_repeat(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setSq_repeat(0) else: - self.reportError('"sq_repeat" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('sq_item', None) + self.reportError( + '"sq_repeat" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("sq_item", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setSq_item(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setSq_item(0) else: - self.reportError('"sq_item" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('mp_subscript', None) + self.reportError( + '"sq_item" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("mp_subscript", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setMp_subscript(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setMp_subscript(0) else: - self.reportError('"mp_subscript" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('sq_ass_item', None) + self.reportError( + '"mp_subscript" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("sq_ass_item", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setSq_ass_item(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setSq_ass_item(0) else: - self.reportError('"sq_ass_item" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('mp_ass_subscript', None) + self.reportError( + '"sq_ass_item" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("mp_ass_subscript", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setMp_ass_subscript(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setMp_ass_subscript(0) else: - self.reportError('"mp_ass_subscript" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('sq_contains', None) + self.reportError( + '"mp_ass_subscript" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("sq_contains", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setSq_contains(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setSq_contains(0) else: - self.reportError('"sq_contains" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('sq_inplace_concat', None) + self.reportError( + '"sq_contains" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("sq_inplace_concat", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setSq_inplace_concat(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setSq_inplace_concat(0) else: - self.reportError('"sq_inplace_concat" attribute must be boolean ("true", "1", "false", "0")') - val = attrs.get('sq_inplace_repeat', None) + self.reportError( + '"sq_inplace_concat" attribute must be boolean ("true", "1", "false", "0")' + ) + val = attrs.get("sq_inplace_repeat", None) if val is not None: - if val in ('true', '1'): + if val in ("true", "1"): obj.setSq_inplace_repeat(1) - elif val in ('false', '0'): + elif val in ("false", "0"): obj.setSq_inplace_repeat(0) else: - self.reportError('"sq_inplace_repeat" attribute must be boolean ("true", "1", "false", "0")') - stackObj = SaxStackElement('Sequence', obj) + self.reportError( + '"sq_inplace_repeat" attribute must be boolean ("true", "1", "false", "0")' + ) + stackObj = SaxStackElement("Sequence", obj) self.stack.append(stackObj) done = 1 - elif name == 'CustomAttributes': - stackObj = SaxStackElement('CustomAttributes', None) + elif name == "CustomAttributes": + stackObj = SaxStackElement("CustomAttributes", None) self.stack.append(stackObj) done = 1 - elif name == 'ClassDeclarations': - stackObj = SaxStackElement('ClassDeclarations', None) + elif name == "ClassDeclarations": + stackObj = SaxStackElement("ClassDeclarations", None) self.stack.append(stackObj) done = 1 - elif name == 'ForwardDeclarations': - stackObj = SaxStackElement('ForwardDeclarations', None) + elif name == "ForwardDeclarations": + stackObj = SaxStackElement("ForwardDeclarations", None) self.stack.append(stackObj) done = 1 - elif name == 'Dependencies': + elif name == "Dependencies": obj = Dependencies.factory() - stackObj = SaxStackElement('Dependencies', obj) + stackObj = SaxStackElement("Dependencies", obj) self.stack.append(stackObj) done = 1 - elif name == 'Content': + elif name == "Content": obj = Content.factory() - stackObj = SaxStackElement('Content', obj) + stackObj = SaxStackElement("Content", obj) self.stack.append(stackObj) done = 1 - elif name == 'Property': + elif name == "Property": obj = Property.factory() - stackObj = SaxStackElement('Property', obj) + stackObj = SaxStackElement("Property", obj) self.stack.append(stackObj) done = 1 - elif name == 'Feature': + elif name == "Feature": obj = Feature.factory() - val = attrs.get('Name', None) + val = attrs.get("Name", None) if val is not None: obj.setName(val) - stackObj = SaxStackElement('Feature', obj) + stackObj = SaxStackElement("Feature", obj) self.stack.append(stackObj) done = 1 - elif name == 'ViewProvider': + elif name == "ViewProvider": obj = ViewProvider.factory() - stackObj = SaxStackElement('ViewProvider', obj) + stackObj = SaxStackElement("ViewProvider", obj) self.stack.append(stackObj) done = 1 - elif name == 'DocObject': + elif name == "DocObject": obj = DocObject.factory() - val = attrs.get('Name', None) + val = attrs.get("Name", None) if val is not None: obj.setName(val) - stackObj = SaxStackElement('DocObject', obj) + stackObj = SaxStackElement("DocObject", obj) self.stack.append(stackObj) done = 1 - elif name == 'GuiCommand': - stackObj = SaxStackElement('GuiCommand', None) + elif name == "GuiCommand": + stackObj = SaxStackElement("GuiCommand", None) self.stack.append(stackObj) done = 1 - elif name == 'PreferencesPage': - stackObj = SaxStackElement('PreferencesPage', None) + elif name == "PreferencesPage": + stackObj = SaxStackElement("PreferencesPage", None) self.stack.append(stackObj) done = 1 - elif name == 'Author': + elif name == "Author": obj = Author.factory() - val = attrs.get('Name', None) + val = attrs.get("Name", None) if val is not None: obj.setName(val) - val = attrs.get('EMail', None) + val = attrs.get("EMail", None) if val is not None: obj.setEmail(val) - val = attrs.get('Licence', None) + val = attrs.get("Licence", None) if val is not None: obj.setLicence(val) - stackObj = SaxStackElement('Author', obj) + stackObj = SaxStackElement("Author", obj) self.stack.append(stackObj) done = 1 - elif name == 'DeveloperDocu': - stackObj = SaxStackElement('DeveloperDocu', None) + elif name == "DeveloperDocu": + stackObj = SaxStackElement("DeveloperDocu", None) self.stack.append(stackObj) done = 1 - elif name == 'UserDocu': - stackObj = SaxStackElement('UserDocu', None) + elif name == "UserDocu": + stackObj = SaxStackElement("UserDocu", None) self.stack.append(stackObj) done = 1 if not done: @@ -2237,118 +2934,118 @@ class SaxGeneratemodelHandler(handler.ContentHandler): def endElement(self, name): done = 0 - if name == 'GenerateModel': + if name == "GenerateModel": if len(self.stack) == 1: self.root = self.stack[-1].obj self.stack.pop() done = 1 - elif name == 'Module': + elif name == "Module": if len(self.stack) >= 2: self.stack[-2].obj.addModule(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'PythonExport': + elif name == "PythonExport": if len(self.stack) >= 2: self.stack[-2].obj.addPythonexport(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'Documentation': + elif name == "Documentation": if len(self.stack) >= 2: self.stack[-2].obj.setDocumentation(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'Methode': + elif name == "Methode": if len(self.stack) >= 2: self.stack[-2].obj.addMethode(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'Parameter': + elif name == "Parameter": if len(self.stack) >= 2: self.stack[-2].obj.addParameter(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'Attribute': + elif name == "Attribute": if len(self.stack) >= 2: self.stack[-2].obj.addAttribute(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'Sequence': + elif name == "Sequence": if len(self.stack) >= 2: self.stack[-2].obj.setSequence(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'CustomAttributes': + elif name == "CustomAttributes": if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.setCustomattributes(content) self.stack.pop() done = 1 - elif name == 'ClassDeclarations': + elif name == "ClassDeclarations": if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.setClassdeclarations(content) self.stack.pop() done = 1 - elif name == 'ForwardDeclarations': + elif name == "ForwardDeclarations": if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.setForwarddeclarations(content) self.stack.pop() done = 1 - elif name == 'Dependencies': + elif name == "Dependencies": if len(self.stack) >= 2: self.stack[-2].obj.setDependencies(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'Content': + elif name == "Content": if len(self.stack) >= 2: self.stack[-2].obj.setContent(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'Property': + elif name == "Property": if len(self.stack) >= 2: self.stack[-2].obj.addProperty(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'Feature': + elif name == "Feature": if len(self.stack) >= 2: self.stack[-2].obj.addFeature(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'ViewProvider': + elif name == "ViewProvider": if len(self.stack) >= 2: self.stack[-2].obj.setViewprovider(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'DocObject': + elif name == "DocObject": if len(self.stack) >= 2: self.stack[-2].obj.addDocobject(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'GuiCommand': + elif name == "GuiCommand": if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.addGuicommand(content) self.stack.pop() done = 1 - elif name == 'PreferencesPage': + elif name == "PreferencesPage": if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.addPreferencespage(content) self.stack.pop() done = 1 - elif name == 'Author': + elif name == "Author": if len(self.stack) >= 2: self.stack[-2].obj.setAuthor(self.stack[-1].obj) self.stack.pop() done = 1 - elif name == 'DeveloperDocu': + elif name == "DeveloperDocu": if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.setDeveloperdocu(content) self.stack.pop() done = 1 - elif name == 'UserDocu': + elif name == "UserDocu": if len(self.stack) >= 2: content = self.stack[-1].content self.stack[-2].obj.setUserdocu(content) @@ -2363,13 +3060,19 @@ class SaxGeneratemodelHandler(handler.ContentHandler): def reportError(self, mesg): locator = self.locator - sys.stderr.write('Doc: %s Line: %d Column: %d\n' % \ - (locator.getSystemId(), locator.getLineNumber(), - locator.getColumnNumber() + 1)) + sys.stderr.write( + "Doc: %s Line: %d Column: %d\n" + % ( + locator.getSystemId(), + locator.getLineNumber(), + locator.getColumnNumber() + 1, + ) + ) sys.stderr.write(mesg) - sys.stderr.write('\n') + sys.stderr.write("\n") sys.exit(-1) - #raise RuntimeError + # raise RuntimeError + USAGE_TEXT = """ Usage: python .py [ -s ] @@ -2377,6 +3080,7 @@ Options: -s Use the SAX parser, not the minidom parser. """ + def usage(): print(USAGE_TEXT) sys.exit(-1) @@ -2388,15 +3092,17 @@ def usage(): class SaxSelectorHandler(handler.ContentHandler): def __init__(self): self.topElementName = None + def getTopElementName(self): return self.topElementName + def startElement(self, name, attrs): self.topElementName = name raise StopIteration def parseSelect(inFileName): - infile = open(inFileName, 'r') + infile = open(inFileName, "r") topElementName = None parser = make_parser() documentHandler = SaxSelectorHandler() @@ -2407,10 +3113,10 @@ def parseSelect(inFileName): except StopIteration: topElementName = documentHandler.getTopElementName() if topElementName is None: - raise RuntimeError('no top level element') - topElementName = topElementName.replace('-', '_').replace(':', '_') + raise RuntimeError("no top level element") + topElementName = topElementName.replace("-", "_").replace(":", "_") if topElementName not in globals(): - raise RuntimeError('no class for top element: %s' % topElementName) + raise RuntimeError("no class for top element: %s" % topElementName) topElement = globals()[topElementName] infile.seek(0) doc = minidom.parse(infile) @@ -2430,7 +3136,7 @@ def saxParse(inFileName): parser = make_parser() documentHandler = SaxGeneratemodelHandler() parser.setDocumentHandler(documentHandler) - parser.parse('file:%s' % inFileName) + parser.parse("file:%s" % inFileName) root = documentHandler.getRoot() sys.stdout.write('\n') root.export(sys.stdout, 0) @@ -2444,8 +3150,8 @@ def saxParseString(inString): parser.feed(inString) parser.close() rootObj = documentHandler.getRoot() - #sys.stdout.write('\n') - #rootObj.export(sys.stdout, 0) + # sys.stdout.write('\n') + # rootObj.export(sys.stdout, 0) return rootObj @@ -2480,16 +3186,16 @@ def parseLiteral(inFileName): rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None - sys.stdout.write('from generateModel_Module import *\n\n') - sys.stdout.write('rootObj = GenerateModel(\n') + sys.stdout.write("from generateModel_Module import *\n\n") + sys.stdout.write("rootObj = GenerateModel(\n") rootObj.exportLiteral(sys.stdout, 0, name_="GenerateModel") - sys.stdout.write(')\n') + sys.stdout.write(")\n") return rootObj def main(): args = sys.argv[1:] - if len(args) == 2 and args[0] == '-s': + if len(args) == 2 and args[0] == "-s": saxParse(args[1]) elif len(args) == 1: parse(args[0]) @@ -2497,8 +3203,7 @@ def main(): usage() -if __name__ == '__main__': +if __name__ == "__main__": main() - #import pdb - #pdb.run('main()') - + # import pdb + # pdb.run('main()') diff --git a/src/Tools/generateBase/generateTools.py b/src/Tools/generateBase/generateTools.py index 2f4b7b5433..a7fc45d57f 100644 --- a/src/Tools/generateBase/generateTools.py +++ b/src/Tools/generateBase/generateTools.py @@ -1,25 +1,27 @@ #! python # -*- coding: utf-8 -*- -# (c) 2007 Jürgen Riegel +# (c) 2007 Jürgen Riegel import os -def ensureDir(path,mode=0o777): - try: - os.makedirs(path,mode) +def ensureDir(path, mode=0o777): + try: + os.makedirs(path, mode) except OSError as err: # https://docs.python.org/3/tutorial/errors.html # raise an error unless it's about an already existing directory print("Dir Exist") - #if errno != 17 or not os.path.isdir(path): - # raise - + # if errno != 17 or not os.path.isdir(path): + # raise + + def convertMultilineString(str): - str = str.replace('\n','\\n') - str = str.replace('"','\\"') - return str - + str = str.replace("\n", "\\n") + str = str.replace('"', '\\"') + return str + + "Yet Another Python Templating Utility, Version 1.2" import sys @@ -27,109 +29,141 @@ import sys # utility stuff to avoid tests in the mainline code class _nevermatch: "Polymorphic with a regex that never matches" + def match(self, line): return None -_never = _nevermatch() # one reusable instance of it suffices + + +_never = _nevermatch() # one reusable instance of it suffices + + def identity(string, why): "A do-nothing-special-to-the-input, just-return-it function" return string + + def nohandle(string): "A do-nothing handler that just re-raises the exception" raise + # and now the real thing class copier: "Smart-copier (YAPTU) class" + def copyblock(self, i=0, last=None): "Main copy method: process lines [i,last) of block" + def repl(match, self=self): "return the eval of a found expression, for replacement" # uncomment for debug: print ('!!! replacing',match.group(1)) - expr = self.preproc(match.group(1), 'eval') - try: return str(eval(expr, self.globals, self.locals)) - except Exception: return str(self.handle(expr)) - block = self.locals['_bl'] - if last is None: last = len(block) - while i Executing: {"+stat+"}") exec(stat, self.globals, self.locals) - i=j+1 - else: # normal line, just copy with substitution + i = j + 1 + else: # normal line, just copy with substitution try: self.ouf.write(self.regex.sub(repl, line).encode("utf8")) except TypeError: self.ouf.write(self.regex.sub(repl, line)) - i=i+1 - def __init__(self, regex=_never, dict=None, - restat=_never, restend=_never, recont=_never, - preproc=identity, handle=nohandle, ouf=sys.stdout): + i = i + 1 + + def __init__( + self, + regex=_never, + dict=None, + restat=_never, + restend=_never, + recont=_never, + preproc=identity, + handle=nohandle, + ouf=sys.stdout, + ): "Initialize self's attributes" - self.regex = regex + self.regex = regex if dict is not None: self.globals = dict else: self.globals = {} - self.globals['sys'] = sys - self.locals = { '_cb':self.copyblock } - self.restat = restat + self.globals["sys"] = sys + self.locals = {"_cb": self.copyblock} + self.restat = restat self.restend = restend - self.recont = recont + self.recont = recont self.preproc = preproc - self.handle = handle - self.ouf = ouf + self.handle = handle + self.ouf = ouf + def copy(self, block=None, inf=sys.stdin): "Entry point: copy-with-processing a file, or a block of lines" - if block is None: block = inf.readlines() - self.locals['_bl'] = block + if block is None: + block = inf.readlines() + self.locals["_bl"] = block self.copyblock() -def replace(template,dict,file): - "Test: copy a block of lines, with full processing" - import re - rex=re.compile('@([^@]+)@') - rbe=re.compile('\+') - ren=re.compile('-') - rco=re.compile('= ') - x=23 # just a variable to try substitution - cop = copier(rex, dict, rbe, ren, rco) - lines_block = [line+'\n' for line in template.split('\n')] - cop.ouf = file - cop.copy(lines_block) -if __name__=='__main__': +def replace(template, dict, file): "Test: copy a block of lines, with full processing" import re - rex=re.compile('@([^@]+)@') - rbe=re.compile('\+') - ren=re.compile('-') - rco=re.compile('= ') - x=23 # just a variable to try substitution + + rex = re.compile("@([^@]+)@") + rbe = re.compile("\+") + ren = re.compile("-") + rco = re.compile("= ") + x = 23 # just a variable to try substitution + cop = copier(rex, dict, rbe, ren, rco) + lines_block = [line + "\n" for line in template.split("\n")] + cop.ouf = file + cop.copy(lines_block) + + +if __name__ == "__main__": + "Test: copy a block of lines, with full processing" + import re + + rex = re.compile("@([^@]+)@") + rbe = re.compile("\+") + ren = re.compile("-") + rco = re.compile("= ") + x = 23 # just a variable to try substitution cop = copier(rex, globals(), rbe, ren, rco) - lines_block = [line+'\n' for line in """ + lines_block = [ + line + "\n" + for line in """ A first, plain line -- it just gets copied. A second line, with @x@ substitutions. + x+=1 # non-block statements MUST end with comments @@ -143,9 +177,11 @@ After all, @x@ is rather small! + for i in range(3): Also, @i@ times @x@ is @i*x@. - -One last, plain line at the end.""".split('\n')] +One last, plain line at the end.""".split( + "\n" + ) + ] print("*** input:") - print(''.join(lines_block)) + print("".join(lines_block)) print("*** output:") cop.copy(lines_block) - diff --git a/src/Tools/generateTemplates/template.py b/src/Tools/generateTemplates/template.py index f152b4f9fc..5f6b82e11a 100644 --- a/src/Tools/generateTemplates/template.py +++ b/src/Tools/generateTemplates/template.py @@ -1,8 +1,8 @@ #! python # -*- coding: utf-8 -*- -# (c) 2006 Juergen Riegel +# (c) 2006 Juergen Riegel + class ModelTemplate: def Generate(self): print("Generate() needs to be implemented in a Template class!") - diff --git a/src/Tools/generateTemplates/templateCPPFile.py b/src/Tools/generateTemplates/templateCPPFile.py index 9bb5414d19..f30e313bfd 100644 --- a/src/Tools/generateTemplates/templateCPPFile.py +++ b/src/Tools/generateTemplates/templateCPPFile.py @@ -1,15 +1,17 @@ #! python # -*- coding: utf-8 -*- -# (c) 2006 Juergen Riegel +# (c) 2006 Juergen Riegel import template import generateBase.generateModel_Module import generateBase.generateTools -class TemplateCPPFile (template.ModelTemplate): - def Generate(self): - generateBase.generateTools.ensureDir(self.path) - print ("Generate() App Dir") + +class TemplateCPPFile(template.ModelTemplate): + def Generate(self): + generateBase.generateTools.ensureDir(self.path) + print("Generate() App Dir") + Template = """ /*************************************************************************** diff --git a/src/Tools/generateTemplates/templateClassPyExport.py b/src/Tools/generateTemplates/templateClassPyExport.py index 2666555d73..7c39527bd7 100644 --- a/src/Tools/generateTemplates/templateClassPyExport.py +++ b/src/Tools/generateTemplates/templateClassPyExport.py @@ -1,33 +1,34 @@ #! python # -*- coding: utf-8 -*- -# (c) 2006 Juergen Riegel +# (c) 2006 Juergen Riegel from . import template -import os,sys +import os, sys import generateBase.generateModel_Module import generateBase.generateTools -class TemplateClassPyExport (template.ModelTemplate): + +class TemplateClassPyExport(template.ModelTemplate): def Generate(self): - #self.ParentNamespace = "Base" - #self.Namespace = "Base" + # self.ParentNamespace = "Base" + # self.Namespace = "Base" encoding = sys.getfilesystemencoding() path = self.path exportName = self.export.Name dirname = self.dirname - print("TemplateClassPyExport",path + exportName) + print("TemplateClassPyExport", path + exportName) # Imp.cpp must not exist, neither in path nor in dirname - if(not os.path.exists(path + exportName + "Imp.cpp")): - if(not os.path.exists(dirname + exportName + "Imp.cpp")): - file = open(path + exportName + "Imp.cpp",'wb') - generateBase.generateTools.replace(self.TemplateImplement,locals(),file) + if not os.path.exists(path + exportName + "Imp.cpp"): + if not os.path.exists(dirname + exportName + "Imp.cpp"): + file = open(path + exportName + "Imp.cpp", "wb") + generateBase.generateTools.replace(self.TemplateImplement, locals(), file) file.close() - with open(path + exportName + ".cpp", 'wb') as file: - generateBase.generateTools.replace(self.TemplateModule,locals(),file) - with open(path + exportName + ".h", 'wb') as file: - generateBase.generateTools.replace(self.TemplateHeader,locals(),file) - #file.write( generateBase.generateTools.replace(self.Template,locals())) + with open(path + exportName + ".cpp", "wb") as file: + generateBase.generateTools.replace(self.TemplateModule, locals(), file) + with open(path + exportName + ".h", "wb") as file: + generateBase.generateTools.replace(self.TemplateHeader, locals(), file) + # file.write( generateBase.generateTools.replace(self.Template,locals())) TemplateHeader = """ // This file is generated by src/Tools/generateTemplates/templateClassPyExport.py out of the XML file @@ -508,7 +509,7 @@ PyGetSetDef @self.export.Name@::GetterSetter[] = { + for i in self.export.Attribute: {"@i.Name@", (getter) staticCallback_get@i.Name@, - (setter) staticCallback_set@i.Name@, + (setter) staticCallback_set@i.Name@, "@i.Documentation.UserDocu.replace('\\n','\\\\n')@", nullptr }, @@ -692,7 +693,7 @@ PyObject *@self.export.Name@::PyMake(struct _typeobject *, PyObject *, PyObject { // never create such objects with the constructor PyErr_SetString(PyExc_RuntimeError, "You cannot create directly an instance of '@self.export.Name@'."); - + return nullptr; } @@ -829,14 +830,14 @@ int @self.export.Name@::_setattr(const char *attr, PyObject *value) // __setattr #endif #if 0 -/* From here on come the methods you have to implement, but NOT in this module. Implement in @self.export.Name@Imp.cpp! This prototypes +/* From here on come the methods you have to implement, but NOT in this module. Implement in @self.export.Name@Imp.cpp! This prototypes * are just for convenience when you add a new method. */ + if (self.export.Constructor): PyObject *@self.export.Name@::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper { - // create a new instance of @self.export.Name@ and the Twin object + // create a new instance of @self.export.Name@ and the Twin object return new @self.export.Name@(new @self.export.TwinPointer@); } @@ -1136,7 +1137,7 @@ PyObject *@self.export.Name@::getCustomAttributes(const char* /*attr*/) const int @self.export.Name@::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { - return 0; + return 0; } - @@ -1158,7 +1159,7 @@ int @self.export.Name@::descriptorSetter(PyObject* self, PyObject* obj, PyObject #endif -""" +""" # Here's the template for the user part of the implementation. This does NOT get overridden if it already exists. TemplateImplement = """ @@ -1181,7 +1182,7 @@ std::string @self.export.Name@::representation() const + if (self.export.Constructor): PyObject *@self.export.Name@::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper { - // create a new instance of @self.export.Name@ and the Twin object + // create a new instance of @self.export.Name@ and the Twin object return new @self.export.Name@(new @self.export.TwinPointer@); } @@ -1479,7 +1480,7 @@ PyObject *@self.export.Name@::getCustomAttributes(const char* /*attr*/) const int @self.export.Name@::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { - return 0; + return 0; } - diff --git a/src/Tools/generateTemplates/templateModule.py b/src/Tools/generateTemplates/templateModule.py index 562e0016f8..dc7fa7387c 100644 --- a/src/Tools/generateTemplates/templateModule.py +++ b/src/Tools/generateTemplates/templateModule.py @@ -1,16 +1,14 @@ #! python # -*- coding: utf-8 -*- -# (c) 2006 Juergen Riegel +# (c) 2006 Juergen Riegel from . import template, templateModuleApp -class TemplateModule (template.ModelTemplate): + +class TemplateModule(template.ModelTemplate): def Generate(self): print("generateBase.generateModel_Module.Generate()\n") - App= templateModuleApp.TemplateModuleApp() - App.path = self.path + App = templateModuleApp.TemplateModuleApp() + App.path = self.path App.module = self.module App.Generate() - - - diff --git a/src/Tools/generateTemplates/templateModuleApp.py b/src/Tools/generateTemplates/templateModuleApp.py index 6097c234b1..8ac39b7cfe 100644 --- a/src/Tools/generateTemplates/templateModuleApp.py +++ b/src/Tools/generateTemplates/templateModuleApp.py @@ -1,22 +1,23 @@ #! python # -*- coding: utf-8 -*- -# (c) 2007 Juergen Riegel +# (c) 2007 Juergen Riegel from . import template, templateModuleAppMain, templateModuleAppFeature import generateBase.generateModel_Module import generateBase.generateTools -class TemplateModuleApp (template.ModelTemplate): + +class TemplateModuleApp(template.ModelTemplate): def Generate(self): AppPath = self.path + "/App/" generateBase.generateTools.ensureDir(AppPath) - + # the main module files - AppMain= templateModuleAppMain.TemplateModuleAppMain() - AppMain.path = AppPath + AppMain = templateModuleAppMain.TemplateModuleAppMain() + AppMain.path = AppPath AppMain.module = self.module AppMain.Generate() - + # Features generateBase.generateTools.ensureDir(AppPath + "Features/") for i in self.module.Content.Feature: @@ -25,5 +26,3 @@ class TemplateModuleApp (template.ModelTemplate): AppFeature.module = self.module AppFeature.feature = i AppFeature.Generate() - - diff --git a/src/Tools/generateTemplates/templateModuleAppFeature.py b/src/Tools/generateTemplates/templateModuleAppFeature.py index c56f6c4b3f..ad81d97c1c 100644 --- a/src/Tools/generateTemplates/templateModuleAppFeature.py +++ b/src/Tools/generateTemplates/templateModuleAppFeature.py @@ -1,22 +1,23 @@ #! python # -*- coding: utf-8 -*- -# (c) 2006 Juergen Riegel +# (c) 2006 Juergen Riegel from . import template import generateBase.generateModel_Module import generateBase.generateTools -class TemplateFeature (template.ModelTemplate): - def Generate(self): - file = open(self.path + self.feature.Name + "Imp.cpp",'w') - generateBase.generateTools.replace(self.TemplateImplement,locals(),file) - file = open(self.path + self.feature.Name + ".cpp",'w') - generateBase.generateTools.replace(self.TemplateModule,locals(),file) - file = open(self.path + self.feature.Name + ".h",'w') - generateBase.generateTools.replace(self.TemplateHeader,locals(),file) - #file.write( generateBase.generateTools.replace(self.Template,locals())) - TemplateHeader = """ +class TemplateFeature(template.ModelTemplate): + def Generate(self): + file = open(self.path + self.feature.Name + "Imp.cpp", "w") + generateBase.generateTools.replace(self.TemplateImplement, locals(), file) + file = open(self.path + self.feature.Name + ".cpp", "w") + generateBase.generateTools.replace(self.TemplateModule, locals(), file) + file = open(self.path + self.feature.Name + ".h", "w") + generateBase.generateTools.replace(self.TemplateHeader, locals(), file) + # file.write( generateBase.generateTools.replace(self.Template,locals())) + + TemplateHeader = """ #ifndef @self.module.Name.upper()@_FEATURE_@self.feature.Name.upper()@_H #define @self.module.Name.upper()@_FEATURE_@self.feature.Name.upper()@_H @@ -54,7 +55,7 @@ public: #endif // @self.module.Name.upper()@_FEATURE_@self.feature.Name.upper()@_H """ - TemplateModule = """ + TemplateModule = """ #include "PreCompiled.h" #include "@self.feature.Name@.h" @@ -69,10 +70,10 @@ PROPERTY_SOURCE(@self.module.Name@::@self.feature.Name@, App::Feature) ADD_PROPERTY(@i.Name@,(0.0)); - } -""" - # Here's the template for the user part of the implementation. This does NOT get overwritten if it already exists. - TemplateImplement = """ -// +""" + # Here's the template for the user part of the implementation. This does NOT get overwritten if it already exists. + TemplateImplement = """ +// #include "PreCompiled.h" #include "@self.feature.Name@.h" diff --git a/src/Tools/generateTemplates/templateModuleAppMain.py b/src/Tools/generateTemplates/templateModuleAppMain.py index 7ba8b3264f..98643a12f3 100644 --- a/src/Tools/generateTemplates/templateModuleAppMain.py +++ b/src/Tools/generateTemplates/templateModuleAppMain.py @@ -1,16 +1,17 @@ #! python # -*- coding: utf-8 -*- -# (c) 2006 Juergen Riegel +# (c) 2006 Juergen Riegel from . import template import generateBase.generateModel_Module import generateBase.generateTools -class TemplateModuleAppMain (template.ModelTemplate): + +class TemplateModuleAppMain(template.ModelTemplate): def Generate(self): - file = open(self.path + "/App" + self.module.Name + ".cpp",'w') - generateBase.generateTools.replace(self.Template,locals(),file) - #file.write( generateBase.generateTools.replace(self.Template,locals())) + file = open(self.path + "/App" + self.module.Name + ".cpp", "w") + generateBase.generateTools.replace(self.Template, locals(), file) + # file.write( generateBase.generateTools.replace(self.Template,locals())) Template = """ /*************************************************************************** diff --git a/src/Tools/generateTemplates/templateModuleGui.py b/src/Tools/generateTemplates/templateModuleGui.py index df0fe13fe4..e6a244d221 100644 --- a/src/Tools/generateTemplates/templateModuleGui.py +++ b/src/Tools/generateTemplates/templateModuleGui.py @@ -1,10 +1,10 @@ #! python # -*- coding: utf-8 -*- -# (c) 2006 Juergen Riegel +# (c) 2006 Juergen Riegel from . import template -class TemplateModuleGui (template.ModelTemplate): + +class TemplateModuleGui(template.ModelTemplate): def Generate(self): print("Generate() needs to be implemented in a Template class!") - diff --git a/src/Tools/githubstats.py b/src/Tools/githubstats.py index 64a1f8dc8f..f29feebd62 100755 --- a/src/Tools/githubstats.py +++ b/src/Tools/githubstats.py @@ -3,9 +3,10 @@ print("Fetching download statistics from github...") import requests -r=requests.get('https://api.github.com/repos/FreeCAD/FreeCAD/releases') + +r = requests.get("https://api.github.com/repos/FreeCAD/FreeCAD/releases") myobj = r.json() for p in myobj: if "assets" in p: - for asset in p['assets']: - print((asset['name'] + ": " + str(asset['download_count']) + " downloads")) + for asset in p["assets"]: + print((asset["name"] + ": " + str(asset["download_count"]) + " downloads")) diff --git a/src/Tools/make_snapshot.py b/src/Tools/make_snapshot.py index 375ec3942a..2ac9dceb61 100644 --- a/src/Tools/make_snapshot.py +++ b/src/Tools/make_snapshot.py @@ -22,19 +22,21 @@ import importlib import sys from PySide2 import QtGui + def init_gui(): try: FreeCADGui.setupWithoutGUI() except Exception as e: pass -def make_snapshot(input_file, output_file, size = 48): + +def make_snapshot(input_file, output_file, size=48): from pivy import coin ext = os.path.splitext(input_file)[1][1:] mod = FreeCAD.getImportType(ext) if len(mod) == 0: - print ("Cannot load file {}".format(input_file)) + print("Cannot load file {}".format(input_file)) return # use the first listed module @@ -43,7 +45,7 @@ def make_snapshot(input_file, output_file, size = 48): doc = FreeCAD.ActiveDocument if doc is None: - print ("No active document") + print("No active document") return init_gui() @@ -64,9 +66,9 @@ def make_snapshot(input_file, output_file, size = 48): height = size viewport = coin.SbViewportRegion(width, height) cam.orientation.setValue(axo) - cam.viewAll(root,viewport) + cam.viewAll(root, viewport) off = FreeCADGui.SoQtOffscreenRenderer(width, height) - off.setBackgroundColor(1,1,1) + off.setBackgroundColor(1, 1, 1) root.ref() # A QGuiApplication is needed to create an OpenGL context diff --git a/src/Tools/makedist.py b/src/Tools/makedist.py index 1fbcb89c9e..fc04a66e3d 100644 --- a/src/Tools/makedist.py +++ b/src/Tools/makedist.py @@ -7,15 +7,20 @@ import sys, os, getopt, tarfile, gzip, time, io, platform, shutil, subprocess + def main(): - bindir="." - major="0" - minor="0" - dfsg=False - check=False - wta=None + bindir = "." + major = "0" + minor = "0" + dfsg = False + check = False + wta = None try: - opts, args = getopt.getopt(sys.argv[1:], "sb:", ["srcdir=","bindir=","major=","minor=","dfsg", "check"]) + opts, args = getopt.getopt( + sys.argv[1:], + "sb:", + ["srcdir=", "bindir=", "major=", "minor=", "dfsg", "check"], + ) except getopt.GetoptError: pass @@ -35,7 +40,7 @@ def main(): check = True if dfsg: - gitattr = open("src/.gitattributes","w") + gitattr = open("src/.gitattributes", "w") gitattr.write("zipios++ export-ignore\n") gitattr.write("Pivy-0.5 export-ignore\n") gitattr.write("Pivy export-ignore\n") @@ -44,24 +49,24 @@ def main(): gitattr.close() # revision number - info=os.popen("git rev-list HEAD").read() - revision='%04d' % (info.count('\n')) + info = os.popen("git rev-list HEAD").read() + revision = "%04d" % (info.count("\n")) - verfile = open("{}/src/Build/Version.h".format(bindir), 'rb') + verfile = open("{}/src/Build/Version.h".format(bindir), "rb") verstream = io.BytesIO(verfile.read()) verfile.close() version_major = major version_minor = minor - PACKAGE_NAME = 'freecad' + PACKAGE_NAME = "freecad" version = "{}.{}.{}".format(version_major, version_minor, revision) - DIRNAME = "%(p)s-%(v)s" % {'p': PACKAGE_NAME, 'v': version} - TARNAME = DIRNAME + '.tar' - TGZNAME = DIRNAME + '.tar.gz' + DIRNAME = "%(p)s-%(v)s" % {"p": PACKAGE_NAME, "v": version} + TARNAME = DIRNAME + ".tar" + TGZNAME = DIRNAME + ".tar.gz" if dfsg: - TGZNAME = DIRNAME + '-dfsg.tar.gz' + TGZNAME = DIRNAME + "-dfsg.tar.gz" verinfo = tarfile.TarInfo(DIRNAME + "/src/Build/Version.h") verinfo.mode = 0o660 @@ -73,15 +78,17 @@ def main(): else: print(("git archive {} --prefix={}/ HEAD".format(wta, DIRNAME))) - if platform.system() == 'Windows': - os.popen("git archive {} --prefix={}/ --output={} HEAD".format(wta, DIRNAME, TARNAME)).read() + if platform.system() == "Windows": + os.popen( + "git archive {} --prefix={}/ --output={} HEAD".format(wta, DIRNAME, TARNAME) + ).read() tar = tarfile.TarFile(mode="a", name=TARNAME) tar.addfile(verinfo, verstream) tar.close() out = gzip.open(TGZNAME, "wb") - tardata = open(TARNAME, 'rb') + tardata = open(TARNAME, "rb") out.write(tardata.read()) out.close() tardata.close() @@ -94,7 +101,7 @@ def main(): cmd_line.append("HEAD") tardata = subprocess.Popen(cmd_line, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - out,err = tardata.communicate() + out, err = tardata.communicate() tarstream = io.BytesIO(out) tar = tarfile.TarFile(mode="a", fileobj=tarstream) @@ -110,7 +117,7 @@ def main(): print(("Created " + TGZNAME)) # Unpack and build if check: - archive=tarfile.open(mode='r:gz',name=TGZNAME) + archive = tarfile.open(mode="r:gz", name=TGZNAME) archive.extractall(bindir) builddir = os.path.join(bindir, DIRNAME) cwd = os.getcwd() @@ -120,5 +127,6 @@ def main(): os.chdir(cwd) shutil.rmtree(builddir) + if __name__ == "__main__": main() diff --git a/src/Tools/params_utils.py b/src/Tools/params_utils.py index 98911a53c1..725ec9b427 100644 --- a/src/Tools/params_utils.py +++ b/src/Tools/params_utils.py @@ -19,62 +19,73 @@ # * USA * # * * # *************************************************************************** -'''Utilites for generating C++ code for parameters management using Python Cog -''' +"""Utilites for generating C++ code for parameters management using Python Cog +""" import cog import inspect, re from os import path + def quote(txt, indent=0): - lines = [ ' '*indent + '"' + l.replace('\\', '\\\\').replace('"', '\\"') for l in txt.split('\n')] + lines = [ + " " * indent + '"' + l.replace("\\", "\\\\").replace('"', '\\"') for l in txt.split("\n") + ] return '\\n"\n'.join(lines) + '"' + def init_params(params, namespace, class_name, param_path, header_file=None): for param in params: param.path = param_path if not header_file: - header_file = [f'{namespace}/{class_name}.h'] - param.header_file = header_file + getattr(param.proxy, 'header_file', []) + header_file = [f"{namespace}/{class_name}.h"] + param.header_file = header_file + getattr(param.proxy, "header_file", []) param.namespace = namespace param.class_name = class_name return params + def auto_comment(frame=1, msg=None, count=1): trace = [] - for stack in inspect.stack()[frame:frame+count]: - filename = path.normpath(stack[1]).split('/src/')[-1] - if filename.find('<') >= 0: + for stack in inspect.stack()[frame : frame + count]: + filename = path.normpath(stack[1]).split("/src/")[-1] + if filename.find("<") >= 0: break lineno = stack[2] - trace.insert(0, f'{filename}:{lineno}') + trace.insert(0, f"{filename}:{lineno}") return f'{"// Auto generated code" if msg is None else msg} ({" <- ".join(trace)})' + def trace_comment(): return auto_comment(2) + def get_module_path(module): - return path.dirname(module.__file__.split(f'src{path.sep}')[-1]) + return path.dirname(module.__file__.split(f"src{path.sep}")[-1]) + def declare_begin(module, header=True): class_name = module.ClassName namespace = module.NameSpace params = module.Params param_path = module.ParamPath - file_path = getattr(module, 'FilePath', get_module_path(module)) - param_file = getattr(module, 'ParamSource', f'{file_path}/{class_name}.py') - header_file = getattr(module, 'HeaderFile', f'{file_path}/{class_name}.h') - source_file = getattr(module, 'SourceFile', f'{file_path}/{class_name}.cpp') + file_path = getattr(module, "FilePath", get_module_path(module)) + param_file = getattr(module, "ParamSource", f"{file_path}/{class_name}.py") + header_file = getattr(module, "HeaderFile", f"{file_path}/{class_name}.h") + source_file = getattr(module, "SourceFile", f"{file_path}/{class_name}.cpp") class_doc = module.ClassDoc - signal = getattr(module, 'Signal', False) + signal = getattr(module, "Signal", False) if header: - cog.out(f''' + cog.out( + f""" {trace_comment()} #include {"#include " if signal else ""} -''') +""" + ) - cog.out(f''' + cog.out( + f""" {trace_comment()} namespace {namespace} {{ /** {class_doc} @@ -110,47 +121,64 @@ namespace {namespace} {{ class {namespace}Export {class_name} {{ public: static ParameterGrp::handle getHandle(); -''') +""" + ) if signal: - cog.out(f''' + cog.out( + f""" static boost::signals2::signal &signalParamChanged(); static void signalAll(); -''') +""" + ) for param in params: - cog.out(f''' + cog.out( + f""" {trace_comment()} //@{{ - /// Accessor for parameter {param.name}''') + /// Accessor for parameter {param.name}""" + ) if param._doc: - cog.out(f''' - ///''') - for line in param._doc.split('\n'): - cog.out(f''' - /// {line}''') - cog.out(f''' + cog.out( + f""" + ///""" + ) + for line in param._doc.split("\n"): + cog.out( + f""" + /// {line}""" + ) + cog.out( + f""" static const {param.C_Type} & get{param.name}(); static const {param.C_Type} & default{param.name}(); static void remove{param.name}(); static void set{param.name}(const {param.C_Type} &v); - static const char *doc{param.name}();''') + static const char *doc{param.name}();""" + ) if param.on_change: - cog.out(f''' - static void on{param.name}Changed();''') - cog.out(f''' + cog.out( + f""" + static void on{param.name}Changed();""" + ) + cog.out( + f""" //@}} -''') +""" + ) def declare_end(module): class_name = module.ClassName namespace = module.NameSpace - cog.out(f''' + cog.out( + f""" {trace_comment()} }}; // class {class_name} }} // namespace {namespace} -''') +""" + ) def define(module, header=True): @@ -159,66 +187,85 @@ def define(module, header=True): params = module.Params param_path = module.ParamPath class_doc = module.ClassDoc - signal = getattr(module, 'Signal', False) + signal = getattr(module, "Signal", False) if header: - cog.out(f''' + cog.out( + f""" {trace_comment()} #include #include #include #include "{class_name}.h" using namespace {namespace}; -''') +""" + ) - cog.out(f''' + cog.out( + f""" {trace_comment()} namespace {{ class {class_name}P: public ParameterGrp::ObserverType {{ public: ParameterGrp::handle handle; std::unordered_map funcs; -''') +""" + ) if signal: - cog.out(f''' + cog.out( + f""" {trace_comment()} boost::signals2::signal signalParamChanged; void signalAll() - {{''') + {{""" + ) for param in params: - cog.out(f''' - signalParamChanged("{param.name}");''') - cog.out(f''' + cog.out( + f""" + signalParamChanged("{param.name}");""" + ) + cog.out( + f""" {trace_comment()} - }}''') + }}""" + ) for param in params: - cog.out(f''' - {param.C_Type} {param.name};''') + cog.out( + f""" + {param.C_Type} {param.name};""" + ) - cog.out(f''' + cog.out( + f""" {trace_comment()} {class_name}P() {{ handle = App::GetApplication().GetParameterGroupByPath("{param_path}"); handle->Attach(this); -''') +""" + ) for param in params: - cog.out(f''' + cog.out( + f""" {param.name} = {param.getter('handle')}; - funcs["{param.name}"] = &{class_name}P::update{param.name};''') + funcs["{param.name}"] = &{class_name}P::update{param.name};""" + ) - cog.out(f''' + cog.out( + f""" }} {trace_comment()} ~{class_name}P() {{ }} -''') - cog.out(f''' +""" + ) + cog.out( + f""" {trace_comment()} void OnChange(Base::Subject &, const char* sReason) {{ if(!sReason) @@ -230,17 +277,21 @@ public: {"signalParamChanged(sReason);" if signal else ""} }} -''') +""" + ) for param in params: if not param.on_change: - cog.out(f''' + cog.out( + f""" {trace_comment()} static void update{param.name}({class_name}P *self) {{ self->{param.name} = {param.getter('self->handle')}; - }}''') + }}""" + ) else: - cog.out(f''' + cog.out( + f""" {trace_comment()} static void update{param.name}({class_name}P *self) {{ auto v = {param.getter('self->handle')}; @@ -248,9 +299,11 @@ public: self->{param.name} = v; {class_name}::on{param.name}Changed(); }} - }}''') + }}""" + ) - cog.out(f''' + cog.out( + f""" }}; {trace_comment()} @@ -260,83 +313,107 @@ public: }} }} // Anonymous namespace -''') - cog.out(f''' +""" + ) + cog.out( + f""" {trace_comment()} ParameterGrp::handle {class_name}::getHandle() {{ return instance()->handle; }} -''') +""" + ) if signal: - cog.out(f''' + cog.out( + f""" {trace_comment()} boost::signals2::signal & {class_name}::signalParamChanged() {{ return instance()->signalParamChanged; }} -''') - cog.out(f''' +""" + ) + cog.out( + f""" {trace_comment()} void signalAll() {{ instance()->signalAll(); }} -''') +""" + ) for param in params: - cog.out(f''' + cog.out( + f""" {trace_comment()} const char *{class_name}::doc{param.name}() {{ return {param.doc(class_name)}; }} -''') - cog.out(f''' +""" + ) + cog.out( + f""" {trace_comment()} const {param.C_Type} & {class_name}::get{param.name}() {{ return instance()->{param.name}; }} -''') - cog.out(f''' +""" + ) + cog.out( + f""" {trace_comment()} const {param.C_Type} & {class_name}::default{param.name}() {{ const static {param.C_Type} def = {param.default}; return def; }} -''') - cog.out(f''' +""" + ) + cog.out( + f""" {trace_comment()} void {class_name}::set{param.name}(const {param.C_Type} &v) {{ {param.setter()}; instance()->{param.name} = v; }} -''') - cog.out(f''' +""" + ) + cog.out( + f""" {trace_comment()} void {class_name}::remove{param.name}() {{ instance()->handle->Remove{param.Type}("{param.name}"); }} -''') +""" + ) + def widgets_declare(param_set): param_group = param_set.ParamGroup - for title,params in param_group: - name = _regex.sub('', title) - cog.out(f''' + for title, params in param_group: + name = _regex.sub("", title) + cog.out( + f""" {trace_comment()} - QGroupBox * group{name} = nullptr;''') + QGroupBox * group{name} = nullptr;""" + ) for param in params: param.declare_widget() + def widgets_init(param_set): param_group = param_set.ParamGroup - cog.out(f''' - auto layout = new QVBoxLayout(this);''') + cog.out( + f""" + auto layout = new QVBoxLayout(this);""" + ) for title, params in param_group: - name = _regex.sub('', title) - cog.out(f''' + name = _regex.sub("", title) + cog.out( + f""" {trace_comment()} @@ -345,54 +422,69 @@ def widgets_init(param_set): auto layoutHoriz{name} = new QHBoxLayout(group{name}); auto layout{name} = new QGridLayout(); layoutHoriz{name}->addLayout(layout{name}); - layoutHoriz{name}->addStretch();''') + layoutHoriz{name}->addStretch();""" + ) - for row,param in enumerate(params): - cog.out(f''' + for row, param in enumerate(params): + cog.out( + f""" - {trace_comment()}''') + {trace_comment()}""" + ) param.init_widget(row, name) - cog.out(''' + cog.out( + """ layout->addItem(new QSpacerItem(40, 20, QSizePolicy::Fixed, QSizePolicy::Expanding)); - retranslateUi();''') + retranslateUi();""" + ) + def widgets_restore(param_set): param_group = param_set.ParamGroup - cog.out(f''' - {trace_comment()}''') - for _,params in param_group: + cog.out( + f""" + {trace_comment()}""" + ) + for _, params in param_group: for param in params: param.widget_restore() + def widgets_save(param_set): param_group = param_set.ParamGroup - cog.out(f''' - {trace_comment()}''') - for _,params in param_group: + cog.out( + f""" + {trace_comment()}""" + ) + for _, params in param_group: for param in params: param.widget_save() + def preference_dialog_declare_begin(param_set, header=True): namespace = param_set.NameSpace class_name = param_set.ClassName - dialog_namespace = getattr(param_set, 'DialogNameSpace', 'Dialog') + dialog_namespace = getattr(param_set, "DialogNameSpace", "Dialog") param_group = param_set.ParamGroup - file_path = getattr(param_set, 'FilePath', get_module_path(param_set)) - param_file = getattr(param_set, 'ParamSource', f'{file_path}/{class_name}.py') - header_file = getattr(param_set, 'HeaderFile', f'{file_path}/{class_name}.h') - source_file = getattr(param_set, 'SourceFile', f'{file_path}/{class_name}.cpp') + file_path = getattr(param_set, "FilePath", get_module_path(param_set)) + param_file = getattr(param_set, "ParamSource", f"{file_path}/{class_name}.py") + header_file = getattr(param_set, "HeaderFile", f"{file_path}/{class_name}.h") + source_file = getattr(param_set, "SourceFile", f"{file_path}/{class_name}.cpp") class_doc = param_set.ClassDoc if header: - cog.out(f''' + cog.out( + f""" {trace_comment()} #include -#include ''') +#include """ + ) - cog.out(f''' + cog.out( + f""" {trace_comment()} class QLabel; class QGroupBox; @@ -428,42 +520,49 @@ public: protected: void changeEvent(QEvent *e); -private:''') +private:""" + ) widgets_declare(param_set) def preference_dialog_declare_end(param_set): class_name = param_set.ClassName namespace = param_set.NameSpace - dialog_namespace = getattr(param_set, 'DialogNameSpace', 'Dialog') + dialog_namespace = getattr(param_set, "DialogNameSpace", "Dialog") - cog.out(f''' + cog.out( + f""" {trace_comment()} }}; }} // namespace {dialog_namespace} }} // namespace {namespace} -''') +""" + ) + def preference_dialog_declare(param_set, header=True): preference_dialog_declare_begin(param_set, header) preference_dialog_declare_end(param_set) + _regex = re.compile(r"[^a-zA-Z_]") + def preference_dialog_define(param_set, header=True): param_group = param_set.ParamGroup class_name = param_set.ClassName - dialog_namespace = getattr(param_set, 'DialogNameSpace', 'Dialog') - namespace = f'{param_set.NameSpace}::{dialog_namespace}' - file_path = getattr(param_set, 'FilePath', get_module_path(param_set)) - param_file = getattr(param_set, 'ParamSource', f'{file_path}/{class_name}.py') - header_file = getattr(param_set, 'HeaderFile', f'{file_path}/{class_name}.h') - source_file = getattr(param_set, 'SourceFile', f'{file_path}/{class_name}.cpp') - user_init = getattr(param_set, 'UserInit', '') + dialog_namespace = getattr(param_set, "DialogNameSpace", "Dialog") + namespace = f"{param_set.NameSpace}::{dialog_namespace}" + file_path = getattr(param_set, "FilePath", get_module_path(param_set)) + param_file = getattr(param_set, "ParamSource", f"{file_path}/{class_name}.py") + header_file = getattr(param_set, "HeaderFile", f"{file_path}/{class_name}.h") + source_file = getattr(param_set, "SourceFile", f"{file_path}/{class_name}.cpp") + user_init = getattr(param_set, "UserInit", "") headers = set() if header: - cog.out(f''' + cog.out( + f""" {trace_comment()} #ifndef _PreComp_ # include @@ -472,66 +571,86 @@ def preference_dialog_define(param_set, header=True): # include # include # include -#endif''') - for _,params in param_group: +#endif""" + ) + for _, params in param_group: for param in params: for header in param.header_file: if header not in headers: headers.add(header) - cog.out(f''' -#include <{header}>''') + cog.out( + f""" +#include <{header}>""" + ) - cog.out(f''' + cog.out( + f""" {trace_comment()} #include "{header_file}" using namespace {namespace}; /* TRANSLATOR {namespace}::{class_name} */ -''') +""" + ) - cog.out(f''' + cog.out( + f""" {trace_comment()} {class_name}::{class_name}(QWidget* parent) : PreferencePage( parent ) {{ -''') +""" + ) widgets_init(param_set) - cog.out(f''' + cog.out( + f""" {trace_comment()} {user_init} }} -''') - cog.out(f''' +""" + ) + cog.out( + f""" {trace_comment()} {class_name}::~{class_name}() {{ }} -''') - cog.out(f''' +""" + ) + cog.out( + f""" {trace_comment()} void {class_name}::saveSettings() -{{''') +{{""" + ) widgets_save(param_set) - cog.out(f''' + cog.out( + f""" }} {trace_comment()} void {class_name}::loadSettings() -{{''') +{{""" + ) widgets_restore(param_set) - cog.out(f''' + cog.out( + f""" }} {trace_comment()} void {class_name}::retranslateUi() {{ - setWindowTitle(QObject::tr("{param_set.Title}"));''') + setWindowTitle(QObject::tr("{param_set.Title}"));""" + ) for title, params in param_group: - name = _regex.sub('', title) - cog.out(f''' - group{name}->setTitle(QObject::tr("{title}"));''') - for row,param in enumerate(params): + name = _regex.sub("", title) + cog.out( + f""" + group{name}->setTitle(QObject::tr("{title}"));""" + ) + for row, param in enumerate(params): param.retranslate() - cog.out(f''' + cog.out( + f""" }} {trace_comment()} @@ -542,19 +661,24 @@ void {class_name}::changeEvent(QEvent *e) }} QWidget::changeEvent(e); }} -''') +""" + ) - cog.out(f''' + cog.out( + f""" {trace_comment()} #include "moc_{class_name}.cpp" -''') +""" + ) + + +_ParamPrefix = "User parameter:BaseApp/Preferences/" -_ParamPrefix = 'User parameter:BaseApp/Preferences/' class Param: - WidgetPrefix = '' + WidgetPrefix = "" - def __init__(self, name, default, doc='', title='', on_change=False, proxy=None, **kwd): + def __init__(self, name, default, doc="", title="", on_change=False, proxy=None, **kwd): self.name = name self.title = title if title else name self._default = default @@ -563,8 +687,10 @@ class Param: self.proxy = proxy def _declare_label(self): - cog.out(f''' - QLabel *label{self.name} = nullptr;''') + cog.out( + f""" + QLabel *label{self.name} = nullptr;""" + ) def declare_label(self): if self.proxy: @@ -573,9 +699,11 @@ class Param: self._declare_label() def _init_label(self, row, group_name): - cog.out(f''' + cog.out( + f""" label{self.name} = new QLabel(this); - layout{group_name}->addWidget(label{self.name}, {row}, 0);''') + layout{group_name}->addWidget(label{self.name}, {row}, 0);""" + ) def init_label(self, row, group_name): if self.proxy: @@ -585,8 +713,10 @@ class Param: def _declare_widget(self): self.declare_label() - cog.out(f''' - {self.widget_type} *{self.widget_name} = nullptr;''') + cog.out( + f""" + {self.widget_type} *{self.widget_name} = nullptr;""" + ) def declare_widget(self): if self.proxy: @@ -596,23 +726,33 @@ class Param: def _init_widget(self, row, group_name): self.init_label(row, group_name) - cog.out(f''' + cog.out( + f""" {self.widget_name} = new {self.widget_type}(this); - layout{group_name}->addWidget({self.widget_name}, {row}, {self.widget_column});''') + layout{group_name}->addWidget({self.widget_name}, {row}, {self.widget_column});""" + ) if self.widget_setter: - cog.out(f''' - {self.widget_name}->{self.widget_setter}({self.namespace}::{self.class_name}::default{self.name}());''') + cog.out( + f""" + {self.widget_name}->{self.widget_setter}({self.namespace}::{self.class_name}::default{self.name}());""" + ) self._init_pref_widget() def _init_pref_widget(self): - cog.out(f''' - {self.widget_name}->setEntryName("{self.name}");''') + cog.out( + f""" + {self.widget_name}->setEntryName("{self.name}");""" + ) if self.path.startswith(_ParamPrefix): - cog.out(f''' - {self.widget_name}->setParamGrpPath("{self.path[len(_ParamPrefix):]}");''') + cog.out( + f""" + {self.widget_name}->setParamGrpPath("{self.path[len(_ParamPrefix):]}");""" + ) else: - cog.out(f''' - {self.widget_name}->setParamGrpPath("{self.path}");''') + cog.out( + f""" + {self.widget_name}->setParamGrpPath("{self.path}");""" + ) def init_widget(self, row, group_name): if self.proxy: @@ -621,8 +761,10 @@ class Param: self._init_widget(row, group_name) def _widget_save(self): - cog.out(f''' - {self.widget_name}->onSave();''') + cog.out( + f""" + {self.widget_name}->onSave();""" + ) def widget_save(self): if self.proxy: @@ -631,8 +773,10 @@ class Param: self._widget_save() def _widget_restore(self): - cog.out(f''' - {self.widget_name}->onRestore();''') + cog.out( + f""" + {self.widget_name}->onRestore();""" + ) def widget_restore(self): if self.proxy: @@ -641,9 +785,11 @@ class Param: self._widget_restore() def _retranslate_label(self): - cog.out(f''' + cog.out( + f""" label{self.name}->setText(QObject::tr("{self.title}")); - label{self.name}->setToolTip({self.widget_name}->toolTip());''') + label{self.name}->setToolTip({self.widget_name}->toolTip());""" + ) def retranslate_label(self): if self.proxy: @@ -652,8 +798,10 @@ class Param: self._retranslate_label() def _retranslate(self): - cog.out(f''' - {self.widget_name}->setToolTip(QApplication::translate("{self.class_name}", {self.namespace}::{self.class_name}::doc{self.name}()));''') + cog.out( + f""" + {self.widget_name}->setToolTip(QApplication::translate("{self.class_name}", {self.namespace}::{self.class_name}::doc{self.name}()));""" + ) self.retranslate_label() def retranslate(self): @@ -669,8 +817,8 @@ class Param: def doc(self, class_name): if not self._doc: return '""' - return f'''QT_TRANSLATE_NOOP("{class_name}", -{quote(self._doc)})''' + return f"""QT_TRANSLATE_NOOP("{class_name}", +{quote(self._doc)})""" @property def widget_type(self): @@ -692,7 +840,7 @@ class Param: @property def widget_name(self): - return f'{self.widget_prefix}{self.name}' + return f"{self.widget_prefix}{self.name}" @property def widget_column(self): @@ -706,16 +854,16 @@ class Param: class ParamBool(Param): - Type = 'Bool' - C_Type = 'bool' - WidgetType = 'Gui::PrefCheckBox' - WidgetSetter = 'setChecked' + Type = "Bool" + C_Type = "bool" + WidgetType = "Gui::PrefCheckBox" + WidgetSetter = "setChecked" @property def default(self): if isinstance(self._default, str): return self._default - return 'true' if self._default else 'false' + return "true" if self._default else "false" def _declare_label(self): pass @@ -728,61 +876,72 @@ class ParamBool(Param): return 0 def _retranslate_label(self): - cog.out(f''' - {self.widget_name}->setText(QObject::tr("{self.title}"));''') + cog.out( + f""" + {self.widget_name}->setText(QObject::tr("{self.title}"));""" + ) + class ParamFloat(Param): - Type = 'Float' - C_Type = 'double' - WidgetType = 'Gui::PrefDoubleSpinBox' - WidgetSetter = 'setValue' + Type = "Float" + C_Type = "double" + WidgetType = "Gui::PrefDoubleSpinBox" + WidgetSetter = "setValue" + class ParamString(Param): - Type = 'ASCII' - C_Type = 'std::string' - WidgetType = 'Gui::PrefLineEdit' - WidgetSetter = 'setText' + Type = "ASCII" + C_Type = "std::string" + WidgetType = "Gui::PrefLineEdit" + WidgetSetter = "setText" @property def default(self): return f'"{self._default}"' + class ParamQString(Param): - Type = 'ASCII' - C_Type = 'QString' - WidgetType = 'Gui::PrefLineEdit' - WidgetSetter = 'setText' + Type = "ASCII" + C_Type = "QString" + WidgetType = "Gui::PrefLineEdit" + WidgetSetter = "setText" @property def default(self): return f'QStringLiteral("{self._default}")' def getter(self, handle): - return f'QString::fromUtf8({handle}->Get{self.Type}("{self.name}", "{self._default}").c_str())' + return ( + f'QString::fromUtf8({handle}->Get{self.Type}("{self.name}", "{self._default}").c_str())' + ) def setter(self): return f'instance()->handle->Set{self.Type}("{self.name}",v.toUtf8().constData())' + class ParamInt(Param): - Type = 'Int' - C_Type = 'long' - WidgetType = 'Gui::PrefSpinBox' - WidgetSetter = 'setValue' + Type = "Int" + C_Type = "long" + WidgetType = "Gui::PrefSpinBox" + WidgetSetter = "setValue" + class ParamUInt(Param): - Type = 'Unsigned' - C_Type = 'unsigned long' - WidgetType = 'Gui::PrefSpinBox' - WidgetSetter = 'setValue' + Type = "Unsigned" + C_Type = "unsigned long" + WidgetType = "Gui::PrefSpinBox" + WidgetSetter = "setValue" + class ParamHex(ParamUInt): @property def default(self): - return '0x%08X' % self._default + return "0x%08X" % self._default + class ParamProxy: WidgetType = None - WidgetPrefix = '' + WidgetPrefix = "" WidgetSetter = None def __init__(self, param_bool=None): @@ -814,9 +973,11 @@ class ParamProxy: param._init_widget(row, group_name) if self.param_bool: self.param_bool.init_widget(row, group_name) - cog.out(f''' + cog.out( + f""" {param.widget_name}->setEnabled({self.param_bool.widget_name}->isChecked()); - connect({self.param_bool.widget_name}, SIGNAL(toggled(bool)), {param.widget_name}, SLOT(setEnabled(bool)));''') + connect({self.param_bool.widget_name}, SIGNAL(toggled(bool)), {param.widget_name}, SLOT(setEnabled(bool)));""" + ) def retranslate_label(self, param): if not self.param_bool: @@ -847,13 +1008,14 @@ class ComboBoxItem: @property def data(self): if self._data is None: - return 'QVariant()' + return "QVariant()" if isinstance(self._data, str): return f'QByteArray("{self._data}")' return self._data + class ParamComboBox(ParamProxy): - WidgetType = 'Gui::PrefComboBox' + WidgetType = "Gui::PrefComboBox" def __init__(self, items, translate=True, param_bool=None): super().__init__(param_bool) @@ -861,11 +1023,11 @@ class ParamComboBox(ParamProxy): self.items = [] for item in items: if isinstance(item, str): - item = ComboBoxItem(item); + item = ComboBoxItem(item) elif isinstance(item, tuple): item = ComboBoxItem(*item) else: - assert(isinstance(item, ComboBoxItem)) + assert isinstance(item, ComboBoxItem) self.items.append(item) def widget_setter(self, _param): @@ -874,51 +1036,69 @@ class ParamComboBox(ParamProxy): def init_widget(self, param, row, group_name): super().init_widget(param, row, group_name) if self.translate: - cog.out(f''' + cog.out( + f""" for (int i=0; i<{len(self.items)}; ++i) {trace_comment()} - {param.widget_name}->addItem(QString());''') + {param.widget_name}->addItem(QString());""" + ) - for i,item in enumerate(self.items): + for i, item in enumerate(self.items): if not self.translate: - cog.out(f''' - {param.widget_name}->addItem(QStringLiteral("{item.text}"));''') + cog.out( + f""" + {param.widget_name}->addItem(QStringLiteral("{item.text}"));""" + ) if item._data is not None: - cog.out(f''' - {param.widget_name}->setItemData({param.widget_name}->count()-1, {item.data});''') + cog.out( + f""" + {param.widget_name}->setItemData({param.widget_name}->count()-1, {item.data});""" + ) - cog.out(f''' - {param.widget_name}->setCurrentIndex({param.namespace}::{param.class_name}::default{param.name}());''') + cog.out( + f""" + {param.widget_name}->setCurrentIndex({param.namespace}::{param.class_name}::default{param.name}());""" + ) def retranslate(self, param): super().retranslate(param) - cog.out(f''' - {trace_comment()}''') - for i,item in enumerate(self.items): + cog.out( + f""" + {trace_comment()}""" + ) + for i, item in enumerate(self.items): if self.translate: - cog.out(f''' - {param.widget_name}->setItemText({i}, QObject::tr("{item.text}"));''') + cog.out( + f""" + {param.widget_name}->setItemText({i}, QObject::tr("{item.text}"));""" + ) if item.tooltips: - cog.out(f''' - {param.widget_name}->setItemData({i}, QObject::tr("{item.tooltips}"), Qt::ToolTipRole);''') + cog.out( + f""" + {param.widget_name}->setItemData({i}, QObject::tr("{item.tooltips}"), Qt::ToolTipRole);""" + ) + class ParamLinePattern(ParamProxy): - WidgetType = 'Gui::PrefLinePattern' + WidgetType = "Gui::PrefLinePattern" def widget_setter(self, _param): return None def init_widget(self, param, row, group_name): super().init_widget(param, row, group_name) - cog.out(f''' + cog.out( + f""" {trace_comment()} for (int i=1; i<{param.widget_name}->count(); ++i) {{ if ({param.widget_name}->itemData(i).toInt() == {param.default}) {param.widget_name}->setCurrentIndex(i); - }}''') + }}""" + ) + class ParamColor(ParamProxy): - WidgetType = 'Gui::PrefColorButton' - WidgetSetter = 'setPackedColor' + WidgetType = "Gui::PrefColorButton" + WidgetSetter = "setPackedColor" def __init__(self, param_bool=None, transparency=True): super().__init__(param_bool) @@ -927,12 +1107,16 @@ class ParamColor(ParamProxy): def init_widget(self, param, row, group_name): super().init_widget(param, row, group_name) if self.transparency: - cog.out(f''' - {param.widget_name}->setAllowTransparency(true);''') + cog.out( + f""" + {param.widget_name}->setAllowTransparency(true);""" + ) + class ParamFile(ParamProxy): - WidgetType = 'Gui::PrefFileChooser' - WidgetSetter = 'setFileNameStd' + WidgetType = "Gui::PrefFileChooser" + WidgetSetter = "setFileNameStd" + class ParamSpinBox(ParamProxy): def __init__(self, value_min, value_max, value_step, decimals=0, param_bool=None): @@ -944,19 +1128,23 @@ class ParamSpinBox(ParamProxy): def init_widget(self, param, row, group_name): super().init_widget(param, row, group_name) - cog.out(f''' + cog.out( + f""" {trace_comment()} {param.widget_name}->setMinimum({self.value_min}); {param.widget_name}->setMaximum({self.value_max}); - {param.widget_name}->setSingleStep({self.value_step});''') + {param.widget_name}->setSingleStep({self.value_step});""" + ) if self.decimals: - cog.out(f''' - {param.widget_name}->setDecimals({self.decimals});''') + cog.out( + f""" + {param.widget_name}->setDecimals({self.decimals});""" + ) class ParamShortcutEdit(ParamProxy): - WidgetType = 'Gui::PrefAccelLineEdit' - WidgetSetter = 'setDisplayText' + WidgetType = "Gui::PrefAccelLineEdit" + WidgetSetter = "setDisplayText" class Property: @@ -964,34 +1152,43 @@ class Property: self.name = name self.type_name = property_type self.doc = doc - self.prop_flags = prop_flags if prop_flags else 'App::Prop_None' + self.prop_flags = prop_flags if prop_flags else "App::Prop_None" self.static = static self.group = group if group else "" def declare(self): if self.static: - cog.out(f''' + cog.out( + f""" static {self.type_name} *get{self.name}Property(App::DocumentObject *obj, bool force=false); inline {self.type_name} *get{self.name}Property(bool force=false) {{ return get{self.name}Property(this, force); - }}''') + }}""" + ) else: - cog.out(f''' - {self.type_name} *get{self.name}Property(bool force=false);''') + cog.out( + f""" + {self.type_name} *get{self.name}Property(bool force=false);""" + ) def define(self, class_name): if self.static: - cog.out(f''' + cog.out( + f""" {trace_comment()} {self.type_name} *{class_name}::get{self.name}Property(App::DocumentObject *obj, bool force) -{{''') +{{""" + ) else: - cog.out(f''' + cog.out( + f""" {trace_comment()} {self.type_name} *{class_name}::get{self.name}Property(bool force) {{ - auto obj = this;''') - cog.out(f''' + auto obj = this;""" + ) + cog.out( + f""" if (auto prop = Base::freecad_dynamic_cast<{self.type_name}>( obj->getPropertyByName("{self.name}"))) {{ @@ -1005,14 +1202,19 @@ class Property: {quote(self.doc)}, {self.prop_flags})); }} -''') +""" + ) + def declare_properties(properties): - cog.out(f''' - {trace_comment()}''') + cog.out( + f""" + {trace_comment()}""" + ) for prop in properties: prop.declare() + def define_properties(properties, class_name): for prop in properties: prop.define(class_name) diff --git a/src/Tools/plugins/imageformats/svg/main.cpp b/src/Tools/plugins/imageformats/svg/main.cpp index 0b5236c216..27952bac9b 100644 --- a/src/Tools/plugins/imageformats/svg/main.cpp +++ b/src/Tools/plugins/imageformats/svg/main.cpp @@ -46,18 +46,18 @@ #include "qsvgiohandler.h" -#include #include #include +#include QT_BEGIN_NAMESPACE -class QSvgPlugin : public QImageIOPlugin +class QSvgPlugin: public QImageIOPlugin { public: QStringList keys() const; - Capabilities capabilities(QIODevice *device, const QByteArray &format) const; - QImageIOHandler *create(QIODevice *device, const QByteArray &format = QByteArray()) const; + Capabilities capabilities(QIODevice* device, const QByteArray& format) const; + QImageIOHandler* create(QIODevice* device, const QByteArray& format = QByteArray()) const; }; QStringList QSvgPlugin::keys() const @@ -65,7 +65,8 @@ QStringList QSvgPlugin::keys() const return QStringList() << QLatin1String("svg") << QLatin1String("svgz"); } -QImageIOPlugin::Capabilities QSvgPlugin::capabilities(QIODevice *device, const QByteArray &format) const +QImageIOPlugin::Capabilities QSvgPlugin::capabilities(QIODevice* device, + const QByteArray& format) const { if (format == "svg" || format == "svgz") return Capabilities(CanRead); @@ -78,9 +79,9 @@ QImageIOPlugin::Capabilities QSvgPlugin::capabilities(QIODevice *device, const Q return cap; } -QImageIOHandler *QSvgPlugin::create(QIODevice *device, const QByteArray &format) const +QImageIOHandler* QSvgPlugin::create(QIODevice* device, const QByteArray& format) const { - QSvgIOHandler *hand = new QSvgIOHandler(); + QSvgIOHandler* hand = new QSvgIOHandler(); hand->setDevice(device); hand->setFormat(format); return hand; @@ -91,4 +92,4 @@ Q_EXPORT_PLUGIN2(qsvg, QSvgPlugin) QT_END_NAMESPACE -#endif // !QT_NO_IMAGEFORMATPLUGIN +#endif// !QT_NO_IMAGEFORMATPLUGIN diff --git a/src/Tools/plugins/imageformats/svg/qsvgiohandler.cpp b/src/Tools/plugins/imageformats/svg/qsvgiohandler.cpp index 5144194c64..fc9d3788a8 100644 --- a/src/Tools/plugins/imageformats/svg/qsvgiohandler.cpp +++ b/src/Tools/plugins/imageformats/svg/qsvgiohandler.cpp @@ -45,45 +45,48 @@ #ifndef QT_NO_SVGRENDERER -#include "qwebview.h" -#include "qxmlstream.h" -#include "qwebframe.h" -#include "qimage.h" -#include "qpixmap.h" -#include "qpainter.h" -#include "qvariant.h" #include "qbuffer.h" #include "qdebug.h" +#include "qimage.h" +#include "qpainter.h" +#include "qpixmap.h" +#include "qvariant.h" +#include "qwebframe.h" +#include "qwebview.h" +#include "qxmlstream.h" QT_BEGIN_NAMESPACE class QSvgIOHandlerPrivate { public: - QSvgIOHandlerPrivate(QSvgIOHandler *qq) - : q(qq), loaded(false), readDone(false), backColor(Qt::transparent) + QSvgIOHandlerPrivate(QSvgIOHandler* qq) + : q(qq), + loaded(false), + readDone(false), + backColor(Qt::transparent) { QPalette pal = webView.palette(); pal.setColor(QPalette::Background, backColor); webView.setPalette(pal); } - bool load(QIODevice *device); + bool load(QIODevice* device); - QSvgIOHandler *q; - QWebView webView; + QSvgIOHandler* q; + QWebView webView; QXmlStreamReader xmlReader; - QSize defaultSize; - QRect clipRect; - QSize scaledSize; - QRect scaledClipRect; - bool loaded; - bool readDone; - QColor backColor; + QSize defaultSize; + QRect clipRect; + QSize scaledSize; + QRect scaledClipRect; + bool loaded; + bool readDone; + QColor backColor; }; -bool QSvgIOHandlerPrivate::load(QIODevice *device) +bool QSvgIOHandlerPrivate::load(QIODevice* device) { if (loaded) return true; @@ -133,9 +136,7 @@ bool QSvgIOHandlerPrivate::load(QIODevice *device) QSvgIOHandler::QSvgIOHandler() : d(new QSvgIOHandlerPrivate(this)) -{ - -} +{} QSvgIOHandler::~QSvgIOHandler() @@ -149,13 +150,14 @@ bool QSvgIOHandler::canRead() const if (!device()) return false; if (d->loaded && !d->readDone) - return true; // Will happen if we have been asked for the size + return true;// Will happen if we have been asked for the size QByteArray buf = device()->peek(8); if (buf.startsWith("\x1f\x8b")) { setFormat("svgz"); return true; - } else if (buf.contains("readDone && d->load(device())) { - bool xform = (d->clipRect.isValid() || d->scaledSize.isValid() || d->scaledClipRect.isValid()); + bool xform = + (d->clipRect.isValid() || d->scaledSize.isValid() || d->scaledClipRect.isValid()); QSize finalSize = d->defaultSize; QRectF bounds; if (xform && !d->defaultSize.isEmpty()) { - bounds = QRectF(QPointF(0,0), QSizeF(d->defaultSize)); + bounds = QRectF(QPointF(0, 0), QSizeF(d->defaultSize)); QPoint tr1, tr2; QSizeF sc(1, 1); if (d->clipRect.isValid()) { @@ -205,15 +208,15 @@ bool QSvgIOHandler::read(QImage *image) #if 0 d->r.render(&p, bounds); #else - //qreal xs = size.isValid() ? size.width() / ww : 1.0; - //qreal ys = size.isValid() ? size.height() / hh : 1.0; - //p.scale(xs, ys); + // qreal xs = size.isValid() ? size.width() / ww : 1.0; + // qreal ys = size.isValid() ? size.height() / hh : 1.0; + // p.scale(xs, ys); // the best quality p.setRenderHint(QPainter::Antialiasing); p.setRenderHint(QPainter::TextAntialiasing); p.setRenderHint(QPainter::SmoothPixmapTransform); - p.setOpacity(0); // important to keep transparent background + p.setOpacity(0);// important to keep transparent background d->webView.page()->mainFrame()->render(&p); #endif p.end(); @@ -228,73 +231,72 @@ bool QSvgIOHandler::read(QImage *image) QVariant QSvgIOHandler::option(ImageOption option) const { - switch(option) { - case ImageFormat: - return QImage::Format_ARGB32_Premultiplied; - break; - case Size: - d->load(device()); - return d->defaultSize; - break; - case ClipRect: - return d->clipRect; - break; - case ScaledSize: - return d->scaledSize; - break; - case ScaledClipRect: - return d->scaledClipRect; - break; - case BackgroundColor: - return d->backColor; - break; - default: - break; + switch (option) { + case ImageFormat: + return QImage::Format_ARGB32_Premultiplied; + break; + case Size: + d->load(device()); + return d->defaultSize; + break; + case ClipRect: + return d->clipRect; + break; + case ScaledSize: + return d->scaledSize; + break; + case ScaledClipRect: + return d->scaledClipRect; + break; + case BackgroundColor: + return d->backColor; + break; + default: + break; } return QVariant(); } -void QSvgIOHandler::setOption(ImageOption option, const QVariant & value) +void QSvgIOHandler::setOption(ImageOption option, const QVariant& value) { - switch(option) { - case ClipRect: - d->clipRect = value.toRect(); - break; - case ScaledSize: - d->scaledSize = value.toSize(); - break; - case ScaledClipRect: - d->scaledClipRect = value.toRect(); - break; - case BackgroundColor: - d->backColor = value.value(); - break; - default: - break; + switch (option) { + case ClipRect: + d->clipRect = value.toRect(); + break; + case ScaledSize: + d->scaledSize = value.toSize(); + break; + case ScaledClipRect: + d->scaledClipRect = value.toRect(); + break; + case BackgroundColor: + d->backColor = value.value(); + break; + default: + break; } } bool QSvgIOHandler::supportsOption(ImageOption option) const { - switch(option) - { - case ImageFormat: - case Size: - case ClipRect: - case ScaledSize: - case ScaledClipRect: - case BackgroundColor: - return true; - default: - break; + switch (option) { + case ImageFormat: + case Size: + case ClipRect: + case ScaledSize: + case ScaledClipRect: + case BackgroundColor: + return true; + default: + break; } return false; } -bool QSvgIOHandler::canRead(QIODevice *device) +bool QSvgIOHandler::canRead(QIODevice* device) { QByteArray buf = device->peek(8); return buf.startsWith("\x1f\x8b") || buf.contains(" #include #include #include @@ -33,6 +32,7 @@ #include #include #include +#include #include #include "customwidgets.h" @@ -40,8 +40,8 @@ using namespace Gui; -UrlLabel::UrlLabel ( QWidget * parent, Qt::WindowFlags f ) - : QLabel("TextLabel", parent, f) +UrlLabel::UrlLabel(QWidget* parent, Qt::WindowFlags f) + : QLabel("TextLabel", parent, f) { _url = "http://localhost"; setToolTip(this->_url); @@ -49,13 +49,12 @@ UrlLabel::UrlLabel ( QWidget * parent, Qt::WindowFlags f ) } UrlLabel::~UrlLabel() -{ -} +{} -void UrlLabel::mouseReleaseEvent ( QMouseEvent * ) +void UrlLabel::mouseReleaseEvent(QMouseEvent*) { - QMessageBox::information(this, "Browser", - QString("This starts your browser with url %1").arg(_url)); + QMessageBox::information( + this, "Browser", QString("This starts your browser with url %1").arg(_url)); } QString UrlLabel::url() const @@ -69,8 +68,8 @@ void UrlLabel::setUrl(const QString& u) setToolTip(this->_url); } -LocationWidget::LocationWidget (QWidget * parent) - : QWidget(parent) +LocationWidget::LocationWidget(QWidget* parent) + : QWidget(parent) { box = new QGridLayout(); @@ -108,12 +107,11 @@ LocationWidget::LocationWidget (QWidget * parent) } LocationWidget::~LocationWidget() -{ -} +{} QSize LocationWidget::sizeHint() const { - return QSize(150,100); + return QSize(150, 100); } void LocationWidget::changeEvent(QEvent* e) @@ -130,57 +128,60 @@ void LocationWidget::retranslateUi() yLabel->setText(QApplication::translate("Gui::LocationWidget", "Y:")); zLabel->setText(QApplication::translate("Gui::LocationWidget", "Z:")); dLabel->setText(QApplication::translate("Gui::LocationWidget", "Direction:")); -} +} -FileChooser::FileChooser( QWidget *parent ) - : QWidget( parent ), md( File ), _filter( QString() ) +FileChooser::FileChooser(QWidget* parent) + : QWidget(parent), + md(File), + _filter(QString()) { - QHBoxLayout *layout = new QHBoxLayout( this ); - layout->setContentsMargins( 0, 0, 0, 0 ); - layout->setSpacing( 6 ); + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->setSpacing(6); - lineEdit = new QLineEdit( this ); - layout->addWidget( lineEdit ); + lineEdit = new QLineEdit(this); + layout->addWidget(lineEdit); connect(lineEdit, &QLineEdit::textChanged, this, &FileChooser::fileNameChanged); - button = new QPushButton( "...", this ); + button = new QPushButton("...", this); #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) button->setFixedWidth(2 * button->fontMetrics().horizontalAdvance(" ... ")); #else - button->setFixedWidth(2*button->fontMetrics().width( " ... " )); + button->setFixedWidth(2 * button->fontMetrics().width(" ... ")); #endif - layout->addWidget( button ); + layout->addWidget(button); connect(button, &QPushButton::clicked, this, &FileChooser::chooseFile); - setFocusProxy( lineEdit ); + setFocusProxy(lineEdit); } FileChooser::~FileChooser() -{ -} +{} QString FileChooser::fileName() const { return lineEdit->text(); } -void FileChooser::setFileName( const QString &fn ) +void FileChooser::setFileName(const QString& fn) { - lineEdit->setText( fn ); + lineEdit->setText(fn); } void FileChooser::chooseFile() { QFileDialog::Options dlgOpt = QFileDialog::DontUseNativeDialog; QString fn; - if ( mode() == File ) { - fn = QFileDialog::getOpenFileName(this, tr("Select a file"), - lineEdit->text(), _filter,0,dlgOpt); - } else { + if (mode() == File) { + fn = QFileDialog::getOpenFileName( + this, tr("Select a file"), lineEdit->text(), _filter, 0, dlgOpt); + } + else { QFileDialog::Options option = QFileDialog::ShowDirsOnly | dlgOpt; - fn = QFileDialog::getExistingDirectory( this, tr( "Select a directory" ), lineEdit->text(),option ); + fn = QFileDialog::getExistingDirectory( + this, tr("Select a directory"), lineEdit->text(), option); } if (!fn.isEmpty()) { @@ -194,7 +195,7 @@ FileChooser::Mode FileChooser::mode() const return md; } -void FileChooser::setMode( Mode m ) +void FileChooser::setMode(Mode m) { md = m; } @@ -204,20 +205,20 @@ QString FileChooser::filter() const return _filter; } -void FileChooser::setFilter ( const QString& filter ) +void FileChooser::setFilter(const QString& filter) { _filter = filter; } -void FileChooser::setButtonText( const QString& txt ) +void FileChooser::setButtonText(const QString& txt) { - button->setText( txt ); + button->setText(txt); #if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0) int w1 = 2 * button->fontMetrics().horizontalAdvance(txt); int w2 = 2 * button->fontMetrics().horizontalAdvance(" ... "); #else int w1 = 2 * button->fontMetrics().width(txt); - int w2 = 2*button->fontMetrics().width(" ... "); + int w2 = 2 * button->fontMetrics().width(" ... "); #endif button->setFixedWidth((w1 > w2 ? w1 : w2)); } @@ -229,44 +230,42 @@ QString FileChooser::buttonText() const // ------------------------------------------------------------------------------ -PrefFileChooser::PrefFileChooser ( QWidget * parent ) - : FileChooser(parent) -{ -} +PrefFileChooser::PrefFileChooser(QWidget* parent) + : FileChooser(parent) +{} PrefFileChooser::~PrefFileChooser() -{ -} +{} -QByteArray PrefFileChooser::entryName () const +QByteArray PrefFileChooser::entryName() const { return m_sPrefName; } -QByteArray PrefFileChooser::paramGrpPath () const +QByteArray PrefFileChooser::paramGrpPath() const { return m_sPrefGrp; } -void PrefFileChooser::setEntryName ( const QByteArray& name ) +void PrefFileChooser::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefFileChooser::setParamGrpPath ( const QByteArray& name ) +void PrefFileChooser::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } // -------------------------------------------------------------------- -AccelLineEdit::AccelLineEdit ( QWidget * parent ) - : QLineEdit(parent) +AccelLineEdit::AccelLineEdit(QWidget* parent) + : QLineEdit(parent) { setText(tr("none")); } -void AccelLineEdit::keyPressEvent ( QKeyEvent * e) +void AccelLineEdit::keyPressEvent(QKeyEvent* e) { QString txt; setText(tr("none")); @@ -274,72 +273,63 @@ void AccelLineEdit::keyPressEvent ( QKeyEvent * e) int key = e->key(); Qt::KeyboardModifiers state = e->modifiers(); - if ( key == Qt::Key_Control ) + if (key == Qt::Key_Control) return; - else if ( key == Qt::Key_Shift ) + else if (key == Qt::Key_Shift) return; - else if ( key == Qt::Key_Alt ) + else if (key == Qt::Key_Alt) return; - else if ( state == Qt::NoModifier && key == Qt::Key_Backspace ) - return; // clears the edit field + else if (state == Qt::NoModifier && key == Qt::Key_Backspace) + return;// clears the edit field - switch( state ) - { - case Qt::ControlModifier: - { - QKeySequence keyseq(Qt::CTRL+key); + switch (state) { + case Qt::ControlModifier: { + QKeySequence keyseq(Qt::CTRL + key); txt += keyseq.toString(QKeySequence::NativeText); setText(txt); - } break; - case Qt::AltModifier: - { - QKeySequence keyseq(Qt::ALT+key); + } break; + case Qt::AltModifier: { + QKeySequence keyseq(Qt::ALT + key); txt += keyseq.toString(QKeySequence::NativeText); setText(txt); - } break; - case Qt::ShiftModifier: - { - QKeySequence keyseq(Qt::SHIFT+key); + } break; + case Qt::ShiftModifier: { + QKeySequence keyseq(Qt::SHIFT + key); txt += keyseq.toString(QKeySequence::NativeText); setText(txt); - } break; - case Qt::ControlModifier+Qt::AltModifier: - { - QKeySequence keyseq(Qt::CTRL+Qt::ALT+key); + } break; + case Qt::ControlModifier + Qt::AltModifier: { + QKeySequence keyseq(Qt::CTRL + Qt::ALT + key); txt += keyseq.toString(QKeySequence::NativeText); setText(txt); - } break; - case Qt::ControlModifier+Qt::ShiftModifier: - { - QKeySequence keyseq(Qt::CTRL+Qt::SHIFT+key); + } break; + case Qt::ControlModifier + Qt::ShiftModifier: { + QKeySequence keyseq(Qt::CTRL + Qt::SHIFT + key); txt += keyseq.toString(QKeySequence::NativeText); setText(txt); - } break; - case Qt::ShiftModifier+Qt::AltModifier: - { - QKeySequence keyseq(Qt::SHIFT+Qt::ALT+key); + } break; + case Qt::ShiftModifier + Qt::AltModifier: { + QKeySequence keyseq(Qt::SHIFT + Qt::ALT + key); txt += keyseq.toString(QKeySequence::NativeText); setText(txt); - } break; - case Qt::ControlModifier+Qt::AltModifier+Qt::ShiftModifier: - { - QKeySequence keyseq(Qt::CTRL+Qt::ALT+Qt::SHIFT+key); + } break; + case Qt::ControlModifier + Qt::AltModifier + Qt::ShiftModifier: { + QKeySequence keyseq(Qt::CTRL + Qt::ALT + Qt::SHIFT + key); txt += keyseq.toString(QKeySequence::NativeText); setText(txt); - } break; - default: - { + } break; + default: { QKeySequence keyseq(key); txt += keyseq.toString(QKeySequence::NativeText); setText(txt); - } break; + } break; } } // ------------------------------------------------------------------------------ ActionSelector::ActionSelector(QWidget* parent) - : QWidget(parent) + : QWidget(parent) { addButton = new QPushButton(this); addButton->setMinimumSize(QSize(30, 30)); @@ -421,27 +411,24 @@ ActionSelector::ActionSelector(QWidget* parent) } ActionSelector::~ActionSelector() -{ -} +{} // -------------------------------------------------------------------- -InputField::InputField (QWidget * parent) - : QLineEdit(parent), - Value(0), - Maximum(INT_MAX), - Minimum(-INT_MAX), - StepSize(1.0), - HistorySize(5) -{ -} +InputField::InputField(QWidget* parent) + : QLineEdit(parent), + Value(0), + Maximum(INT_MAX), + Minimum(-INT_MAX), + StepSize(1.0), + HistorySize(5) +{} InputField::~InputField() -{ -} +{} /** Sets the preference path to \a path. */ -void InputField::setParamGrpPath( const QByteArray& path ) +void InputField::setParamGrpPath(const QByteArray& path) { m_sPrefGrp = path; } @@ -466,36 +453,36 @@ double InputField::getQuantity() const } /// get the value of the singleStep property -double InputField::singleStep(void)const +double InputField::singleStep(void) const { return StepSize; } -/// set the value of the singleStep property +/// set the value of the singleStep property void InputField::setSingleStep(double s) { StepSize = s; } /// get the value of the maximum property -double InputField::maximum(void)const +double InputField::maximum(void) const { return Maximum; } -/// set the value of the maximum property +/// set the value of the maximum property void InputField::setMaximum(double m) { Maximum = m; } /// get the value of the minimum property -double InputField::minimum(void)const +double InputField::minimum(void) const { return Minimum; } -/// set the value of the minimum property +/// set the value of the minimum property void InputField::setMinimum(double m) { Minimum = m; @@ -513,12 +500,12 @@ QString InputField::getUnitText(void) } // get the value of the minimum property -int InputField::historySize(void)const +int InputField::historySize(void) const { return HistorySize; } -// set the value of the minimum property +// set the value of the minimum property void InputField::setHistorySize(int i) { HistorySize = i; @@ -526,30 +513,27 @@ void InputField::setHistorySize(int i) // -------------------------------------------------------------------- -namespace Base { - -Unit::Unit() +namespace Base { -} +Unit::Unit() +{} Unit::Unit(const QString& u) : unit(u) -{ - -} +{} bool Unit::isEmpty() const { return unit.isEmpty(); } -bool Unit::operator ==(const Unit& that) +bool Unit::operator==(const Unit& that) { return this->unit == that.unit; } -bool Unit::operator !=(const Unit& that) +bool Unit::operator!=(const Unit& that) { return this->unit != that.unit; } @@ -559,44 +543,39 @@ const QString& Unit::getString() const return unit; } -int QuantityFormat::defaultDenominator = 8; // for 1/8" +int QuantityFormat::defaultDenominator = 8;// for 1/8" QuantityFormat::QuantityFormat() - : option(OmitGroupSeparator | RejectGroupSeparator) - , format(Fixed) - , precision(4) - , denominator(defaultDenominator) -{ -} + : option(OmitGroupSeparator | RejectGroupSeparator), + format(Fixed), + precision(4), + denominator(defaultDenominator) +{} Quantity::Quantity() - : value(0) - , unit() -{ - -} + : value(0), + unit() +{} Quantity::Quantity(double v, const Unit& u) - : value(v) - , unit(u) -{ - -} + : value(v), + unit(u) +{} Quantity Quantity::parse(const QString& str) { bool ok; QString txt = str; QString unit; - while (!txt.isEmpty() && txt[txt.length()-1].isLetter()) { - unit.prepend(txt[txt.length()-1]); + while (!txt.isEmpty() && txt[txt.length() - 1].isLetter()) { + unit.prepend(txt[txt.length() - 1]); txt.chop(1); } double v = QLocale::system().toDouble(txt, &ok); - //if (!ok && !txt.isEmpty()) - // throw Base::Exception(); + // if (!ok && !txt.isEmpty()) + // throw Base::Exception(); return Quantity(v, Unit(unit)); } @@ -649,27 +628,26 @@ QString Quantity::getUserString(double& factor, QString& unitString) const return QString::fromUtf8("%1 %2").arg(Ln, unit.getString()); } -} +}// namespace Base -namespace Gui { +namespace Gui +{ class QuantitySpinBoxPrivate { public: - QuantitySpinBoxPrivate() : - validInput(true), - pendingEmit(false), - unitValue(0), - maximum(INT_MAX), - minimum(-INT_MAX), - singleStep(1.0) - { - } + QuantitySpinBoxPrivate() + : validInput(true), + pendingEmit(false), + unitValue(0), + maximum(INT_MAX), + minimum(-INT_MAX), + singleStep(1.0) + {} ~QuantitySpinBoxPrivate() - { - } + {} - QString stripped(const QString &t, int *pos) const + QString stripped(const QString& t, int* pos) const { QString text = t; const int s = text.size(); @@ -721,46 +699,47 @@ public: const bool minus = min <= 0; switch (len) { - case 0: - state = max != min ? QValidator::Intermediate : QValidator::Invalid; - goto end; - case 1: - if (copy.at(0) == locale.decimalPoint()) { - state = QValidator::Intermediate; - copy.prepend(QLatin1Char('0')); - pos++; - len++; + case 0: + state = max != min ? QValidator::Intermediate : QValidator::Invalid; goto end; - } - else if (copy.at(0) == QLatin1Char('+')) { - // the quantity parser doesn't allow numbers of the form '+1.0' - state = QValidator::Invalid; - goto end; - } - else if (copy.at(0) == QLatin1Char('-')) { - if (minus) + case 1: + if (copy.at(0) == locale.decimalPoint()) { state = QValidator::Intermediate; - else + copy.prepend(QLatin1Char('0')); + pos++; + len++; + goto end; + } + else if (copy.at(0) == QLatin1Char('+')) { + // the quantity parser doesn't allow numbers of the form '+1.0' state = QValidator::Invalid; - goto end; - } - break; - case 2: - if (copy.at(1) == locale.decimalPoint() - && (plus && copy.at(0) == QLatin1Char('+'))) { - state = QValidator::Intermediate; - goto end; - } - if (copy.at(1) == locale.decimalPoint() - && (minus && copy.at(0) == QLatin1Char('-'))) { - state = QValidator::Intermediate; - copy.insert(1, QLatin1Char('0')); - pos++; - len++; - goto end; - } - break; - default: break; + goto end; + } + else if (copy.at(0) == QLatin1Char('-')) { + if (minus) + state = QValidator::Intermediate; + else + state = QValidator::Invalid; + goto end; + } + break; + case 2: + if (copy.at(1) == locale.decimalPoint() + && (plus && copy.at(0) == QLatin1Char('+'))) { + state = QValidator::Intermediate; + goto end; + } + if (copy.at(1) == locale.decimalPoint() + && (minus && copy.at(0) == QLatin1Char('-'))) { + state = QValidator::Intermediate; + copy.insert(1, QLatin1Char('0')); + pos++; + len++; + goto end; + } + break; + default: + break; } { @@ -770,7 +749,7 @@ public: } else if (len > 1) { bool decOccurred = false; - for (int i = 0; i 0 ? min : max); } @@ -859,9 +839,9 @@ end: double minimum; double singleStep; }; -} +}// namespace Gui -QuantitySpinBox::QuantitySpinBox(QWidget *parent) +QuantitySpinBox::QuantitySpinBox(QWidget* parent) : QAbstractSpinBox(parent), d_ptr(new QuantitySpinBoxPrivate()) { @@ -872,27 +852,26 @@ QuantitySpinBox::QuantitySpinBox(QWidget *parent) } QuantitySpinBox::~QuantitySpinBox() -{ -} +{} -void QuantitySpinBox::resizeEvent(QResizeEvent * event) +void QuantitySpinBox::resizeEvent(QResizeEvent* event) { QAbstractSpinBox::resizeEvent(event); } -void Gui::QuantitySpinBox::keyPressEvent(QKeyEvent *event) +void Gui::QuantitySpinBox::keyPressEvent(QKeyEvent* event) { QAbstractSpinBox::keyPressEvent(event); } -void QuantitySpinBox::updateText(const Base::Quantity &quant) +void QuantitySpinBox::updateText(const Base::Quantity& quant) { Q_D(QuantitySpinBox); double dFactor; QString txt = getUserString(quant, dFactor, d->unitStr); - d->unitValue = quant.getValue()/dFactor; + d->unitValue = quant.getValue() / dFactor; lineEdit()->setText(txt); handlePendingEmit(); } @@ -937,7 +916,7 @@ bool QuantitySpinBox::hasValidInput() const } // Gets called after call of 'validateAndInterpret' -void QuantitySpinBox::userInput(const QString & text) +void QuantitySpinBox::userInput(const QString& text) { Q_D(QuantitySpinBox); @@ -994,7 +973,7 @@ Base::Unit QuantitySpinBox::unit() const return d->unit; } -void QuantitySpinBox::setUnit(const Base::Unit &unit) +void QuantitySpinBox::setUnit(const Base::Unit& unit) { Q_D(QuantitySpinBox); @@ -1086,7 +1065,8 @@ void QuantitySpinBox::clearSchema() updateText(d->quantity); } -QString QuantitySpinBox::getUserString(const Base::Quantity& val, double& factor, QString& unitString) const +QString QuantitySpinBox::getUserString(const Base::Quantity& val, double& factor, + QString& unitString) const { return val.getUserString(factor, unitString); } @@ -1099,7 +1079,7 @@ QString QuantitySpinBox::getUserString(const Base::Quantity& val) const QAbstractSpinBox::StepEnabled QuantitySpinBox::stepEnabled() const { Q_D(const QuantitySpinBox); - if (isReadOnly()/* || !d->validInput*/) + if (isReadOnly() /* || !d->validInput*/) return StepNone; if (wrapping()) return StepEnabled(StepUpEnabled | StepDownEnabled); @@ -1151,7 +1131,7 @@ QSize QuantitySpinBox::sizeHint() const w = fm.width(s); #endif - w += 2; // cursor blinking space + w += 2;// cursor blinking space w += iconHeight; QStyleOptionSpinBox opt; @@ -1181,7 +1161,7 @@ QSize QuantitySpinBox::minimumSizeHint() const w = fm.width(s); #endif - w += 2; // cursor blinking space + w += 2;// cursor blinking space w += iconHeight; QStyleOptionSpinBox opt; @@ -1191,7 +1171,7 @@ QSize QuantitySpinBox::minimumSizeHint() const return size; } -void QuantitySpinBox::showEvent(QShowEvent * event) +void QuantitySpinBox::showEvent(QShowEvent* event) { Q_D(QuantitySpinBox); @@ -1203,19 +1183,19 @@ void QuantitySpinBox::showEvent(QShowEvent * event) selectNumber(); } -void QuantitySpinBox::hideEvent(QHideEvent * event) +void QuantitySpinBox::hideEvent(QHideEvent* event) { handlePendingEmit(); QAbstractSpinBox::hideEvent(event); } -void QuantitySpinBox::closeEvent(QCloseEvent * event) +void QuantitySpinBox::closeEvent(QCloseEvent* event) { handlePendingEmit(); QAbstractSpinBox::closeEvent(event); } -bool QuantitySpinBox::event(QEvent * event) +bool QuantitySpinBox::event(QEvent* event) { // issue #0004059: Tooltips for Gui::QuantitySpinBox not showing // Here we must not try to show the tooltip of the icon label @@ -1241,21 +1221,20 @@ bool QuantitySpinBox::event(QEvent * event) return QAbstractSpinBox::event(event); } -void QuantitySpinBox::focusInEvent(QFocusEvent * event) +void QuantitySpinBox::focusInEvent(QFocusEvent* event) { bool hasSel = lineEdit()->hasSelectedText(); QAbstractSpinBox::focusInEvent(event); - if (event->reason() == Qt::TabFocusReason || - event->reason() == Qt::BacktabFocusReason || - event->reason() == Qt::ShortcutFocusReason) { + if (event->reason() == Qt::TabFocusReason || event->reason() == Qt::BacktabFocusReason + || event->reason() == Qt::ShortcutFocusReason) { if (!hasSel) selectNumber(); } } -void QuantitySpinBox::focusOutEvent(QFocusEvent * event) +void QuantitySpinBox::focusOutEvent(QFocusEvent* event) { Q_D(QuantitySpinBox); @@ -1281,11 +1260,11 @@ void QuantitySpinBox::clear() void QuantitySpinBox::selectNumber() { QString expr = QString::fromLatin1("^([%1%2]?[0-9\\%3]*)\\%4?([0-9]+(%5[%1%2]?[0-9]+)?)") - .arg(locale().negativeSign()) - .arg(locale().positiveSign()) - .arg(locale().groupSeparator()) - .arg(locale().decimalPoint()) - .arg(locale().exponential()); + .arg(locale().negativeSign()) + .arg(locale().positiveSign()) + .arg(locale().groupSeparator()) + .arg(locale().decimalPoint()) + .arg(locale().exponential()); auto rmatch = QRegularExpression(expr).match(lineEdit()->text()); if (rmatch.hasMatch()) { lineEdit()->setSelection(0, rmatch.capturedLength()); @@ -1303,7 +1282,7 @@ QString QuantitySpinBox::textFromValue(const Base::Quantity& value) const return str; } -Base::Quantity QuantitySpinBox::valueFromText(const QString &text) const +Base::Quantity QuantitySpinBox::valueFromText(const QString& text) const { Q_D(const QuantitySpinBox); @@ -1319,7 +1298,7 @@ Base::Quantity QuantitySpinBox::valueFromText(const QString &text) const return quant; } -QValidator::State QuantitySpinBox::validate(QString &text, int &pos) const +QValidator::State QuantitySpinBox::validate(QString& text, int& pos) const { Q_D(const QuantitySpinBox); @@ -1328,38 +1307,36 @@ QValidator::State QuantitySpinBox::validate(QString &text, int &pos) const return state; } -void QuantitySpinBox::fixup(QString &input) const +void QuantitySpinBox::fixup(QString& input) const { input.remove(locale().groupSeparator()); } // ------------------------------------------------------------------------------ -PrefUnitSpinBox::PrefUnitSpinBox ( QWidget * parent ) - : QuantitySpinBox(parent) -{ -} +PrefUnitSpinBox::PrefUnitSpinBox(QWidget* parent) + : QuantitySpinBox(parent) +{} PrefUnitSpinBox::~PrefUnitSpinBox() -{ -} +{} -QByteArray PrefUnitSpinBox::entryName () const +QByteArray PrefUnitSpinBox::entryName() const { return m_sPrefName; } -QByteArray PrefUnitSpinBox::paramGrpPath () const +QByteArray PrefUnitSpinBox::paramGrpPath() const { return m_sPrefGrp; } -void PrefUnitSpinBox::setEntryName ( const QByteArray& name ) +void PrefUnitSpinBox::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefUnitSpinBox::setParamGrpPath ( const QByteArray& name ) +void PrefUnitSpinBox::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } @@ -1368,12 +1345,10 @@ void PrefUnitSpinBox::setParamGrpPath ( const QByteArray& name ) PrefQuantitySpinBox::PrefQuantitySpinBox(QWidget* parent) : QuantitySpinBox(parent) -{ -} +{} PrefQuantitySpinBox::~PrefQuantitySpinBox() -{ -} +{} QByteArray PrefQuantitySpinBox::entryName() const { @@ -1397,17 +1372,16 @@ void PrefQuantitySpinBox::setParamGrpPath(const QByteArray& name) // -------------------------------------------------------------------- -CommandIconView::CommandIconView ( QWidget * parent ) - : QListWidget(parent) +CommandIconView::CommandIconView(QWidget* parent) + : QListWidget(parent) { connect(this, &QListWidget::currentItemChanged, this, &CommandIconView::onSelectionChanged); } -CommandIconView::~CommandIconView () -{ -} +CommandIconView::~CommandIconView() +{} -void CommandIconView::startDrag ( Qt::DropActions /*supportedActions*/ ) +void CommandIconView::startDrag(Qt::DropActions /*supportedActions*/) { QList items = selectedItems(); QByteArray itemData; @@ -1421,17 +1395,17 @@ void CommandIconView::startDrag ( Qt::DropActions /*supportedActions*/ ) dataStream << (*it)->text(); } - QMimeData *mimeData = new QMimeData; + QMimeData* mimeData = new QMimeData; mimeData->setData("text/x-action-items", itemData); - QDrag *drag = new QDrag(this); + QDrag* drag = new QDrag(this); drag->setMimeData(mimeData); drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2)); drag->setPixmap(pixmap); drag->exec(Qt::MoveAction); } -void CommandIconView::onSelectionChanged(QListWidgetItem * item, QListWidgetItem *) +void CommandIconView::onSelectionChanged(QListWidgetItem* item, QListWidgetItem*) { if (item) emitSelectionChanged(item->toolTip()); @@ -1439,135 +1413,144 @@ void CommandIconView::onSelectionChanged(QListWidgetItem * item, QListWidgetItem // ------------------------------------------------------------------------------ -namespace Gui { +namespace Gui +{ -class UnsignedValidator : public QValidator +class UnsignedValidator: public QValidator { public: - UnsignedValidator( QObject * parent ); - UnsignedValidator( uint minimum, uint maximum, QObject * parent ); + UnsignedValidator(QObject* parent); + UnsignedValidator(uint minimum, uint maximum, QObject* parent); ~UnsignedValidator(); - QValidator::State validate( QString &, int & ) const; + QValidator::State validate(QString&, int&) const; - void setBottom( uint ); - void setTop( uint ); - virtual void setRange( uint bottom, uint top ); + void setBottom(uint); + void setTop(uint); + virtual void setRange(uint bottom, uint top); - uint bottom() const { return b; } - uint top() const { return t; } + uint bottom() const + { + return b; + } + uint top() const + { + return t; + } private: uint b, t; }; -UnsignedValidator::UnsignedValidator( QObject * parent ) - : QValidator( parent ) +UnsignedValidator::UnsignedValidator(QObject* parent) + : QValidator(parent) { - b = 0; - t = UINT_MAX; + b = 0; + t = UINT_MAX; } -UnsignedValidator::UnsignedValidator( uint minimum, uint maximum, QObject * parent ) - : QValidator( parent ) +UnsignedValidator::UnsignedValidator(uint minimum, uint maximum, QObject* parent) + : QValidator(parent) { b = minimum; t = maximum; } UnsignedValidator::~UnsignedValidator() -{ +{} -} - -QValidator::State UnsignedValidator::validate( QString & input, int & ) const +QValidator::State UnsignedValidator::validate(QString& input, int&) const { QString stripped;// = input.stripWhiteSpace(); - if ( stripped.isEmpty() ) + if (stripped.isEmpty()) return Intermediate; bool ok; - uint entered = input.toUInt( &ok ); - if ( !ok ) + uint entered = input.toUInt(&ok); + if (!ok) return Invalid; - else if ( entered < b ) + else if (entered < b) return Intermediate; - else if ( entered > t ) + else if (entered > t) return Invalid; -// else if ( entered < b || entered > t ) -// return Invalid; + // else if ( entered < b || entered > t ) + // return Invalid; else return Acceptable; } -void UnsignedValidator::setRange( uint minimum, uint maximum ) +void UnsignedValidator::setRange(uint minimum, uint maximum) { b = minimum; t = maximum; } -void UnsignedValidator::setBottom( uint bottom ) +void UnsignedValidator::setBottom(uint bottom) { - setRange( bottom, top() ); + setRange(bottom, top()); } -void UnsignedValidator::setTop( uint top ) +void UnsignedValidator::setTop(uint top) { - setRange( bottom(), top ); + setRange(bottom(), top); } class UIntSpinBoxPrivate { public: - UnsignedValidator * mValidator; + UnsignedValidator* mValidator; - UIntSpinBoxPrivate() : mValidator(0) - { - } - uint mapToUInt( int v ) const + UIntSpinBoxPrivate() + : mValidator(0) + {} + uint mapToUInt(int v) const { uint ui; - if ( v == INT_MIN ) { + if (v == INT_MIN) { ui = 0; } - else if ( v == INT_MAX ) { + else if (v == INT_MAX) { ui = UINT_MAX; } - else if ( v < 0 ) { - v -= INT_MIN; ui = (uint)v; + else if (v < 0) { + v -= INT_MIN; + ui = (uint)v; } else { - ui = (uint)v; ui -= INT_MIN; + ui = (uint)v; + ui -= INT_MIN; } return ui; } - int mapToInt( uint v ) const + int mapToInt(uint v) const { int in; - if ( v == UINT_MAX ) { + if (v == UINT_MAX) { in = INT_MAX; } - else if ( v == 0 ) { + else if (v == 0) { in = INT_MIN; } - else if ( v > INT_MAX ) { - v += INT_MIN; in = (int)v; + else if (v > INT_MAX) { + v += INT_MIN; + in = (int)v; } else { - in = v; in += INT_MIN; + in = v; + in += INT_MIN; } return in; } }; -} // namespace Gui +}// namespace Gui // ------------------------------------------------------------- -UIntSpinBox::UIntSpinBox (QWidget* parent) - : QSpinBox (parent) +UIntSpinBox::UIntSpinBox(QWidget* parent) + : QSpinBox(parent) { d = new UIntSpinBoxPrivate; - d->mValidator = new UnsignedValidator(this->minimum(), this->maximum(), this); + d->mValidator = new UnsignedValidator(this->minimum(), this->maximum(), this); connect(this, qOverload(&QSpinBox::valueChanged), this, &UIntSpinBox::valueChange); setRange(0, 99); setValue(0); @@ -1577,7 +1560,8 @@ UIntSpinBox::UIntSpinBox (QWidget* parent) UIntSpinBox::~UIntSpinBox() { delete d->mValidator; - delete d; d = 0; + delete d; + d = 0; } void UIntSpinBox::setRange(uint minVal, uint maxVal) @@ -1588,7 +1572,7 @@ void UIntSpinBox::setRange(uint minVal, uint maxVal) updateValidator(); } -QValidator::State UIntSpinBox::validate (QString & input, int & pos) const +QValidator::State UIntSpinBox::validate(QString& input, int& pos) const { return d->mValidator->validate(input, pos); } @@ -1634,7 +1618,7 @@ void UIntSpinBox::setMaximum(uint maxVal) setRange(minVal, maxVal); } -QString UIntSpinBox::textFromValue (int v) const +QString UIntSpinBox::textFromValue(int v) const { uint val = d->mapToUInt(v); QString s; @@ -1642,7 +1626,7 @@ QString UIntSpinBox::textFromValue (int v) const return s; } -int UIntSpinBox::valueFromText (const QString & text) const +int UIntSpinBox::valueFromText(const QString& text) const { bool ok; QString s = text; @@ -1655,7 +1639,7 @@ int UIntSpinBox::valueFromText (const QString & text) const return d->mapToInt(newVal); } -void UIntSpinBox::updateValidator() +void UIntSpinBox::updateValidator() { d->mValidator->setRange(this->minimum(), this->maximum()); } @@ -1663,42 +1647,37 @@ void UIntSpinBox::updateValidator() // -------------------------------------------------------------------- IntSpinBox::IntSpinBox(QWidget* parent) - : QSpinBox(parent) -{ -} + : QSpinBox(parent) +{} IntSpinBox::~IntSpinBox() -{ - -} +{} // -------------------------------------------------------------------- -PrefSpinBox::PrefSpinBox ( QWidget * parent ) - : QSpinBox(parent) -{ -} +PrefSpinBox::PrefSpinBox(QWidget* parent) + : QSpinBox(parent) +{} PrefSpinBox::~PrefSpinBox() -{ -} +{} -QByteArray PrefSpinBox::entryName () const +QByteArray PrefSpinBox::entryName() const { return m_sPrefName; } -QByteArray PrefSpinBox::paramGrpPath () const +QByteArray PrefSpinBox::paramGrpPath() const { return m_sPrefGrp; } -void PrefSpinBox::setEntryName ( const QByteArray& name ) +void PrefSpinBox::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefSpinBox::setParamGrpPath ( const QByteArray& name ) +void PrefSpinBox::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } @@ -1706,41 +1685,37 @@ void PrefSpinBox::setParamGrpPath ( const QByteArray& name ) // -------------------------------------------------------------------- DoubleSpinBox::DoubleSpinBox(QWidget* parent) - : QDoubleSpinBox(parent) -{ -} + : QDoubleSpinBox(parent) +{} DoubleSpinBox::~DoubleSpinBox() -{ -} +{} // -------------------------------------------------------------------- -PrefDoubleSpinBox::PrefDoubleSpinBox ( QWidget * parent ) - : QDoubleSpinBox(parent) -{ -} +PrefDoubleSpinBox::PrefDoubleSpinBox(QWidget* parent) + : QDoubleSpinBox(parent) +{} PrefDoubleSpinBox::~PrefDoubleSpinBox() -{ -} +{} -QByteArray PrefDoubleSpinBox::entryName () const +QByteArray PrefDoubleSpinBox::entryName() const { return m_sPrefName; } -QByteArray PrefDoubleSpinBox::paramGrpPath () const +QByteArray PrefDoubleSpinBox::paramGrpPath() const { return m_sPrefGrp; } -void PrefDoubleSpinBox::setEntryName ( const QByteArray& name ) +void PrefDoubleSpinBox::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefDoubleSpinBox::setParamGrpPath ( const QByteArray& name ) +void PrefDoubleSpinBox::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } @@ -1748,20 +1723,19 @@ void PrefDoubleSpinBox::setParamGrpPath ( const QByteArray& name ) // ------------------------------------------------------------- ColorButton::ColorButton(QWidget* parent) - : QPushButton(parent) - , _allowChange(true) - , _allowTransparency(false) - , _drawFrame(true) + : QPushButton(parent), + _allowChange(true), + _allowTransparency(false), + _drawFrame(true) { - _col = palette().color(QPalette::Active,QPalette::Midlight); + _col = palette().color(QPalette::Active, QPalette::Midlight); connect(this, &ColorButton::clicked, this, &ColorButton::onChooseColor); } ColorButton::~ColorButton() -{ -} +{} -void ColorButton::setColor( const QColor& c ) +void ColorButton::setColor(const QColor& c) { _col = c; update(); @@ -1802,27 +1776,29 @@ bool ColorButton::drawFrame() const return _drawFrame; } -void ColorButton::paintEvent ( QPaintEvent * e ) +void ColorButton::paintEvent(QPaintEvent* e) { // first paint the complete button QPushButton::paintEvent(e); // repaint the rectangle area - QPalette::ColorGroup group = isEnabled() ? hasFocus() ? QPalette::Active : QPalette::Inactive : QPalette::Disabled; - QColor pen = palette().color(group,QPalette::ButtonText); + QPalette::ColorGroup group = + isEnabled() ? hasFocus() ? QPalette::Active : QPalette::Inactive : QPalette::Disabled; + QColor pen = palette().color(group, QPalette::ButtonText); { QPainter paint(this); - paint.setPen( pen ); + paint.setPen(pen); if (_drawFrame) { paint.setBrush(QBrush(_col)); - paint.drawRect(5, 5, width()-10, height()-10); - } else { - paint.fillRect(5, 5, width()-10, height()-10, QBrush(_col)); + paint.drawRect(5, 5, width() - 10, height() - 10); + } + else { + paint.fillRect(5, 5, width() - 10, height() - 10, QBrush(_col)); } } - // overpaint the rectangle to paint icon and text + // overpaint the rectangle to paint icon and text QStyleOptionButton opt; opt.init(this); opt.text = text(); @@ -1837,231 +1813,218 @@ void ColorButton::onChooseColor() { if (!_allowChange) return; - QColor c = QColorDialog::getColor( _col, this ); - if ( c.isValid() ) - { - setColor( c ); + QColor c = QColorDialog::getColor(_col, this); + if (c.isValid()) { + setColor(c); Q_EMIT changed(); } } // ------------------------------------------------------------------------------ -PrefColorButton::PrefColorButton ( QWidget * parent ) - : ColorButton(parent) -{ -} +PrefColorButton::PrefColorButton(QWidget* parent) + : ColorButton(parent) +{} PrefColorButton::~PrefColorButton() -{ -} +{} -QByteArray PrefColorButton::entryName () const +QByteArray PrefColorButton::entryName() const { return m_sPrefName; } -QByteArray PrefColorButton::paramGrpPath () const +QByteArray PrefColorButton::paramGrpPath() const { return m_sPrefGrp; } -void PrefColorButton::setEntryName ( const QByteArray& name ) +void PrefColorButton::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefColorButton::setParamGrpPath ( const QByteArray& name ) +void PrefColorButton::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } // -------------------------------------------------------------------- -PrefLineEdit::PrefLineEdit ( QWidget * parent ) - : QLineEdit(parent) -{ -} +PrefLineEdit::PrefLineEdit(QWidget* parent) + : QLineEdit(parent) +{} PrefLineEdit::~PrefLineEdit() -{ -} +{} -QByteArray PrefLineEdit::entryName () const +QByteArray PrefLineEdit::entryName() const { return m_sPrefName; } -QByteArray PrefLineEdit::paramGrpPath () const +QByteArray PrefLineEdit::paramGrpPath() const { return m_sPrefGrp; } -void PrefLineEdit::setEntryName ( const QByteArray& name ) +void PrefLineEdit::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefLineEdit::setParamGrpPath ( const QByteArray& name ) +void PrefLineEdit::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } // -------------------------------------------------------------------- -PrefComboBox::PrefComboBox ( QWidget * parent ) - : QComboBox(parent) +PrefComboBox::PrefComboBox(QWidget* parent) + : QComboBox(parent) { setEditable(false); } PrefComboBox::~PrefComboBox() -{ -} +{} -QByteArray PrefComboBox::entryName () const +QByteArray PrefComboBox::entryName() const { return m_sPrefName; } -QByteArray PrefComboBox::paramGrpPath () const +QByteArray PrefComboBox::paramGrpPath() const { return m_sPrefGrp; } -void PrefComboBox::setEntryName ( const QByteArray& name ) +void PrefComboBox::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefComboBox::setParamGrpPath ( const QByteArray& name ) +void PrefComboBox::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } // -------------------------------------------------------------------- -PrefCheckBox::PrefCheckBox ( QWidget * parent ) - : QCheckBox(parent) +PrefCheckBox::PrefCheckBox(QWidget* parent) + : QCheckBox(parent) { - setText("CheckBox"); + setText("CheckBox"); } PrefCheckBox::~PrefCheckBox() -{ -} +{} -QByteArray PrefCheckBox::entryName () const +QByteArray PrefCheckBox::entryName() const { return m_sPrefName; } -QByteArray PrefCheckBox::paramGrpPath () const +QByteArray PrefCheckBox::paramGrpPath() const { return m_sPrefGrp; } -void PrefCheckBox::setEntryName ( const QByteArray& name ) +void PrefCheckBox::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefCheckBox::setParamGrpPath ( const QByteArray& name ) +void PrefCheckBox::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } // -------------------------------------------------------------------- -PrefRadioButton::PrefRadioButton ( QWidget * parent ) - : QRadioButton(parent) +PrefRadioButton::PrefRadioButton(QWidget* parent) + : QRadioButton(parent) { setText("RadioButton"); } PrefRadioButton::~PrefRadioButton() -{ -} +{} -QByteArray PrefRadioButton::entryName () const +QByteArray PrefRadioButton::entryName() const { return m_sPrefName; } -QByteArray PrefRadioButton::paramGrpPath () const +QByteArray PrefRadioButton::paramGrpPath() const { return m_sPrefGrp; } -void PrefRadioButton::setEntryName ( const QByteArray& name ) +void PrefRadioButton::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefRadioButton::setParamGrpPath ( const QByteArray& name ) +void PrefRadioButton::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } // -------------------------------------------------------------------- -PrefSlider::PrefSlider ( QWidget * parent ) - : QSlider(parent) -{ -} +PrefSlider::PrefSlider(QWidget* parent) + : QSlider(parent) +{} PrefSlider::~PrefSlider() -{ -} +{} -QByteArray PrefSlider::entryName () const +QByteArray PrefSlider::entryName() const { return m_sPrefName; } -QByteArray PrefSlider::paramGrpPath () const +QByteArray PrefSlider::paramGrpPath() const { return m_sPrefGrp; } -void PrefSlider::setEntryName ( const QByteArray& name ) +void PrefSlider::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefSlider::setParamGrpPath ( const QByteArray& name ) +void PrefSlider::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } // -------------------------------------------------------------------- -PrefFontBox::PrefFontBox ( QWidget * parent ) - : QFontComboBox(parent) -{ -} +PrefFontBox::PrefFontBox(QWidget* parent) + : QFontComboBox(parent) +{} PrefFontBox::~PrefFontBox() -{ -} +{} -QByteArray PrefFontBox::entryName () const +QByteArray PrefFontBox::entryName() const { return m_sPrefName; } -QByteArray PrefFontBox::paramGrpPath () const +QByteArray PrefFontBox::paramGrpPath() const { return m_sPrefGrp; } -void PrefFontBox::setEntryName ( const QByteArray& name ) +void PrefFontBox::setEntryName(const QByteArray& name) { m_sPrefName = name; } -void PrefFontBox::setParamGrpPath ( const QByteArray& name ) +void PrefFontBox::setParamGrpPath(const QByteArray& name) { m_sPrefGrp = name; } - diff --git a/src/Tools/plugins/widget/customwidgets.h b/src/Tools/plugins/widget/customwidgets.h index 837ef45f84..11ea06ce2f 100644 --- a/src/Tools/plugins/widget/customwidgets.h +++ b/src/Tools/plugins/widget/customwidgets.h @@ -40,74 +40,86 @@ #include #include -namespace Base { - class Exception { - }; - class Unit{ - public: - Unit(); - Unit(const QString&); - bool isEmpty() const; - bool operator ==(const Unit&); - bool operator !=(const Unit&); - const QString& getString() const; +namespace Base +{ +class Exception +{ +}; +class Unit +{ +public: + Unit(); + Unit(const QString&); + bool isEmpty() const; + bool operator==(const Unit&); + bool operator!=(const Unit&); + const QString& getString() const; - private: - QString unit; +private: + QString unit; +}; + +struct QuantityFormat +{ + enum NumberOption + { + None = 0x00, + OmitGroupSeparator = 0x01, + RejectGroupSeparator = 0x02 + }; + enum NumberFormat + { + Default = 0, + Fixed = 1, + Scientific = 2 }; - struct QuantityFormat { - enum NumberOption { - None = 0x00, - OmitGroupSeparator = 0x01, - RejectGroupSeparator = 0x02 - }; - enum NumberFormat { - Default = 0, - Fixed = 1, - Scientific = 2 - }; + using NumberOptions = int; + NumberOptions option; + NumberFormat format; + int precision; + int denominator; - using NumberOptions = int; - NumberOptions option; - NumberFormat format; - int precision; - int denominator; + // Default denominator of minimum fractional inch. Only used in certain + // schemas. + static int defaultDenominator;// i.e 8 for 1/8" - // Default denominator of minimum fractional inch. Only used in certain - // schemas. - static int defaultDenominator; // i.e 8 for 1/8" + static inline int getDefaultDenominator() + { + return defaultDenominator; + } - static inline int getDefaultDenominator() { - return defaultDenominator; - } + static inline void setDefaultDenominator(int denom) + { + defaultDenominator = denom; + } - static inline void setDefaultDenominator(int denom) { - defaultDenominator = denom; - } + inline int getDenominator() const + { + return denominator; + } - inline int getDenominator() const { - return denominator; - } - - inline void setDenominator(int denom) { - denominator = denom; - } - QuantityFormat(); - inline char toFormat() const { - switch (format) { + inline void setDenominator(int denom) + { + denominator = denom; + } + QuantityFormat(); + inline char toFormat() const + { + switch (format) { case Fixed: return 'f'; case Scientific: return 'e'; default: return 'g'; - } } - static inline NumberFormat toFormat(char c, bool* ok = 0) { - if (ok) - *ok = true; - switch (c) { + } + static inline NumberFormat toFormat(char c, bool* ok = 0) + { + if (ok) + *ok = true; + switch (c) { case 'f': return Fixed; case 'e': @@ -118,67 +130,70 @@ namespace Base { if (ok) *ok = false; return Default; - } } - }; + } +}; - class Quantity{ - public: - Quantity(void); - explicit Quantity(double Value, const Unit& unit=Unit()); - static Quantity parse(const QString&); - void setValue(double); - double getValue() const; - void setUnit(const Unit&); - Unit getUnit() const; - const QuantityFormat& getFormat() const { - return format; - } - void setFormat(const QuantityFormat& f) { - format = f; - } - QString getUserString() const; - QString getUserString(double& factor, QString& unitString) const; +class Quantity +{ +public: + Quantity(void); + explicit Quantity(double Value, const Unit& unit = Unit()); + static Quantity parse(const QString&); + void setValue(double); + double getValue() const; + void setUnit(const Unit&); + Unit getUnit() const; + const QuantityFormat& getFormat() const + { + return format; + } + void setFormat(const QuantityFormat& f) + { + format = f; + } + QString getUserString() const; + QString getUserString(double& factor, QString& unitString) const; - private: - double value; - Unit unit; - QuantityFormat format; - }; -} +private: + double value; + Unit unit; + QuantityFormat format; +}; +}// namespace Base Q_DECLARE_METATYPE(Base::Quantity) namespace Gui { -class UrlLabel : public QLabel +class UrlLabel: public QLabel { Q_OBJECT - Q_PROPERTY( QString url READ url WRITE setUrl) + Q_PROPERTY(QString url READ url WRITE setUrl) public: - UrlLabel ( QWidget * parent = 0, Qt::WindowFlags f = Qt::WindowFlags()); + UrlLabel(QWidget* parent = 0, Qt::WindowFlags f = Qt::WindowFlags()); virtual ~UrlLabel(); QString url() const; public Q_SLOTS: - void setUrl( const QString &u ); + void setUrl(const QString& u); protected: - void mouseReleaseEvent ( QMouseEvent * ); + void mouseReleaseEvent(QMouseEvent*); private: QString _url; }; -class LocationWidget : public QWidget +class LocationWidget: public QWidget { Q_OBJECT - + public: - LocationWidget (QWidget * parent = 0); + LocationWidget(QWidget* parent = 0); virtual ~LocationWidget(); QSize sizeHint() const; @@ -189,15 +204,15 @@ private: void retranslateUi(); private: - QGridLayout *box; - QLabel *xLabel; - QLabel *yLabel; - QLabel *zLabel; - QLabel *dLabel; - QDoubleSpinBox *xValue; - QDoubleSpinBox *yValue; - QDoubleSpinBox *zValue; - QComboBox *dValue; + QGridLayout* box; + QLabel* xLabel; + QLabel* yLabel; + QLabel* zLabel; + QLabel* dLabel; + QDoubleSpinBox* xValue; + QDoubleSpinBox* yValue; + QDoubleSpinBox* zValue; + QComboBox* dValue; }; /** @@ -205,22 +220,26 @@ private: * is inside a namespace and it uses the Q_ENUM macro then QtDesigner doesn't handle * the enum(s) correctly in its property editor. This bug is fixed since Qt 4.3.0. */ -class FileChooser : public QWidget +class FileChooser: public QWidget { Q_OBJECT public: - enum Mode { File, Directory }; + enum Mode + { + File, + Directory + }; private: - Q_ENUM( Mode ) - Q_PROPERTY( Mode mode READ mode WRITE setMode ) - Q_PROPERTY( QString fileName READ fileName WRITE setFileName ) - Q_PROPERTY( QString filter READ filter WRITE setFilter ) - Q_PROPERTY( QString buttonText READ buttonText WRITE setButtonText ) + Q_ENUM(Mode) + Q_PROPERTY(Mode mode READ mode WRITE setMode) + Q_PROPERTY(QString fileName READ fileName WRITE setFileName) + Q_PROPERTY(QString filter READ filter WRITE setFilter) + Q_PROPERTY(QString buttonText READ buttonText WRITE setButtonText) public: - FileChooser (QWidget *parent = 0); + FileChooser(QWidget* parent = 0); virtual ~FileChooser(); @@ -230,42 +249,42 @@ public: QString buttonText() const; public Q_SLOTS: - void setFileName( const QString &fn ); - void setMode( FileChooser::Mode m ); - void setFilter ( const QString & ); - void setButtonText ( const QString & ); + void setFileName(const QString& fn); + void setMode(FileChooser::Mode m); + void setFilter(const QString&); + void setButtonText(const QString&); Q_SIGNALS: - void fileNameChanged( const QString & ); - void fileNameSelected( const QString & ); + void fileNameChanged(const QString&); + void fileNameSelected(const QString&); private Q_SLOTS: void chooseFile(); private: - QLineEdit *lineEdit; - QPushButton *button; + QLineEdit* lineEdit; + QPushButton* button; Mode md; QString _filter; }; // ------------------------------------------------------------------------------ -class PrefFileChooser : public FileChooser +class PrefFileChooser: public FileChooser { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefFileChooser ( QWidget * parent = 0 ); + PrefFileChooser(QWidget* parent = 0); virtual ~PrefFileChooser(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -274,59 +293,59 @@ private: // ------------------------------------------------------------------------------ -class AccelLineEdit : public QLineEdit +class AccelLineEdit: public QLineEdit { Q_OBJECT public: - AccelLineEdit ( QWidget * parent=0 ); + AccelLineEdit(QWidget* parent = 0); protected: - void keyPressEvent ( QKeyEvent * e); + void keyPressEvent(QKeyEvent* e); }; // ------------------------------------------------------------------------------ -class ActionSelector : public QWidget +class ActionSelector: public QWidget { Q_OBJECT public: - ActionSelector(QWidget* parent=0); + ActionSelector(QWidget* parent = 0); ~ActionSelector(); private: - QGridLayout *gridLayout; - QVBoxLayout *vboxLayout; - QVBoxLayout *vboxLayout1; - QPushButton *addButton; - QPushButton *removeButton; - QPushButton *upButton; - QPushButton *downButton; - QLabel *labelAvailable; - QLabel *labelSelected; - QTreeWidget *availableWidget; - QTreeWidget *selectedWidget; - QSpacerItem *spacerItem; - QSpacerItem *spacerItem1; + QGridLayout* gridLayout; + QVBoxLayout* vboxLayout; + QVBoxLayout* vboxLayout1; + QPushButton* addButton; + QPushButton* removeButton; + QPushButton* upButton; + QPushButton* downButton; + QLabel* labelAvailable; + QLabel* labelSelected; + QTreeWidget* availableWidget; + QTreeWidget* selectedWidget; + QSpacerItem* spacerItem; + QSpacerItem* spacerItem1; }; // ------------------------------------------------------------------------------ -class InputField : public QLineEdit +class InputField: public QLineEdit { Q_OBJECT - Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) - Q_PROPERTY(double singleStep READ singleStep WRITE setSingleStep ) - Q_PROPERTY(double maximum READ maximum WRITE setMaximum ) - Q_PROPERTY(double minimum READ minimum WRITE setMinimum ) - Q_PROPERTY(int historySize READ historySize WRITE setHistorySize ) - Q_PROPERTY(QString unit READ getUnitText WRITE setUnitText ) - Q_PROPERTY(double quantity READ getQuantity WRITE setValue ) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) + Q_PROPERTY(double singleStep READ singleStep WRITE setSingleStep) + Q_PROPERTY(double maximum READ maximum WRITE setMaximum) + Q_PROPERTY(double minimum READ minimum WRITE setMinimum) + Q_PROPERTY(int historySize READ historySize WRITE setHistorySize) + Q_PROPERTY(QString unit READ getUnitText WRITE setUnitText) + Q_PROPERTY(double quantity READ getQuantity WRITE setValue) public: - InputField (QWidget * parent = 0); + InputField(QWidget* parent = 0); virtual ~InputField(); void setValue(double); @@ -340,9 +359,9 @@ public: int historySize(void) const; void setHistorySize(int); void setUnitText(QString); - QString getUnitText(void); - QByteArray paramGrpPath () const; - void setParamGrpPath(const QByteArray& name); + QString getUnitText(void); + QByteArray paramGrpPath() const; + void setParamGrpPath(const QByteArray& name); Q_SIGNALS: void valueChanged(const Base::Quantity&); @@ -362,7 +381,7 @@ private: // ------------------------------------------------------------------------------ class QuantitySpinBoxPrivate; -class QuantitySpinBox : public QAbstractSpinBox +class QuantitySpinBox: public QAbstractSpinBox { Q_OBJECT @@ -372,10 +391,10 @@ class QuantitySpinBox : public QAbstractSpinBox Q_PROPERTY(double singleStep READ singleStep WRITE setSingleStep) Q_PROPERTY(double rawValue READ rawValue WRITE setValue NOTIFY valueChanged DESIGNABLE false) Q_PROPERTY(double value READ rawValue WRITE setValue NOTIFY valueChanged USER true) - //Q_PROPERTY(Base::Quantity value READ value WRITE setValue NOTIFY valueChanged USER true) + // Q_PROPERTY(Base::Quantity value READ value WRITE setValue NOTIFY valueChanged USER true) public: - explicit QuantitySpinBox(QWidget *parent = 0); + explicit QuantitySpinBox(QWidget* parent = 0); virtual ~QuantitySpinBox(); /// Get the current quantity @@ -383,8 +402,8 @@ public: /// Get the current quantity without unit double rawValue() const; - /// Gives the current state of the user input, gives true if it is a valid input with correct quantity - /// or returns false if the input is a unparsable string or has a wrong unit. + /// Gives the current state of the user input, gives true if it is a valid input with correct + /// quantity or returns false if the input is a unparsable string or has a wrong unit. bool hasValidInput() const; /** Sets the Unit this widget is working with. @@ -394,7 +413,7 @@ public: * Quantity. */ Base::Unit unit() const; - void setUnit(const Base::Unit &unit); + void setUnit(const Base::Unit& unit); /// Set the unit property void setUnitText(const QString&); /// Get the unit property @@ -428,16 +447,16 @@ public: void setRange(double min, double max); - Base::Quantity valueFromText(const QString &text) const; + Base::Quantity valueFromText(const QString& text) const; QString textFromValue(const Base::Quantity& val) const; virtual void stepBy(int steps); virtual void clear(); - virtual QValidator::State validate(QString &input, int &pos) const; - virtual void fixup(QString &str) const; + virtual QValidator::State validate(QString& input, int& pos) const; + virtual void fixup(QString& str) const; QSize sizeHint() const; QSize minimumSizeHint() const; - bool event(QEvent *event); + bool event(QEvent* event); public Q_SLOTS: /// Sets the field with a quantity @@ -446,18 +465,18 @@ public Q_SLOTS: void setValue(double); protected Q_SLOTS: - void userInput(const QString & text); + void userInput(const QString& text); void handlePendingEmit(); protected: virtual StepEnabled stepEnabled() const; - virtual void showEvent(QShowEvent * event); - virtual void hideEvent(QHideEvent * event); - virtual void closeEvent(QCloseEvent * event); - virtual void focusInEvent(QFocusEvent * event); - virtual void focusOutEvent(QFocusEvent * event); - virtual void keyPressEvent(QKeyEvent *event); - virtual void resizeEvent(QResizeEvent *event); + virtual void showEvent(QShowEvent* event); + virtual void hideEvent(QHideEvent* event); + virtual void closeEvent(QCloseEvent* event); + virtual void focusInEvent(QFocusEvent* event); + virtual void focusOutEvent(QFocusEvent* event); + virtual void keyPressEvent(QKeyEvent* event); + virtual void resizeEvent(QResizeEvent* event); private: void updateText(const Base::Quantity&); @@ -493,21 +512,21 @@ private: // ------------------------------------------------------------------------------ -class PrefUnitSpinBox : public QuantitySpinBox +class PrefUnitSpinBox: public QuantitySpinBox { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefUnitSpinBox ( QWidget * parent = 0 ); + PrefUnitSpinBox(QWidget* parent = 0); virtual ~PrefUnitSpinBox(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -516,12 +535,12 @@ private: // ------------------------------------------------------------------------------ -class PrefQuantitySpinBox : public QuantitySpinBox +class PrefQuantitySpinBox: public QuantitySpinBox { Q_OBJECT - Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) - Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: PrefQuantitySpinBox(QWidget* parent = 0); @@ -529,8 +548,8 @@ public: QByteArray entryName() const; QByteArray paramGrpPath() const; - void setEntryName(const QByteArray& name); - void setParamGrpPath(const QByteArray& name); + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -539,103 +558,103 @@ private: // ------------------------------------------------------------------------------ -class CommandIconView : public QListWidget +class CommandIconView: public QListWidget { Q_OBJECT public: - CommandIconView ( QWidget * parent = 0 ); - virtual ~CommandIconView (); + CommandIconView(QWidget* parent = 0); + virtual ~CommandIconView(); protected: - void startDrag ( Qt::DropActions supportedActions ); + void startDrag(Qt::DropActions supportedActions); protected Q_SLOTS: - void onSelectionChanged( QListWidgetItem * item, QListWidgetItem * ); + void onSelectionChanged(QListWidgetItem* item, QListWidgetItem*); Q_SIGNALS: - void emitSelectionChanged( const QString& ); + void emitSelectionChanged(const QString&); }; // ------------------------------------------------------------- class UIntSpinBoxPrivate; -class UIntSpinBox : public QSpinBox +class UIntSpinBox: public QSpinBox { Q_OBJECT - Q_OVERRIDE( uint maximum READ maximum WRITE setMaximum ) - Q_OVERRIDE( uint minimum READ minimum WRITE setMinimum ) - Q_OVERRIDE( uint value READ value WRITE setValue ) + Q_OVERRIDE(uint maximum READ maximum WRITE setMaximum) + Q_OVERRIDE(uint minimum READ minimum WRITE setMinimum) + Q_OVERRIDE(uint value READ value WRITE setValue) public: - UIntSpinBox ( QWidget* parent ); + UIntSpinBox(QWidget* parent); virtual ~UIntSpinBox(); - void setRange( uint minVal, uint maxVal ); + void setRange(uint minVal, uint maxVal); uint value() const; - virtual QValidator::State validate ( QString & input, int & pos ) const; + virtual QValidator::State validate(QString& input, int& pos) const; uint minimum() const; - void setMinimum( uint value ); + void setMinimum(uint value); uint maximum() const; - void setMaximum( uint value ); + void setMaximum(uint value); Q_SIGNALS: - void unsignedChanged( uint value ); + void unsignedChanged(uint value); public Q_SLOTS: - void setValue( uint value ); + void setValue(uint value); private Q_SLOTS: - void valueChange( int value ); + void valueChange(int value); protected: - virtual QString textFromValue ( int v ) const; - virtual int valueFromText ( const QString & text ) const; + virtual QString textFromValue(int v) const; + virtual int valueFromText(const QString& text) const; private: void updateValidator(); - UIntSpinBoxPrivate * d; + UIntSpinBoxPrivate* d; }; // ------------------------------------------------------------------------------ -class IntSpinBox : public QSpinBox +class IntSpinBox: public QSpinBox { Q_OBJECT public: - IntSpinBox ( QWidget* parent=0 ); + IntSpinBox(QWidget* parent = 0); virtual ~IntSpinBox(); }; // ------------------------------------------------------------------------------ -class DoubleSpinBox : public QDoubleSpinBox +class DoubleSpinBox: public QDoubleSpinBox { Q_OBJECT public: - DoubleSpinBox ( QWidget* parent=0 ); + DoubleSpinBox(QWidget* parent = 0); virtual ~DoubleSpinBox(); }; // ------------------------------------------------------------- -class PrefSpinBox : public QSpinBox +class PrefSpinBox: public QSpinBox { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefSpinBox ( QWidget * parent = 0 ); + PrefSpinBox(QWidget* parent = 0); virtual ~PrefSpinBox(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -644,20 +663,20 @@ private: // ------------------------------------------------------------------------------ -class ColorButton : public QPushButton +class ColorButton: public QPushButton { Q_OBJECT - Q_PROPERTY( QColor color READ color WRITE setColor ) - Q_PROPERTY( bool allowChangeColor READ allowChangeColor WRITE setAllowChangeColor ) - Q_PROPERTY( bool drawFrame READ drawFrame WRITE setDrawFrame ) - Q_PROPERTY( bool allowTransparency READ allowTransparency WRITE setAllowTransparency ) + Q_PROPERTY(QColor color READ color WRITE setColor) + Q_PROPERTY(bool allowChangeColor READ allowChangeColor WRITE setAllowChangeColor) + Q_PROPERTY(bool drawFrame READ drawFrame WRITE setDrawFrame) + Q_PROPERTY(bool allowTransparency READ allowTransparency WRITE setAllowTransparency) public: - ColorButton( QWidget* parent = 0 ); + ColorButton(QWidget* parent = 0); ~ColorButton(); - void setColor( const QColor& ); + void setColor(const QColor&); QColor color() const; void setAllowChangeColor(bool); @@ -675,7 +694,7 @@ Q_SIGNALS: void changed(); protected: - void paintEvent ( QPaintEvent* ); + void paintEvent(QPaintEvent*); private: QColor _col; @@ -686,21 +705,21 @@ private: // ------------------------------------------------------------------------------ -class PrefColorButton : public ColorButton +class PrefColorButton: public ColorButton { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefColorButton ( QWidget * parent = 0 ); + PrefColorButton(QWidget* parent = 0); virtual ~PrefColorButton(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -709,21 +728,21 @@ private: // ------------------------------------------------------------------------------ -class PrefDoubleSpinBox : public QDoubleSpinBox +class PrefDoubleSpinBox: public QDoubleSpinBox { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefDoubleSpinBox ( QWidget * parent = 0 ); + PrefDoubleSpinBox(QWidget* parent = 0); virtual ~PrefDoubleSpinBox(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -732,21 +751,21 @@ private: // ------------------------------------------------------------------------------ -class PrefLineEdit : public QLineEdit +class PrefLineEdit: public QLineEdit { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefLineEdit ( QWidget * parent = 0 ); + PrefLineEdit(QWidget* parent = 0); virtual ~PrefLineEdit(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -755,21 +774,21 @@ private: // ------------------------------------------------------------------------------ -class PrefComboBox : public QComboBox +class PrefComboBox: public QComboBox { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefComboBox ( QWidget * parent = 0 ); + PrefComboBox(QWidget* parent = 0); virtual ~PrefComboBox(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -778,21 +797,21 @@ private: // ------------------------------------------------------------------------------ -class PrefCheckBox : public QCheckBox +class PrefCheckBox: public QCheckBox { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefCheckBox ( QWidget * parent = 0 ); + PrefCheckBox(QWidget* parent = 0); virtual ~PrefCheckBox(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -801,21 +820,21 @@ private: // ------------------------------------------------------------------------------ -class PrefRadioButton : public QRadioButton +class PrefRadioButton: public QRadioButton { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefRadioButton ( QWidget * parent = 0 ); + PrefRadioButton(QWidget* parent = 0); virtual ~PrefRadioButton(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -824,21 +843,21 @@ private: // ------------------------------------------------------------------------------ -class PrefSlider : public QSlider +class PrefSlider: public QSlider { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefSlider ( QWidget * parent = 0 ); + PrefSlider(QWidget* parent = 0); virtual ~PrefSlider(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; @@ -847,26 +866,26 @@ private: // ------------------------------------------------------------------------------ -class PrefFontBox : public QFontComboBox +class PrefFontBox: public QFontComboBox { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) public: - PrefFontBox ( QWidget * parent = 0 ); + PrefFontBox(QWidget* parent = 0); virtual ~PrefFontBox(); - QByteArray entryName () const; - QByteArray paramGrpPath () const; - void setEntryName ( const QByteArray& name ); - void setParamGrpPath ( const QByteArray& name ); + QByteArray entryName() const; + QByteArray paramGrpPath() const; + void setEntryName(const QByteArray& name); + void setParamGrpPath(const QByteArray& name); private: QByteArray m_sPrefName; QByteArray m_sPrefGrp; }; -} // namespace Gui +}// namespace Gui -#endif // GUI_CUSTOMWIDGETS_H +#endif// GUI_CUSTOMWIDGETS_H diff --git a/src/Tools/plugins/widget/plugin.cpp b/src/Tools/plugins/widget/plugin.cpp index 4303448bd2..62b9672fff 100644 --- a/src/Tools/plugins/widget/plugin.cpp +++ b/src/Tools/plugins/widget/plugin.cpp @@ -21,12 +21,12 @@ ***************************************************************************/ -#include -#include +#include #include #include -#include #include +#include +#include #include #include @@ -37,42 +37,40 @@ /* XPM */ -static const char *urllabel_pixmap[]={ -"22 22 3 1", -"# c #000000", -"x c #ffffff", -". c None", -"......................", -".......##.............", -"......#xx#............", -"......#xx#............", -"......#xx#............", -"......#xx#............", -"......#xx###..........", -"......#xx#xx###.......", -"......#xx#xx#xx##.....", -"...##.#xx#xx#xx#x#....", -"..#xx##xx#xx#xx#x#....", -"..#xxx#xxxxxxxxxx#....", -"...#xxxxxxxxxxxxx#....", -"....#xxxxxxxxxxxx#....", -"....#xxxxxxxxxxxx#....", -".....#xxxxxxxxxx#.....", -".....#xxxxxxxxxx#.....", -"......#xxxxxxxx#......", -"......#xxxxxxxx#......", -"......##########......", -"......##########......", -"......##########......"}; +static const char* urllabel_pixmap[] = {"22 22 3 1", + "# c #000000", + "x c #ffffff", + ". c None", + "......................", + ".......##.............", + "......#xx#............", + "......#xx#............", + "......#xx#............", + "......#xx#............", + "......#xx###..........", + "......#xx#xx###.......", + "......#xx#xx#xx##.....", + "...##.#xx#xx#xx#x#....", + "..#xx##xx#xx#xx#x#....", + "..#xxx#xxxxxxxxxx#....", + "...#xxxxxxxxxxxxx#....", + "....#xxxxxxxxxxxx#....", + "....#xxxxxxxxxxxx#....", + ".....#xxxxxxxxxx#.....", + ".....#xxxxxxxxxx#.....", + "......#xxxxxxxx#......", + "......#xxxxxxxx#......", + "......##########......", + "......##########......", + "......##########......"}; -class UrlLabelPlugin : public QDesignerCustomWidgetInterface +class UrlLabelPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: UrlLabelPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::UrlLabel(parent); } @@ -82,7 +80,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( urllabel_pixmap ) ); + return QIcon(QPixmap(urllabel_pixmap)); } QString includeFile() const { @@ -100,7 +98,7 @@ public: { return false; } -// QString codeTemplate() const; + // QString codeTemplate() const; QString domXml() const { return "\n" @@ -114,14 +112,13 @@ public: } }; -class LocationWidgetPlugin : public QDesignerCustomWidgetInterface +class LocationWidgetPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: LocationWidgetPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::LocationWidget(parent); } @@ -131,7 +128,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( urllabel_pixmap ) ); + return QIcon(QPixmap(urllabel_pixmap)); } QString includeFile() const { @@ -162,48 +159,45 @@ public: } }; -static const char *filechooser_pixmap[] = { - "22 22 8 1", - " c Gray100", - ". c Gray97", - "X c #4f504f", - "o c #00007f", - "O c Gray0", - "+ c none", - "@ c Gray0", - "# c Gray0", - "++++++++++++++++++++++", - "++++++++++++++++++++++", - "++++++++++++++++++++++", - "++++++++++++++++++++++", - "+OOOOOOOOOOOOOOOOOOOO+", - "OOXXXXXXXXXXXXXXXXXXOO", - "OXX. OO OO O", - "OX. oo O O", - "OX. oo O .O", - "OX ooo oooo O O", - "OX oo oo oo O O", - "OX oooo oo oo O O", - "OX oo oo oo oo O O", - "OX oo oo oo oo O O", - "OX oooo oooo O O", - "OX OO OO O", - "OO..................OO", - "+OOOOOOOOOOOOOOOOOOOO+", - "++++++++++++++++++++++", - "++++++++++++++++++++++", - "++++++++++++++++++++++", - "++++++++++++++++++++++" -}; +static const char* filechooser_pixmap[] = {"22 22 8 1", + " c Gray100", + ". c Gray97", + "X c #4f504f", + "o c #00007f", + "O c Gray0", + "+ c none", + "@ c Gray0", + "# c Gray0", + "++++++++++++++++++++++", + "++++++++++++++++++++++", + "++++++++++++++++++++++", + "++++++++++++++++++++++", + "+OOOOOOOOOOOOOOOOOOOO+", + "OOXXXXXXXXXXXXXXXXXXOO", + "OXX. OO OO O", + "OX. oo O O", + "OX. oo O .O", + "OX ooo oooo O O", + "OX oo oo oo O O", + "OX oooo oo oo O O", + "OX oo oo oo oo O O", + "OX oo oo oo oo O O", + "OX oooo oooo O O", + "OX OO OO O", + "OO..................OO", + "+OOOOOOOOOOOOOOOOOOOO+", + "++++++++++++++++++++++", + "++++++++++++++++++++++", + "++++++++++++++++++++++", + "++++++++++++++++++++++"}; -class FileChooserPlugin : public QDesignerCustomWidgetInterface +class FileChooserPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: FileChooserPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::FileChooser(parent); } @@ -213,7 +207,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( filechooser_pixmap ) ); + return QIcon(QPixmap(filechooser_pixmap)); } QString includeFile() const { @@ -231,7 +225,7 @@ public: { return false; } -// QString codeTemplate() const; + // QString codeTemplate() const; QString domXml() const { return "\n" @@ -245,14 +239,13 @@ public: } }; -class PrefFileChooserPlugin : public QDesignerCustomWidgetInterface +class PrefFileChooserPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefFileChooserPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefFileChooser(parent); } @@ -262,7 +255,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( filechooser_pixmap ) ); + return QIcon(QPixmap(filechooser_pixmap)); } QString includeFile() const { @@ -294,45 +287,43 @@ public: }; /* XPM */ -static const char *lineedit_pixmap[]={ -"22 22 6 1", -"a c #000000", -"# c #000080", -"b c #008080", -"c c #808080", -"d c #c0c0c0", -". c #ffffff", -"......................", -"......................", -"......................", -"...#aaaaaaaaaaaaaa#...", -".baccccccccccccccccab.", -".acccddddddddddddddca.", -"#ccd................d#", -"acc.................da", -"acd.......d....ca.ac.a", -"acd......db......a...a", -"acd.dbbb.dbbbd...a...a", -"acd.ccdbddb.db...a...a", -"acd.dbbbddb..b...a...a", -"acd.bd.bddb..b...a...a", -"acd.bbbbddbbbc...a...a", -"acd..d.....dd..ca.acda", -"#cd.................d#", -".ac................da.", -".badd............dda#.", -"...#aaaaaaaaaaaaaa#...", -"......................", -"......................"}; +static const char* lineedit_pixmap[] = {"22 22 6 1", + "a c #000000", + "# c #000080", + "b c #008080", + "c c #808080", + "d c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "...#aaaaaaaaaaaaaa#...", + ".baccccccccccccccccab.", + ".acccddddddddddddddca.", + "#ccd................d#", + "acc.................da", + "acd.......d....ca.ac.a", + "acd......db......a...a", + "acd.dbbb.dbbbd...a...a", + "acd.ccdbddb.db...a...a", + "acd.dbbbddb..b...a...a", + "acd.bd.bddb..b...a...a", + "acd.bbbbddbbbc...a...a", + "acd..d.....dd..ca.acda", + "#cd.................d#", + ".ac................da.", + ".badd............dda#.", + "...#aaaaaaaaaaaaaa#...", + "......................", + "......................"}; -class AccelLineEditPlugin : public QDesignerCustomWidgetInterface +class AccelLineEditPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: AccelLineEditPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::AccelLineEdit(parent); } @@ -342,7 +333,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( lineedit_pixmap ) ); + return QIcon(QPixmap(lineedit_pixmap)); } QString includeFile() const { @@ -374,45 +365,43 @@ public: }; /* XPM */ -static const char *actionselector_pixmap[]={ -"22 22 6 1", -"a c #000000", -"# c #000080", -"b c #008080", -"c c #808080", -"d c #c0c0c0", -". c #ffffff", -"......................", -"......................", -"......................", -"...#aaaaaaaaaaaaaa#...", -".baccccccccccccccccab.", -".acccddddddddddddddca.", -"#ccd................d#", -"acc.................da", -"acd.......d....ca.ac.a", -"acd......db......a...a", -"acd.dbbb.dbbbd...a...a", -"acd.ccdbddb.db...a...a", -"acd.dbbbddb..b...a...a", -"acd.bd.bddb..b...a...a", -"acd.bbbbddbbbc...a...a", -"acd..d.....dd..ca.acda", -"#cd.................d#", -".ac................da.", -".badd............dda#.", -"...#aaaaaaaaaaaaaa#...", -"......................", -"......................"}; +static const char* actionselector_pixmap[] = {"22 22 6 1", + "a c #000000", + "# c #000080", + "b c #008080", + "c c #808080", + "d c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "...#aaaaaaaaaaaaaa#...", + ".baccccccccccccccccab.", + ".acccddddddddddddddca.", + "#ccd................d#", + "acc.................da", + "acd.......d....ca.ac.a", + "acd......db......a...a", + "acd.dbbb.dbbbd...a...a", + "acd.ccdbddb.db...a...a", + "acd.dbbbddb..b...a...a", + "acd.bd.bddb..b...a...a", + "acd.bbbbddbbbc...a...a", + "acd..d.....dd..ca.acda", + "#cd.................d#", + ".ac................da.", + ".badd............dda#.", + "...#aaaaaaaaaaaaaa#...", + "......................", + "......................"}; -class ActionSelectorPlugin : public QDesignerCustomWidgetInterface +class ActionSelectorPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: ActionSelectorPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::ActionSelector(parent); } @@ -422,7 +411,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( actionselector_pixmap ) ); + return QIcon(QPixmap(actionselector_pixmap)); } QString includeFile() const { @@ -454,45 +443,43 @@ public: }; /* XPM */ -static const char *inputfield_pixmap[]={ -"22 22 6 1", -"a c #000000", -"# c #000080", -"b c #008080", -"c c #808080", -"d c #c0c0c0", -". c #ffffff", -"......................", -"......................", -"......................", -"...#aaaaaaaaaaaaaa#...", -".baccccccccccccccccab.", -".acccddddddddddddddca.", -"#ccd................d#", -"acc.................da", -"acd.......d....ca.ac.a", -"acd......db......a...a", -"acd.dbbb.dbbbd...a...a", -"acd.ccdbddb.db...a...a", -"acd.dbbbddb..b...a...a", -"acd.bd.bddb..b...a...a", -"acd.bbbbddbbbc...a...a", -"acd..d.....dd..ca.acda", -"#cd.................d#", -".ac................da.", -".badd............dda#.", -"...#aaaaaaaaaaaaaa#...", -"......................", -"......................"}; +static const char* inputfield_pixmap[] = {"22 22 6 1", + "a c #000000", + "# c #000080", + "b c #008080", + "c c #808080", + "d c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "...#aaaaaaaaaaaaaa#...", + ".baccccccccccccccccab.", + ".acccddddddddddddddca.", + "#ccd................d#", + "acc.................da", + "acd.......d....ca.ac.a", + "acd......db......a...a", + "acd.dbbb.dbbbd...a...a", + "acd.ccdbddb.db...a...a", + "acd.dbbbddb..b...a...a", + "acd.bd.bddb..b...a...a", + "acd.bbbbddbbbc...a...a", + "acd..d.....dd..ca.acda", + "#cd.................d#", + ".ac................da.", + ".badd............dda#.", + "...#aaaaaaaaaaaaaa#...", + "......................", + "......................"}; -class InputFieldPlugin : public QDesignerCustomWidgetInterface +class InputFieldPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: InputFieldPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::InputField(parent); } @@ -502,7 +489,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( inputfield_pixmap ) ); + return QIcon(QPixmap(inputfield_pixmap)); } QString includeFile() const { @@ -537,45 +524,43 @@ public: }; /* XPM */ -static const char *quantityspinbox_pixmap[]={ -"22 22 6 1", -"a c #000000", -"# c #000080", -"b c #008080", -"c c #808080", -"d c #c0c0c0", -". c #ffffff", -"...#aaaaaaaaaaaaaa#...", -".baccccccccccccccccab.", -".acccddddddddddddddca.", -"#ccd................d#", -"acc.............dcd.da", -"acd.............dbd..a", -"acd............dcbbd.a", -"acd.d..dd..d...dbbbc.a", -"acddb.dbbdcbb.dbbb#bda", -"acd.b.d.cc..b.bb###bda", -"acd.b...bd.cb.dddccdda", -"acd.b...b..db...dddd.a", -"acd.b..cd...bdddccbbda", -"acd.b.dbbccdb.ccbbbbda", -"acddd.ddd.dd..dbbb#cda", -"acd............bb##cda", -"acd............db#cd.a", -"acd.............bbcdda", -"#cd.............ddd.d#", -".ac................da.", -".badd............dda#.", -"...#aaaaaaaaaaaaaa#..."}; +static const char* quantityspinbox_pixmap[] = {"22 22 6 1", + "a c #000000", + "# c #000080", + "b c #008080", + "c c #808080", + "d c #c0c0c0", + ". c #ffffff", + "...#aaaaaaaaaaaaaa#...", + ".baccccccccccccccccab.", + ".acccddddddddddddddca.", + "#ccd................d#", + "acc.............dcd.da", + "acd.............dbd..a", + "acd............dcbbd.a", + "acd.d..dd..d...dbbbc.a", + "acddb.dbbdcbb.dbbb#bda", + "acd.b.d.cc..b.bb###bda", + "acd.b...bd.cb.dddccdda", + "acd.b...b..db...dddd.a", + "acd.b..cd...bdddccbbda", + "acd.b.dbbccdb.ccbbbbda", + "acddd.ddd.dd..dbbb#cda", + "acd............bb##cda", + "acd............db#cd.a", + "acd.............bbcdda", + "#cd.............ddd.d#", + ".ac................da.", + ".badd............dda#.", + "...#aaaaaaaaaaaaaa#..."}; -class QuantitySpinBoxPlugin : public QDesignerCustomWidgetInterface +class QuantitySpinBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: QuantitySpinBoxPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::QuantitySpinBox(parent); } @@ -585,7 +570,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( quantityspinbox_pixmap ) ); + return QIcon(QPixmap(quantityspinbox_pixmap)); } QString includeFile() const { @@ -619,14 +604,13 @@ public: } }; -class PrefUnitSpinBoxPlugin : public QDesignerCustomWidgetInterface +class PrefUnitSpinBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefUnitSpinBoxPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefUnitSpinBox(parent); } @@ -636,7 +620,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( quantityspinbox_pixmap ) ); + return QIcon(QPixmap(quantityspinbox_pixmap)); } QString includeFile() const { @@ -667,13 +651,12 @@ public: } }; -class PrefQuantitySpinBoxPlugin : public QDesignerCustomWidgetInterface +class PrefQuantitySpinBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefQuantitySpinBoxPlugin() - { - } + {} QWidget* createWidget(QWidget* parent) { return new Gui::PrefQuantitySpinBox(parent); @@ -705,9 +688,9 @@ public: QString domXml() const { return "\n" - " \n" - " \n" - ""; + " \n" + " \n" + ""; } QString name() const { @@ -716,49 +699,47 @@ public: }; /* XPM */ -static const char *iconview_pixmap[]={ -"22 22 10 1", -"# c #000000", -"h c #000080", -"f c #0000ff", -"d c #008000", -"e c #008080", -"a c #800000", -"b c #808080", -"c c #c0c0c0", -"g c #ff0000", -". c #ffffff", -"...################...", -".a#bbccccccccccccbb#a.", -".#bcc..............b#.", -"#bb......c.....c....c#", -"#bbbbc..cbbc...bbbc.c#", -"#cccdd....bdb..ccdd..#", -"#cbcb#c.cbcbd..bcb#c.#", -"#cbbb#b..bbb#..cbb#c.#", -"#c..c##...cb#c...c##.#", -"#c...................#", -"#ccbbc..c#bbc..cbbcc.#", -"#c...................#", -"#cbbbaa.cb..cc..c.bb.#", -"#cbccca.c#ccb..cecf#.#", -"#cbcgba..c#b...bfbfh.#", -"#cacbba..bb#c..bbhb#.#", -"#caaaaa.bc.bb..bb###.#", -"#b..................c#", -"#b.bbcc..cbbbb.cbbc.c#", -".#b................c#.", -".a#cc............cc##.", -"...################..."}; +static const char* iconview_pixmap[] = {"22 22 10 1", + "# c #000000", + "h c #000080", + "f c #0000ff", + "d c #008000", + "e c #008080", + "a c #800000", + "b c #808080", + "c c #c0c0c0", + "g c #ff0000", + ". c #ffffff", + "...################...", + ".a#bbccccccccccccbb#a.", + ".#bcc..............b#.", + "#bb......c.....c....c#", + "#bbbbc..cbbc...bbbc.c#", + "#cccdd....bdb..ccdd..#", + "#cbcb#c.cbcbd..bcb#c.#", + "#cbbb#b..bbb#..cbb#c.#", + "#c..c##...cb#c...c##.#", + "#c...................#", + "#ccbbc..c#bbc..cbbcc.#", + "#c...................#", + "#cbbbaa.cb..cc..c.bb.#", + "#cbccca.c#ccb..cecf#.#", + "#cbcgba..c#b...bfbfh.#", + "#cacbba..bb#c..bbhb#.#", + "#caaaaa.bc.bb..bb###.#", + "#b..................c#", + "#b.bbcc..cbbbb.cbbc.c#", + ".#b................c#.", + ".a#cc............cc##.", + "...################..."}; -class CommandIconViewPlugin : public QDesignerCustomWidgetInterface +class CommandIconViewPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: CommandIconViewPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::CommandIconView(parent); } @@ -768,7 +749,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( iconview_pixmap ) ); + return QIcon(QPixmap(iconview_pixmap)); } QString includeFile() const { @@ -800,45 +781,43 @@ public: }; /* XPM */ -static const char *spinbox_pixmap[]={ -"22 22 6 1", -"a c #000000", -"# c #000080", -"b c #008080", -"c c #808080", -"d c #c0c0c0", -". c #ffffff", -"...#aaaaaaaaaaaaaa#...", -".baccccccccccccccccab.", -".acccddddddddddddddca.", -"#ccd................d#", -"acc.............dcd.da", -"acd.............dbd..a", -"acd............dcbbd.a", -"acd.d..dd..d...dbbbc.a", -"acddb.dbbdcbb.dbbb#bda", -"acd.b.d.cc..b.bb###bda", -"acd.b...bd.cb.dddccdda", -"acd.b...b..db...dddd.a", -"acd.b..cd...bdddccbbda", -"acd.b.dbbccdb.ccbbbbda", -"acddd.ddd.dd..dbbb#cda", -"acd............bb##cda", -"acd............db#cd.a", -"acd.............bbcdda", -"#cd.............ddd.d#", -".ac................da.", -".badd............dda#.", -"...#aaaaaaaaaaaaaa#..."}; +static const char* spinbox_pixmap[] = {"22 22 6 1", + "a c #000000", + "# c #000080", + "b c #008080", + "c c #808080", + "d c #c0c0c0", + ". c #ffffff", + "...#aaaaaaaaaaaaaa#...", + ".baccccccccccccccccab.", + ".acccddddddddddddddca.", + "#ccd................d#", + "acc.............dcd.da", + "acd.............dbd..a", + "acd............dcbbd.a", + "acd.d..dd..d...dbbbc.a", + "acddb.dbbdcbb.dbbb#bda", + "acd.b.d.cc..b.bb###bda", + "acd.b...bd.cb.dddccdda", + "acd.b...b..db...dddd.a", + "acd.b..cd...bdddccbbda", + "acd.b.dbbccdb.ccbbbbda", + "acddd.ddd.dd..dbbb#cda", + "acd............bb##cda", + "acd............db#cd.a", + "acd.............bbcdda", + "#cd.............ddd.d#", + ".ac................da.", + ".badd............dda#.", + "...#aaaaaaaaaaaaaa#..."}; -class UIntSpinBoxPlugin : public QDesignerCustomWidgetInterface +class UIntSpinBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: UIntSpinBoxPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::UIntSpinBox(parent); } @@ -848,7 +827,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( spinbox_pixmap ) ); + return QIcon(QPixmap(spinbox_pixmap)); } QString includeFile() const { @@ -879,14 +858,13 @@ public: } }; -class IntSpinBoxPlugin : public QDesignerCustomWidgetInterface +class IntSpinBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: IntSpinBoxPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::IntSpinBox(parent); } @@ -896,7 +874,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( spinbox_pixmap ) ); + return QIcon(QPixmap(spinbox_pixmap)); } QString includeFile() const { @@ -927,14 +905,13 @@ public: } }; -class DoubleSpinBoxPlugin : public QDesignerCustomWidgetInterface +class DoubleSpinBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: DoubleSpinBoxPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::DoubleSpinBox(parent); } @@ -944,7 +921,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( spinbox_pixmap ) ); + return QIcon(QPixmap(spinbox_pixmap)); } QString includeFile() const { @@ -975,14 +952,13 @@ public: } }; -class PrefSpinBoxPlugin : public QDesignerCustomWidgetInterface +class PrefSpinBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefSpinBoxPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefSpinBox(parent); } @@ -992,7 +968,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( spinbox_pixmap ) ); + return QIcon(QPixmap(spinbox_pixmap)); } QString includeFile() const { @@ -1024,45 +1000,43 @@ public: }; /* XPM */ -static const char *colorbutton_pixmap[]={ -"21 21 7 1", -"d c #000000", -"b c #000080", -"e c #0000ff", -"a c #008080", -"# c #808080", -"c c #c0c0c0", -". c #ffffff", -".....................", -".#abbbbbbbbbbbbbba#c.", -"c#c..............c##.", -"#c................ca.", -"#..................b.", -"#...ddddddddddd....b.", -"#...deeeeeeeeed....b.", -"#...deeeeeeeeed....b.", -"#...deeeeeeeeed....b.", -"#...deeeeeeeeed....b.", -"#...deeeeeeeeed....b.", -"#...deeeeeeeeed....b.", -"#...deeeeeeeeed....b.", -"#...deeeeeeeeed....b.", -"#...deeeeeeeeed....b.", -"#...ddddddddddd....b.", -"#..................b.", -"#.................cb.", -"#cccccccccccccccccca.", -"c#cccccccccccccccc##.", -".cccccccccccccccccc.."}; +static const char* colorbutton_pixmap[] = {"21 21 7 1", + "d c #000000", + "b c #000080", + "e c #0000ff", + "a c #008080", + "# c #808080", + "c c #c0c0c0", + ". c #ffffff", + ".....................", + ".#abbbbbbbbbbbbbba#c.", + "c#c..............c##.", + "#c................ca.", + "#..................b.", + "#...ddddddddddd....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...deeeeeeeeed....b.", + "#...ddddddddddd....b.", + "#..................b.", + "#.................cb.", + "#cccccccccccccccccca.", + "c#cccccccccccccccc##.", + ".cccccccccccccccccc.."}; -class ColorButtonPlugin : public QDesignerCustomWidgetInterface +class ColorButtonPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: ColorButtonPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::ColorButton(parent); } @@ -1072,7 +1046,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( colorbutton_pixmap ) ); + return QIcon(QPixmap(colorbutton_pixmap)); } QString includeFile() const { @@ -1103,14 +1077,13 @@ public: } }; -class PrefColorButtonPlugin : public QDesignerCustomWidgetInterface +class PrefColorButtonPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefColorButtonPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefColorButton(parent); } @@ -1120,7 +1093,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( colorbutton_pixmap ) ); + return QIcon(QPixmap(colorbutton_pixmap)); } QString includeFile() const { @@ -1152,44 +1125,42 @@ public: }; /* XPM */ -static const char *slider_pixmap[]={ -"22 22 5 1", -"b c #000000", -"c c #008080", -"# c #808080", -"a c #c0c0c0", -". c #ffffff", -"......................", -"......................", -"......................", -"......................", -"......................", -".........#............", -"........a##...........", -"........a##...........", -"........a##...........", -"..bbbb..a#bbbbbbbbbb..", -".bbbbb..a#bbbbbbbbbbc.", -".bb###..a#b########c#.", -".bbb##..a#b########aa.", -"..cc##..a#b########a..", -"........a##...........", -"........a##...........", -"........a##...........", -"......#####...........", -".......####...........", -"......................", -"......................", -"......................"}; +static const char* slider_pixmap[] = {"22 22 5 1", + "b c #000000", + "c c #008080", + "# c #808080", + "a c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "......................", + "......................", + ".........#............", + "........a##...........", + "........a##...........", + "........a##...........", + "..bbbb..a#bbbbbbbbbb..", + ".bbbbb..a#bbbbbbbbbbc.", + ".bb###..a#b########c#.", + ".bbb##..a#b########aa.", + "..cc##..a#b########a..", + "........a##...........", + "........a##...........", + "........a##...........", + "......#####...........", + ".......####...........", + "......................", + "......................", + "......................"}; -class PrefSliderPlugin : public QDesignerCustomWidgetInterface +class PrefSliderPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefSliderPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefSlider(parent); } @@ -1199,7 +1170,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( slider_pixmap ) ); + return QIcon(QPixmap(slider_pixmap)); } QString includeFile() const { @@ -1231,43 +1202,41 @@ public: }; /* XPM */ -static const char *radiobutton_pixmap[]={ -"22 22 4 1", -"b c #000000", -"# c #808080", -"a c #c0c0c0", -". c #ffffff", -"......................", -"......................", -"......................", -"......................", -".......########.......", -"......#####aaa##......", -".....#b##a...aaa#.....", -"....###aa.aa....a#....", -"....###a.####a...a....", -"....##a.####bba..a....", -"....##.a###bbb#.......", -"....#a.a##bbbb#.......", -"....#a..bbbbbba.......", -"....#aa.abbbb#...a....", -"....##a..a##a....a....", -".....#a.........a.....", -"......#a.......a......", -".......#aa...aa.......", -"......................", -"......................", -"......................", -"......................"}; +static const char* radiobutton_pixmap[] = {"22 22 4 1", + "b c #000000", + "# c #808080", + "a c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "......................", + ".......########.......", + "......#####aaa##......", + ".....#b##a...aaa#.....", + "....###aa.aa....a#....", + "....###a.####a...a....", + "....##a.####bba..a....", + "....##.a###bbb#.......", + "....#a.a##bbbb#.......", + "....#a..bbbbbba.......", + "....#aa.abbbb#...a....", + "....##a..a##a....a....", + ".....#a.........a.....", + "......#a.......a......", + ".......#aa...aa.......", + "......................", + "......................", + "......................", + "......................"}; -class PrefRadioButtonPlugin : public QDesignerCustomWidgetInterface +class PrefRadioButtonPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefRadioButtonPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefRadioButton(parent); } @@ -1277,7 +1246,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( radiobutton_pixmap ) ); + return QIcon(QPixmap(radiobutton_pixmap)); } QString includeFile() const { @@ -1309,43 +1278,41 @@ public: }; /* XPM */ -static const char *checkbox_pixmap[]={ -"22 22 4 1", -"# c #000000", -"a c #808080", -"b c #c0c0c0", -". c #ffffff", -"......................", -"......................", -"......................", -"......................", -"....###########aaa....", -"....##aaaaaaaaaabb....", -"....#aabbbbbbbbbbb....", -"....#abbbbbbbbaa......", -"....#abbbbbbba#a......", -"....#ababbbba##a......", -"....#ab#abba###a......", -"....#ab##aa###ab......", -"....#ab######abb......", -"....#abb####abbb......", -"....#abbb##abbbb......", -"....aabbbbabbbb.......", -"....abb......b........", -"....abb...............", -"......................", -"......................", -"......................", -"......................"}; +static const char* checkbox_pixmap[] = {"22 22 4 1", + "# c #000000", + "a c #808080", + "b c #c0c0c0", + ". c #ffffff", + "......................", + "......................", + "......................", + "......................", + "....###########aaa....", + "....##aaaaaaaaaabb....", + "....#aabbbbbbbbbbb....", + "....#abbbbbbbbaa......", + "....#abbbbbbba#a......", + "....#ababbbba##a......", + "....#ab#abba###a......", + "....#ab##aa###ab......", + "....#ab######abb......", + "....#abb####abbb......", + "....#abbb##abbbb......", + "....aabbbbabbbb.......", + "....abb......b........", + "....abb...............", + "......................", + "......................", + "......................", + "......................"}; -class PrefCheckBoxPlugin : public QDesignerCustomWidgetInterface +class PrefCheckBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefCheckBoxPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefCheckBox(parent); } @@ -1355,7 +1322,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( checkbox_pixmap ) ); + return QIcon(QPixmap(checkbox_pixmap)); } QString includeFile() const { @@ -1387,47 +1354,45 @@ public: }; /* XPM */ -static const char *combobox_pixmap[]={ -"22 22 8 1", -"a c #000000", -"# c #000080", -"e c #008080", -"f c #800000", -"b c #808080", -"c c #c0c0c0", -"d c #ff0000", -". c #ffffff", -".#aaaaaaaaaaaaaaaaaa#.", -"#bbccccccccccccccccdd#", -"accee#########e.addfaa", -"#c..............a.fa.#", -"e#aaaaaaaaaaaaaaaaaa#e", -"....#c...............#", -"....ac...............a", -"....ac.ccbbbbbbbbeb..a", -"....ac.bbbeeeeeee##c.a", -"....ac.bee########ac.a", -"....ac..cccccccccccc.a", -"....ac.ccccccccccbec.a", -"....ac.cccccccccbbec.a", -"....ac.bcbbbbbbbbbec.a", -"....ac..cccccccccccc.a", -"....ac.cbbeeeeeee#bc.a", -"....ac.bee########ac.a", -"....ab.b##aaaaaaaaacca", -"....#bc.ccccccccccccc#", -".....ab............ca.", -".....eacc.........ca#.", -".......#aaaaaaaaaa#..."}; +static const char* combobox_pixmap[] = {"22 22 8 1", + "a c #000000", + "# c #000080", + "e c #008080", + "f c #800000", + "b c #808080", + "c c #c0c0c0", + "d c #ff0000", + ". c #ffffff", + ".#aaaaaaaaaaaaaaaaaa#.", + "#bbccccccccccccccccdd#", + "accee#########e.addfaa", + "#c..............a.fa.#", + "e#aaaaaaaaaaaaaaaaaa#e", + "....#c...............#", + "....ac...............a", + "....ac.ccbbbbbbbbeb..a", + "....ac.bbbeeeeeee##c.a", + "....ac.bee########ac.a", + "....ac..cccccccccccc.a", + "....ac.ccccccccccbec.a", + "....ac.cccccccccbbec.a", + "....ac.bcbbbbbbbbbec.a", + "....ac..cccccccccccc.a", + "....ac.cbbeeeeeee#bc.a", + "....ac.bee########ac.a", + "....ab.b##aaaaaaaaacca", + "....#bc.ccccccccccccc#", + ".....ab............ca.", + ".....eacc.........ca#.", + ".......#aaaaaaaaaa#..."}; -class PrefComboBoxPlugin : public QDesignerCustomWidgetInterface +class PrefComboBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefComboBoxPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefComboBox(parent); } @@ -1437,7 +1402,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( combobox_pixmap ) ); + return QIcon(QPixmap(combobox_pixmap)); } QString includeFile() const { @@ -1468,14 +1433,13 @@ public: } }; -class PrefLineEditPlugin : public QDesignerCustomWidgetInterface +class PrefLineEditPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefLineEditPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefLineEdit(parent); } @@ -1485,7 +1449,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( lineedit_pixmap ) ); + return QIcon(QPixmap(lineedit_pixmap)); } QString includeFile() const { @@ -1516,14 +1480,13 @@ public: } }; -class PrefDoubleSpinBoxPlugin : public QDesignerCustomWidgetInterface +class PrefDoubleSpinBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefDoubleSpinBoxPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefDoubleSpinBox(parent); } @@ -1533,7 +1496,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( spinbox_pixmap ) ); + return QIcon(QPixmap(spinbox_pixmap)); } QString includeFile() const { @@ -1566,47 +1529,45 @@ public: /* XPM */ -static const char *fontbox_pixmap[]={ -"22 22 8 1", -"a c #000000", -"# c #000080", -"e c #008080", -"f c #800000", -"b c #808080", -"c c #c0c0c0", -"d c #ff0000", -". c #ffffff", -".#aaaaaaaaaaaaaaaaaa#.", -"#bbccccccccccccccccdd#", -"accee#########e.addfaa", -"#c..............a.fa.#", -"e#aaaaaaaaaaaaaaaaaa#e", -"....#c...............#", -"....ac...............a", -"....ac.ccbbbbbbbbeb..a", -"....ac.bbbeeeeeee##c.a", -"....ac.bee########ac.a", -"....ac..cccccccccccc.a", -"....ac.ccccccccccbec.a", -"....ac.cccccccccbbec.a", -"....ac.bcbbbbbbbbbec.a", -"....ac..cccccccccccc.a", -"....ac.cbbeeeeeee#bc.a", -"....ac.bee########ac.a", -"....ab.b##aaaaaaaaacca", -"....#bc.ccccccccccccc#", -".....ab............ca.", -".....eacc.........ca#.", -".......#aaaaaaaaaa#..."}; +static const char* fontbox_pixmap[] = {"22 22 8 1", + "a c #000000", + "# c #000080", + "e c #008080", + "f c #800000", + "b c #808080", + "c c #c0c0c0", + "d c #ff0000", + ". c #ffffff", + ".#aaaaaaaaaaaaaaaaaa#.", + "#bbccccccccccccccccdd#", + "accee#########e.addfaa", + "#c..............a.fa.#", + "e#aaaaaaaaaaaaaaaaaa#e", + "....#c...............#", + "....ac...............a", + "....ac.ccbbbbbbbbeb..a", + "....ac.bbbeeeeeee##c.a", + "....ac.bee########ac.a", + "....ac..cccccccccccc.a", + "....ac.ccccccccccbec.a", + "....ac.cccccccccbbec.a", + "....ac.bcbbbbbbbbbec.a", + "....ac..cccccccccccc.a", + "....ac.cbbeeeeeee#bc.a", + "....ac.bee########ac.a", + "....ab.b##aaaaaaaaacca", + "....#bc.ccccccccccccc#", + ".....ab............ca.", + ".....eacc.........ca#.", + ".......#aaaaaaaaaa#..."}; -class PrefFontBoxPlugin : public QDesignerCustomWidgetInterface +class PrefFontBoxPlugin: public QDesignerCustomWidgetInterface { Q_INTERFACES(QDesignerCustomWidgetInterface) public: PrefFontBoxPlugin() - { - } - QWidget *createWidget(QWidget *parent) + {} + QWidget* createWidget(QWidget* parent) { return new Gui::PrefFontBox(parent); } @@ -1616,7 +1577,7 @@ public: } QIcon icon() const { - return QIcon( QPixmap( fontbox_pixmap ) ); + return QIcon(QPixmap(fontbox_pixmap)); } QString includeFile() const { @@ -1680,14 +1641,13 @@ static char *listbox_pixmap[]={ ".c#bb............#b##.", "...################..."}; */ -CustomWidgetPlugin::CustomWidgetPlugin(QObject *parent) - : QObject(parent) -{ -} +CustomWidgetPlugin::CustomWidgetPlugin(QObject* parent) + : QObject(parent) +{} -QList CustomWidgetPlugin::customWidgets () const +QList CustomWidgetPlugin::customWidgets() const { - QList cw; + QList cw; cw.append(new UrlLabelPlugin); cw.append(new LocationWidgetPlugin); cw.append(new FileChooserPlugin); @@ -1714,4 +1674,3 @@ QList CustomWidgetPlugin::customWidgets () con cw.append(new PrefQuantitySpinBoxPlugin); return cw; } - diff --git a/src/Tools/plugins/widget/plugin.h b/src/Tools/plugins/widget/plugin.h index 922d65d20e..6accfb5d75 100644 --- a/src/Tools/plugins/widget/plugin.h +++ b/src/Tools/plugins/widget/plugin.h @@ -26,14 +26,13 @@ class QDesignerFormEditorInterface; -class CustomWidgetPlugin : public QObject, public QDesignerCustomWidgetCollectionInterface +class CustomWidgetPlugin: public QObject, public QDesignerCustomWidgetCollectionInterface { Q_OBJECT Q_INTERFACES(QDesignerCustomWidgetCollectionInterface) Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QDesignerCustomWidgetCollectionInterface") public: - CustomWidgetPlugin(QObject *parent = 0); - QList customWidgets () const; + CustomWidgetPlugin(QObject* parent = 0); + QList customWidgets() const; }; - diff --git a/src/Tools/plugins/widget/wizard.cpp b/src/Tools/plugins/widget/wizard.cpp index 6aae3ac0af..e9cc2f3297 100644 --- a/src/Tools/plugins/widget/wizard.cpp +++ b/src/Tools/plugins/widget/wizard.cpp @@ -25,11 +25,11 @@ #include "wizard.h" -Wizard::Wizard(QWidget *parent) +Wizard::Wizard(QWidget* parent) : QDialog(parent) { textLabel = new QLabel(); - + topLine = new QFrame(); topLine->setFrameShape(QFrame::HLine); topLine->setFrameShadow(QFrame::Sunken); @@ -45,14 +45,10 @@ Wizard::Wizard(QWidget *parent) _finishButton = new QPushButton(tr("&Finish")); _finishButton->setDisabled(true); - connect(_cancelButton, SIGNAL(clicked()), - this, SLOT(reject())); - connect(_backButton, SIGNAL(clicked()), - this, SLOT(backButtonClicked())); - connect(_nextButton, SIGNAL(clicked()), - this, SLOT(nextButtonClicked())); - connect(_finishButton, SIGNAL(clicked()), - this, SLOT(accept())); + connect(_cancelButton, SIGNAL(clicked()), this, SLOT(reject())); + connect(_backButton, SIGNAL(clicked()), this, SLOT(backButtonClicked())); + connect(_nextButton, SIGNAL(clicked()), this, SLOT(nextButtonClicked())); + connect(_finishButton, SIGNAL(clicked()), this, SLOT(accept())); buttonLayout = new QHBoxLayout; buttonLayout->addStretch(1); @@ -77,19 +73,19 @@ QSize Wizard::sizeHint() const return QSize(200, 150); } -void Wizard::addPage(QWidget *page) +void Wizard::addPage(QWidget* page) { insertPage(count(), page); } void Wizard::removePage(int index) { - QWidget *widget = stackWidget->widget(index); + QWidget* widget = stackWidget->widget(index); stackWidget->removeWidget(widget); index = currentIndex(); _backButton->setEnabled(index > 0); - _nextButton->setEnabled(index < count()-1); + _nextButton->setEnabled(index < count() - 1); } int Wizard::count() const @@ -102,7 +98,7 @@ int Wizard::currentIndex() const return stackWidget->currentIndex(); } -void Wizard::insertPage(int index, QWidget *page) +void Wizard::insertPage(int index, QWidget* page) { page->setParent(stackWidget); @@ -119,21 +115,21 @@ void Wizard::insertPage(int index, QWidget *page) int current = currentIndex(); _backButton->setEnabled(current > 0); - _nextButton->setEnabled(current < count()-1); + _nextButton->setEnabled(current < count() - 1); } void Wizard::backButtonClicked() { int index = currentIndex(); if (index > 0) - setCurrentIndex(index-1); + setCurrentIndex(index - 1); } void Wizard::nextButtonClicked() { int index = currentIndex(); - if (index < count()-1) - setCurrentIndex(index+1); + if (index < count() - 1) + setCurrentIndex(index + 1); } QPushButton* Wizard::backButton() const @@ -152,7 +148,7 @@ void Wizard::setCurrentIndex(int index) stackWidget->setCurrentIndex(index); textLabel->setText(stackWidget->currentWidget()->windowTitle()); _backButton->setEnabled(index > 0); - _nextButton->setEnabled(index < count()-1); + _nextButton->setEnabled(index < count() - 1); Q_EMIT currentIndexChanged(index); } } @@ -167,20 +163,20 @@ QString Wizard::pageTitle() const return stackWidget->currentWidget()->windowTitle(); } -void Wizard::setPageTitle(QString const &newTitle) +void Wizard::setPageTitle(QString const& newTitle) { stackWidget->currentWidget()->setWindowTitle(newTitle); textLabel->setText(newTitle); Q_EMIT pageTitleChanged(newTitle); } -WizardExtension::WizardExtension(Wizard *widget, QObject *parent) - : QObject(parent) +WizardExtension::WizardExtension(Wizard* widget, QObject* parent) + : QObject(parent) { myWidget = widget; } -void WizardExtension::addWidget(QWidget *widget) +void WizardExtension::addWidget(QWidget* widget) { myWidget->addPage(widget); } @@ -195,7 +191,7 @@ int WizardExtension::currentIndex() const return myWidget->currentIndex(); } -void WizardExtension::insertWidget(int index, QWidget *widget) +void WizardExtension::insertWidget(int index, QWidget* widget) { myWidget->insertPage(index, widget); } @@ -215,17 +211,19 @@ QWidget* WizardExtension::widget(int index) const return myWidget->widget(index); } -WizardExtensionFactory::WizardExtensionFactory(QExtensionManager *parent) +WizardExtensionFactory::WizardExtensionFactory(QExtensionManager* parent) : QExtensionFactory(parent) {} -QObject *WizardExtensionFactory::createExtension(QObject *object, const QString &iid, QObject *parent) const +QObject* WizardExtensionFactory::createExtension(QObject* object, const QString& iid, + QObject* parent) const { - Wizard *widget = qobject_cast(object); + Wizard* widget = qobject_cast(object); if (widget && (iid == Q_TYPEID(QDesignerContainerExtension))) { return new WizardExtension(widget, parent); - } else { + } + else { return 0; } } diff --git a/src/Tools/plugins/widget/wizard.h b/src/Tools/plugins/widget/wizard.h index 962dda8643..02d8da75e8 100644 --- a/src/Tools/plugins/widget/wizard.h +++ b/src/Tools/plugins/widget/wizard.h @@ -25,9 +25,9 @@ #define WIZARD_H +#include #include #include -#include class QLabel; class QFrame; @@ -37,30 +37,30 @@ class QHBoxLayout; class QVBoxLayout; class QExtensionManager; -class Wizard : public QDialog +class Wizard: public QDialog { Q_OBJECT Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex) Q_PROPERTY(QString pageTitle READ pageTitle WRITE setPageTitle STORED false) public: - Wizard(QWidget *parent = 0); + Wizard(QWidget* parent = 0); QSize sizeHint() const; - void addPage(QWidget *page); + void addPage(QWidget* page); void removePage(int index); int count() const; int currentIndex() const; - void insertPage(int index, QWidget *page); + void insertPage(int index, QWidget* page); void setCurrentIndex(int index); - QWidget *widget(int index); + QWidget* widget(int index); QPushButton* backButton() const; QPushButton* nextButton() const; QString pageTitle() const; - void setPageTitle(QString const &newTitle); + void setPageTitle(QString const& newTitle); public Q_SLOTS: void backButtonClicked(); @@ -68,52 +68,52 @@ public Q_SLOTS: Q_SIGNALS: void currentIndexChanged(int index); - void pageTitleChanged(const QString &title); + void pageTitleChanged(const QString& title); private: - QLabel *textLabel; + QLabel* textLabel; QFrame* topLine; QFrame* bottomLine; - QStackedWidget *stackWidget; - QPushButton *_cancelButton; - QPushButton *_backButton; - QPushButton *_nextButton; - QPushButton *_finishButton; - QHBoxLayout *buttonLayout; - QVBoxLayout *mainLayout; + QStackedWidget* stackWidget; + QPushButton* _cancelButton; + QPushButton* _backButton; + QPushButton* _nextButton; + QPushButton* _finishButton; + QHBoxLayout* buttonLayout; + QVBoxLayout* mainLayout; }; -class WizardExtension : public QObject, public QDesignerContainerExtension +class WizardExtension: public QObject, public QDesignerContainerExtension { Q_OBJECT Q_INTERFACES(QDesignerContainerExtension) public: - WizardExtension(Wizard *widget, QObject *parent); + WizardExtension(Wizard* widget, QObject* parent); int count() const; - QWidget *widget(int index) const; + QWidget* widget(int index) const; int currentIndex() const; void setCurrentIndex(int index); - void addWidget(QWidget *widget); - void insertWidget(int index, QWidget *widget); + void addWidget(QWidget* widget); + void insertWidget(int index, QWidget* widget); void remove(int index); private: - Wizard *myWidget; + Wizard* myWidget; }; class QExtensionManager; -class WizardExtensionFactory : public QExtensionFactory +class WizardExtensionFactory: public QExtensionFactory { Q_OBJECT public: - WizardExtensionFactory(QExtensionManager *parent = 0); + WizardExtensionFactory(QExtensionManager* parent = 0); protected: - QObject *createExtension(QObject *object, const QString &iid, QObject *parent) const; + QObject* createExtension(QObject* object, const QString& iid, QObject* parent) const; }; #endif diff --git a/src/Tools/pythondoc.py b/src/Tools/pythondoc.py index eb8eaadd88..5e0547efab 100644 --- a/src/Tools/pythondoc.py +++ b/src/Tools/pythondoc.py @@ -5,84 +5,87 @@ import pydoc, pkgutil, sys, os, dircache, zipfile + def generateDoc(): - # Get the path to the FreeCAD module relative to this directory - toolspath = os.path.dirname(__file__) - homepath = toolspath + '/../../' - homepath = os.path.realpath(homepath) - binpath = os.path.join(homepath, 'bin') - docpath = os.path.join(homepath, 'doc') - modpath = os.path.join(homepath, 'Mod') + # Get the path to the FreeCAD module relative to this directory + toolspath = os.path.dirname(__file__) + homepath = toolspath + "/../../" + homepath = os.path.realpath(homepath) + binpath = os.path.join(homepath, "bin") + docpath = os.path.join(homepath, "doc") + modpath = os.path.join(homepath, "Mod") - # Change to the doc directory - cwd = os.getcwd() - print('Change to ' + docpath) - os.chdir(homepath) - if os.path.exists('doc') == False: - os.mkdir('doc') - os.chdir('doc') + # Change to the doc directory + cwd = os.getcwd() + print("Change to " + docpath) + os.chdir(homepath) + if os.path.exists("doc") == False: + os.mkdir("doc") + os.chdir("doc") - # Add the bin path to the system path - if os.name == 'nt': - os.environ['PATH'] = os.environ['PATH'] + ';' + binpath - else: - os.environ['PATH'] = os.environ['PATH'] + ':' + binpath + # Add the bin path to the system path + if os.name == "nt": + os.environ["PATH"] = os.environ["PATH"] + ";" + binpath + else: + os.environ["PATH"] = os.environ["PATH"] + ":" + binpath - # Import FreeCAD module - sys.path.append(binpath) - print('Write documentation for module \'FreeCAD\'') - pydoc.writedoc('FreeCAD') - print('') + # Import FreeCAD module + sys.path.append(binpath) + print("Write documentation for module 'FreeCAD'") + pydoc.writedoc("FreeCAD") + print("") - # Module directory - ModDirs = dircache.listdir(modpath) + # Module directory + ModDirs = dircache.listdir(modpath) - # Search for module paths and append them to Python path - #for Dir in ModDirs: - # if (Dir != '__init__.py'): - # sys.path.append( os.path.join(modpath,Dir) ) + # Search for module paths and append them to Python path + # for Dir in ModDirs: + # if (Dir != '__init__.py'): + # sys.path.append( os.path.join(modpath,Dir) ) - # Walk through the module paths again and try loading the modules to create HTML files - for Dir in ModDirs: - dest = os.path.join(modpath,Dir) - print('Write documentation for module \'' + Dir + '\'') - if (Dir != '__init__.py'): - writedocs(dest) - print('') + # Walk through the module paths again and try loading the modules to create HTML files + for Dir in ModDirs: + dest = os.path.join(modpath, Dir) + print("Write documentation for module '" + Dir + "'") + if Dir != "__init__.py": + writedocs(dest) + print("") - # Now we must create a document and create instances of all Python classes which - # cannot be directly created by a module. + # Now we must create a document and create instances of all Python classes which + # cannot be directly created by a module. - # Create a ZIP archive from all HTML files - print('Creating ZIP archive \'docs.zip\'...') - zip = zipfile.ZipFile('docs.zip', 'w') - for file in os.listdir('.'): - if not os.path.isdir(file): - if file.find('.html') > 0: - print(' Adding file ' + file + ' to archive') - zip.write(file) + # Create a ZIP archive from all HTML files + print("Creating ZIP archive 'docs.zip'...") + zip = zipfile.ZipFile("docs.zip", "w") + for file in os.listdir("."): + if not os.path.isdir(file): + if file.find(".html") > 0: + print(" Adding file " + file + " to archive") + zip.write(file) - print('done.') - zip.close() + print("done.") + zip.close() - # Remove all HTML files - print('Cleaning up HTML files...') - for file in os.listdir('.'): - if not os.path.isdir(file): - if file.find('.html') > 0: - print(' Removing ' + file) - os.remove(file) + # Remove all HTML files + print("Cleaning up HTML files...") + for file in os.listdir("."): + if not os.path.isdir(file): + if file.find(".html") > 0: + print(" Removing " + file) + os.remove(file) - os.chdir(cwd) - print('done.') + os.chdir(cwd) + print("done.") -def writedocs(dir, pkgpath=''): + +def writedocs(dir, pkgpath=""): """Write out HTML documentation for all modules in a directory tree.""" for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath): - # Ignore all debug modules - if modname[-2:] != '_d': - pydoc.writedoc(modname) + # Ignore all debug modules + if modname[-2:] != "_d": + pydoc.writedoc(modname) return + if __name__ == "__main__": - generateDoc() + generateDoc() diff --git a/src/Tools/updatecrowdin.py b/src/Tools/updatecrowdin.py index 2882f846ad..22312f2df7 100755 --- a/src/Tools/updatecrowdin.py +++ b/src/Tools/updatecrowdin.py @@ -197,9 +197,7 @@ locations = [ ], ] -THRESHOLD = ( - 25 # how many % must be translated for the translation to be included in FreeCAD -) +THRESHOLD = 25 # how many % must be translated for the translation to be included in FreeCAD class CrowdinUpdater: @@ -270,9 +268,7 @@ class CrowdinUpdater: ) print(f"{filename} updated") else: - self._make_project_api_req( - "/files", data={"storageId": storage_id, "name": filename} - ) + self._make_project_api_req("/files", data={"storageId": storage_id, "name": filename}) print(f"{filename} uploaded") def status(self): @@ -281,9 +277,7 @@ class CrowdinUpdater: def download(self, build_id): filename = f"{self.project_identifier}.zip" - response = self._make_project_api_req( - f"/translations/builds/{build_id}/download" - ) + response = self._make_project_api_req(f"/translations/builds/{build_id}/download") urlretrieve(response["url"], filename) print("download of " + filename + " complete") @@ -383,9 +377,7 @@ def updateTranslatorCpp(lncode): "updates the Translator.cpp file with the given translation entry" - cppfile = os.path.join( - os.path.dirname(__file__), "..", "Gui", "Language", "Translator.cpp" - ) + cppfile = os.path.join(os.path.dirname(__file__), "..", "Gui", "Language", "Translator.cpp") l = QtCore.QLocale(lncode) lnname = l.languageToString(l.language()) @@ -412,13 +404,7 @@ def updateTranslatorCpp(lncode): sys.exit() # inserting new entry just before the above line - line = ( - ' d->mapLanguageTopLevelDomain[QT_TR_NOOP("' - + lnname - + '")] = "' - + lncode - + '";\n' - ) + line = ' d->mapLanguageTopLevelDomain[QT_TR_NOOP("' + lnname + '")] = "' + lncode + '";\n' cppcode.insert(pos, line) print(lnname + " (" + lncode + ") added Translator.cpp") @@ -480,9 +466,7 @@ def applyTranslations(languages): src = os.path.join(currentfolder, "freecad.zip") dst = os.path.join(tempfolder, "freecad.zip") if not os.path.exists(src): - print( - 'freecad.zip file not found! Aborting. Run "download" command before this one.' - ) + print('freecad.zip file not found! Aborting. Run "download" command before this one.') sys.exit() shutil.copyfile(src, dst) os.chdir(tempfolder) @@ -519,9 +503,7 @@ if __name__ == "__main__": if command == "status": status = updater.status() - status = sorted( - status, key=lambda item: item["translationProgress"], reverse=True - ) + status = sorted(status, key=lambda item: item["translationProgress"], reverse=True) print( len([item for item in status if item["translationProgress"] > THRESHOLD]), " languages with status > " + str(THRESHOLD) + "%:", @@ -555,9 +537,7 @@ if __name__ == "__main__": elif command == "build-status": for item in updater.build_status(): - print( - f" id: {item['id']} progress: {item['progress']}% status: {item['status']}" - ) + print(f" id: {item['id']} progress: {item['progress']}% status: {item['status']}") elif command == "build": updater.build() @@ -603,13 +583,9 @@ if __name__ == "__main__": elif command in ["apply", "install"]: print("retrieving list of languages...") status = updater.status() - status = sorted( - status, key=lambda item: item["translationProgress"], reverse=True - ) + status = sorted(status, key=lambda item: item["translationProgress"], reverse=True) languages = [ - item["languageId"] - for item in status - if item["translationProgress"] > THRESHOLD + item["languageId"] for item in status if item["translationProgress"] > THRESHOLD ] applyTranslations(languages) print("Updating Translator.cpp...") @@ -619,13 +595,9 @@ if __name__ == "__main__": elif command == "updateTranslator": print("retrieving list of languages...") status = updater.status() - status = sorted( - status, key=lambda item: item["translationProgress"], reverse=True - ) + status = sorted(status, key=lambda item: item["translationProgress"], reverse=True) languages = [ - item["languageId"] - for item in status - if item["translationProgress"] > THRESHOLD + item["languageId"] for item in status if item["translationProgress"] > THRESHOLD ] print("Updating Translator.cpp...") for ln in languages: diff --git a/src/Tools/updateppa.py b/src/Tools/updateppa.py index 52248ae13e..c763ca6def 100644 --- a/src/Tools/updateppa.py +++ b/src/Tools/updateppa.py @@ -9,22 +9,23 @@ from tempfile import gettempdir from bzrlib.branch import Branch from bzrlib.workingtree import WorkingTree + def runUpdate(filename): branch = "versioning.git" - REMOTE_URL="bzr+ssh://bazaar.launchpad.net/~freecad-maintainers/freecad/%s" % (branch) - LOCAL_BRANCH=path.join(gettempdir(),branch) + REMOTE_URL = "bzr+ssh://bazaar.launchpad.net/~freecad-maintainers/freecad/%s" % (branch) + LOCAL_BRANCH = path.join(gettempdir(), branch) # Location of branch on Launchpad remote_branch = Branch.open(REMOTE_URL) # Location of branch on local system local_branch = remote_branch.bzrdir.sprout(LOCAL_BRANCH).open_branch() - False if local_branch.__name__ else True # "Use" to silence analyzers, pending PEP 640 or similar + False if local_branch.__name__ else True # "Use" to silence analyzers, pending PEP 640 or similar # Change a file in the local branch try: - wf = open(LOCAL_BRANCH + "/src/Build/Version.h", 'w') - rf = open(filename, 'r') + wf = open(LOCAL_BRANCH + "/src/Build/Version.h", "w") + rf = open(filename, "r") except IOError as error: raise error else: @@ -36,11 +37,13 @@ def runUpdate(filename): tree.commit("Update version number") # Push back to Launchpad - #transport = get_transport(PUSHTO_URL) - #local_branch.create_clone_on_transport(transport) + # transport = get_transport(PUSHTO_URL) + # local_branch.create_clone_on_transport(transport) + def main(): runUpdate(sys.argv[1]) + if __name__ == "__main__": main() diff --git a/src/Tools/updatets.py b/src/Tools/updatets.py index ce668739a3..3d02ae3dbb 100755 --- a/src/Tools/updatets.py +++ b/src/Tools/updatets.py @@ -282,13 +282,9 @@ def update_translation(entry): f"touch dummy_cpp_file_for_lupdate.cpp" ) # lupdate 5.x requires at least one source file to process the UI files execline.append(f"touch {tsBasename}py.ts") - execline.append( - f'{PYLUPDATE} `find ./ -name "*.py"` -ts {tsBasename}py.ts {log_redirect}' - ) + execline.append(f'{PYLUPDATE} `find ./ -name "*.py"` -ts {tsBasename}py.ts {log_redirect}') execline.append(f"{QMAKE} -project -o {project_filename} -r") - execline.append( - f"{LUPDATE} {project_filename} -ts {tsBasename}.ts {log_redirect}" - ) + execline.append(f"{LUPDATE} {project_filename} -ts {tsBasename}.ts {log_redirect}") execline.append( f"sed 's/.*<\/translation>/<\/translation>/g' {tsBasename}.ts > {tsBasename}.ts.temp" )