Tools: Apply pre-commit autoformatting

This commit is contained in:
Chris Hennes
2023-04-22 12:53:49 -05:00
parent 74561536af
commit 4a7e1b6d9b
105 changed files with 6814 additions and 5407 deletions

View File

@@ -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:

View File

@@ -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 <path to Version.h> [--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()

View File

@@ -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")

View File

@@ -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

View File

@@ -1 +1 @@
FreeCAD is distributed under the Gnu General Public Licence.
FreeCAD is distributed under the Gnu General Public Licence.

View File

@@ -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()

View File

@@ -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/<Application>
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/<Application>
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 <Application>
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")

View File

@@ -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])

View File

@@ -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()
main()

View File

@@ -1,25 +1,25 @@
#***************************************************************************
#* Copyright (c) 2002 Jürgen Riegel <juergen.riegel@web.de> *
#* *
#* 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 <juergen.riegel@web.de> *
# * *
# * 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"
)

View File

@@ -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()

View File

@@ -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")

View File

@@ -25,7 +25,7 @@
#include <qapplication.h>
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;
}

View File

@@ -31,7 +31,8 @@
#include <qvalidator.h>
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;

View File

@@ -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

View File

@@ -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 = "<li class=\"branch\"><a href="
pattern = '<li class="branch"><a href='
start = html.find(pattern) + len(pattern)
end = html.find("\n", start)
link = html[start:end]
@@ -201,7 +230,7 @@ class DebianGitHub(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
@@ -209,84 +238,99 @@ class DebianGitHub(VersionControl):
def printInfo(self):
print("Debian/GitHub")
class GitControl(VersionControl):
#http://www.hermanradtke.com/blog/canonical-version-numbers-with-git/
#http://blog.marcingil.com/2011/11/creating-build-numbers-using-git-commits/
#http://gitref.org/remotes/#fetch
#http://cworth.org/hgbook-git/tour/
#http://git.or.cz/course/svn.html
#git help log
# http://www.hermanradtke.com/blog/canonical-version-numbers-with-git/
# http://blog.marcingil.com/2011/11/creating-build-numbers-using-git-commits/
# http://gitref.org/remotes/#fetch
# http://cworth.org/hgbook-git/tour/
# http://git.or.cz/course/svn.html
# git help log
def getremotes(self):
"""return a mapping of remotes and their fetch urls"""
rr=os.popen("git remote -v")
rrstr=rr.read().strip()
if rr.close() is None: # exit code == 0
self.remotes=dict(l[:-8].split('\t') for l in rrstr.splitlines() \
if l.endswith(' (fetch)'))
self.branchlst=os.popen("git show -s --pretty=%d HEAD").read()\
.strip(" ()\n").split(', ') #used for possible remotes
rr = os.popen("git remote -v")
rrstr = rr.read().strip()
if rr.close() is None: # exit code == 0
self.remotes = dict(
l[:-8].split("\t") for l in rrstr.splitlines() if l.endswith(" (fetch)")
)
self.branchlst = (
os.popen("git show -s --pretty=%d HEAD").read().strip(" ()\n").split(", ")
) # used for possible remotes
def geturl(self):
urls=[]
urls = []
for ref in self.branchlst:
if '/' in ref:
remote,branch = ref.split('/',1)
if "/" in ref:
remote, branch = ref.split("/", 1)
if remote in self.remotes:
url=self.remotes[remote]
#rewrite github to public url
match = re.match('git@github\.com:(\S+?)/(\S+\.git)',url) \
or re.match('https://github\.com/(\S+)/(\S+\.git)'\
,url)
url = self.remotes[remote]
# rewrite github to public url
match = re.match("git@github\.com:(\S+?)/(\S+\.git)", url) or re.match(
"https://github\.com/(\S+)/(\S+\.git)", url
)
if match is not None:
url = 'git://github.com/%s/%s' % match.groups()
match = re.match('ssh://\S+?@(\S+)',url)
url = "git://github.com/%s/%s" % match.groups()
match = re.match("ssh://\S+?@(\S+)", url)
if match is not None:
url = 'git://%s' % match.group(1)
entryscore=(url == "git://github.com/FreeCAD/FreeCAD.git",\
'github.com' in url,branch==self.branch,\
branch=='master', '@' not in url)
#used for sorting the list
if branch==self.branch: #add branch name
url = '%s %s' % (url,branch)
urls.append((entryscore,url))
url = "git://%s" % match.group(1)
entryscore = (
url == "git://github.com/FreeCAD/FreeCAD.git",
"github.com" in url,
branch == self.branch,
branch == "master",
"@" not in url,
)
# used for sorting the list
if branch == self.branch: # add branch name
url = "%s %s" % (url, branch)
urls.append((entryscore, url))
if len(urls) > 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()

View File

@@ -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;
}
}

View File

@@ -23,7 +23,7 @@
#pragma once
class CClassFactory : public IClassFactory
class CClassFactory: public IClassFactory
{
private:
LONG m_cRef;

View File

@@ -23,12 +23,12 @@
#pragma once
#include <windows.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <thumbcache.h>
#include <tchar.h>
#include <strsafe.h>
#include <tchar.h>
#include <thumbcache.h>
#include <windows.h>
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);

View File

@@ -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 <config.h>
# endif // HAVE_CONFIG_H
# endif
#ifndef FC_OS_WIN32
#define FC_OS_WIN32
#endif
#if defined(__MINGW32__)
#if HAVE_CONFIG_H
#include <config.h>
#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

View File

@@ -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;
}
}

View File

@@ -23,14 +23,14 @@
#pragma warning(disable : 4995)
#include "Common.h"
#include "ThumbnailProvider.h"
#include "Common.h"
#include <iostream>
#include <zipios++/zipinputstream.h>
#include <zipios++/zipfile.h>
#include <wincodec.h>
#include <wincodecsdk.h>
#include <zipios++/zipfile.h>
#include <zipios++/zipinputstream.h>
#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<void**>(&ipDecoder))))
if (FAILED(CoCreateInstance(CLSID_WICPngDecoder,
NULL,
CLSCTX_INPROC_SERVER,
__uuidof(ipDecoder),
reinterpret_cast<void**>(&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<BYTE*>(pvImageBits))))
{
if (FAILED(ipBitmap->CopyPixels(NULL, cbStride, cbImage, static_cast<BYTE*>(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<unsigned char> 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;
}

View File

@@ -4,4 +4,4 @@ EXPORTS
DllRegisterServer PRIVATE
DllUnregisterServer PRIVATE
DllGetClassObject PRIVATE
DllCanUnloadNow PRIVATE
DllCanUnloadNow PRIVATE

View File

@@ -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*);
};
};

View File

@@ -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)

View File

@@ -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())

View File

@@ -1,3 +1,2 @@
/** \defgroup TEMPLATE _TEMPLATEPY_
* \ingroup WORKBENCHES */

View File

@@ -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())

View File

@@ -23,7 +23,7 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#include <Python.h>
#endif
#include <Base/Console.h>
@@ -34,16 +34,19 @@
#include <CXX/Objects.hxx>
namespace _TEMPLATE_ {
class Module : public Py::ExtensionModule<Module>
namespace _TEMPLATE_
{
class Module: public Py::ExtensionModule<Module>
{
public:
Module() : Py::ExtensionModule<Module>("_TEMPLATE_")
Module()
: Py::ExtensionModule<Module>("_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 */

View File

@@ -21,4 +21,4 @@
***************************************************************************/
#include "PreCompiled.h"
#include "PreCompiled.h"

View File

@@ -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 <cstdio>
#include <cassert>
#include <cstdio>
#include <iostream>
// STL
@@ -55,7 +55,6 @@
// Xerces
#include <xercesc/util/XercesDefs.hpp>
#endif //_PreComp_
#endif//_PreComp_
#endif

View File

@@ -23,7 +23,7 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <Python.h>
#include <Python.h>
#endif
#include <Base/Console.h>
@@ -40,16 +40,19 @@
void Create_TEMPLATE_Commands(void);
namespace _TEMPLATE_Gui {
class Module : public Py::ExtensionModule<Module>
namespace _TEMPLATE_Gui
{
class Module: public Py::ExtensionModule<Module>
{
public:
Module() : Py::ExtensionModule<Module>("_TEMPLATE_Gui")
Module()
: Py::ExtensionModule<Module>("_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 */

View File

@@ -25,8 +25,8 @@
#ifndef _PreComp_
#endif
#include <Base/Console.h>
#include <App/Document.h>
#include <Base/Console.h>
#include <Gui/Application.h>
#include <Gui/Command.h>
@@ -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());
}

View File

@@ -21,4 +21,4 @@
***************************************************************************/
#include "PreCompiled.h"
#include "PreCompiled.h"

View File

@@ -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 <cstdio>
#include <cassert>
#include <cstdio>
// STL
#include <algorithm>
@@ -57,14 +57,14 @@
#include <xercesc/util/XercesDefs.hpp>
#ifdef FC_OS_WIN32
# include <windows.h>
#include <windows.h>
#endif
// Qt Toolkit
#ifndef __QtAll__
# include <Gui/QtAll.h>
#include <Gui/QtAll.h>
#endif
#endif //_PreComp_
#endif//_PreComp_
#endif // GUI_PRECOMPILED_H
#endif// GUI_PRECOMPILED_H

View File

@@ -1,5 +1,5 @@
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<qresource>
<file>icons/_TEMPLATE_Workbench.svg</file>
</qresource>
</RCC>
</RCC>

View File

@@ -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;
}

View File

@@ -26,9 +26,10 @@
#include <Gui/Workbench.h>
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

View File

@@ -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())

View File

@@ -1,3 +1,2 @@
/** \defgroup TEMPLATE _TEMPLATE_
* \ingroup WORKBENCHES */

View File

@@ -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

View File

@@ -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()

View File

@@ -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

View File

@@ -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 = """<RCC>
<qresource%s>
<qresource%s>
"""
hhcFooter=""" </qresource>
</RCC>
hhcFooter = """ </qresource>
</RCC>
"""
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(' <file>' + i + '</file>\n')
file.write(" <file>" + i + "</file>\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()

View File

@@ -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

View File

@@ -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_()

View File

@@ -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_()

View File

@@ -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_()

View File

@@ -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()

View File

@@ -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)
)

View File

@@ -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

View File

@@ -1,9 +1,9 @@
#include <QApplication>
#include <QDialog>
#include <QPushButton>
#include <QLibrary>
#include <QFileDialog>
#include <QLibrary>
#include <QPushButton>
QLibrary* freecadPlugin = nullptr;

View File

@@ -5,16 +5,16 @@
#include <QMessageBox>
#include <QVector>
#include <App/Application.h>
#include <Base/Factory.h>
#include <Base/Interpreter.h>
#include <App/Application.h>
#include <Gui/Application.h>
#include <Gui/MainWindow.h>
PyMODINIT_FUNC FreeCAD_init()
{
static QVector<char *> argv;
static QVector<char*> 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());
}
}

View File

@@ -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();
}

View File

@@ -1,11 +1,11 @@
#include <Python.h>
#include <string>
#include <sstream>
#include <QtGui>
#include <QtWidgets>
#include <sstream>
#include <string>
#if defined(Q_WS_X11)
# include <QX11EmbedContainer>
#include <QX11EmbedContainer>
#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"));
}

View File

@@ -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

View File

@@ -1,70 +1,63 @@
// FreeCAD_widget.cpp : Defines the entry point for the application.
//
#include "FreeCAD_widget.h"
#include "stdafx.h"
#include <Commdlg.h>
#include <Shlobj.h>
#include "FreeCAD_widget.h"
#include <string>
#include <sstream>
#include <string>
#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 <Python.h>
@@ -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) {

View File

@@ -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

View File

@@ -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

View File

@@ -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 <windows.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <stdlib.h>
#include <tchar.h>

View File

@@ -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

View File

@@ -1,17 +1,21 @@
#include <stdlib.h>
#include <gtk/gtk.h>
#include <Python.h>
#include <gtk/gtk.h>
#include <stdlib.h>
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;
}

View File

@@ -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()

View File

@@ -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)

View File

@@ -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

View File

@@ -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

View File

@@ -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/<Application>
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/<Application>
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 <Application>
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]

View File

@@ -1,64 +1,69 @@
#***************************************************************************
#* Copyright (c) 2003 Werner Mayer <werner.wm.mayer@gmx.de> *
#* *
#* 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 <werner.wm.mayer@gmx.de> *
# * *
# * 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/<Application>
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/<Application>
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 <Application>
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]

View File

@@ -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)

View File

@@ -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)

View File

@@ -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)

View File

@@ -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$"]

View File

@@ -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

View File

@@ -1,25 +1,25 @@
#***************************************************************************
#* Copyright (c) 2002 Juergen Riegel <juergen.riegel@web.de> *
#* *
#* 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 <juergen.riegel@web.de> *
# * *
# * 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(["<Include>\n",
" <?define FCVersionMajor ="+FCVersionMajor[23:-1] + " ?>\n",
" <?define FCVersionMinor ="+FCVersionMinor[23:-1] + " ?>\n",
" <?define FCVersionBuild ="+ str(BuildNumber) + " ?>\n",
"</Include> \n"])
open("../Version.wxi", "w").writelines(
[
"<Include>\n",
" <?define FCVersionMajor =" + FCVersionMajor[23:-1] + " ?>\n",
" <?define FCVersionMinor =" + FCVersionMinor[23:-1] + " ?>\n",
" <?define FCVersionBuild =" + str(BuildNumber) + " ?>\n",
"</Include> \n",
]
)

View File

@@ -2,32 +2,32 @@
# -*- coding: utf8 -*-
#***************************************************************************
#* *
#* Copyright (c) 2015 Yorik van Havre <yorik@uncreated.net> *
#* *
#* 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 <yorik@uncreated.net> *
# * *
# * 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 <document> tag into the main one
doc = re.sub(b"<\/Document>",b"",doc,flags=re.MULTILINE|re.DOTALL)
guidoc = re.sub(b"<Document.*?>",b" ",guidoc,flags=re.MULTILINE|re.DOTALL)
doc = re.sub(b"<\/Document>", b"", doc, flags=re.MULTILINE | re.DOTALL)
guidoc = re.sub(b"<Document.*?>", 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))

View File

@@ -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]

View File

@@ -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__":

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -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<last:
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 < last:
line = block[i]
match = self.restat.match(line)
if match: # a statement starts "here" (at line block[i])
if match: # a statement starts "here" (at line block[i])
# i is the last line to _not_ process
stat = match.string[match.end(0):].strip()
j=i+1 # look for 'finish' from here onwards
nest=1 # count nesting levels of statements
while j<last:
stat = match.string[match.end(0) :].strip()
j = i + 1 # look for 'finish' from here onwards
nest = 1 # count nesting levels of statements
while j < last:
line = block[j]
# first look for nested statements or 'finish' lines
if self.restend.match(line): # found a statement-end
nest = nest - 1 # update (decrease) nesting
if nest==0: break # j is first line to _not_ process
elif self.restat.match(line): # found a nested statement
nest = nest + 1 # update (increase) nesting
elif nest==1: # look for continuation only at this nesting
if self.restend.match(line): # found a statement-end
nest = nest - 1 # update (decrease) nesting
if nest == 0:
break # j is first line to _not_ process
elif self.restat.match(line): # found a nested statement
nest = nest + 1 # update (increase) nesting
elif nest == 1: # look for continuation only at this nesting
match = self.recont.match(line)
if match: # found a contin.-statement
nestat = match.string[match.end(0):].strip()
stat = '%s _cb(%s,%s)\n%s' % (stat,i+1,j,nestat)
i=j # again, i is the last line to _not_ process
j=j+1
stat = self.preproc(stat, 'exec')
stat = '%s _cb(%s,%s)' % (stat,i+1,j)
if match: # found a contin.-statement
nestat = match.string[match.end(0) :].strip()
stat = "%s _cb(%s,%s)\n%s" % (stat, i + 1, j, nestat)
i = j # again, i is the last line to _not_ process
j = j + 1
stat = self.preproc(stat, "exec")
stat = "%s _cb(%s,%s)" % (stat, i + 1, j)
# for debugging, uncomment...: print("-> 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)

View File

@@ -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!")

View File

@@ -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 = """
/***************************************************************************

View File

@@ -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;
}
-

View File

@@ -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()

View File

@@ -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()

View File

@@ -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"

View File

@@ -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 = """
/***************************************************************************

View File

@@ -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!")

View File

@@ -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"))

View File

@@ -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

View File

@@ -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()

File diff suppressed because it is too large Load Diff

View File

@@ -46,18 +46,18 @@
#include "qsvgiohandler.h"
#include <qiodevice.h>
#include <qbytearray.h>
#include <qdebug.h>
#include <qiodevice.h>
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

View File

@@ -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("<?xml") || buf.contains("<svg")) {
}
else if (buf.contains("<?xml") || buf.contains("<svg")) {
setFormat("svg");
return true;
}
@@ -169,14 +171,15 @@ QByteArray QSvgIOHandler::name() const
}
bool QSvgIOHandler::read(QImage *image)
bool QSvgIOHandler::read(QImage* image)
{
if (!d->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<QColor>();
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<QColor>();
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("<?xml") || buf.contains("<svg");
@@ -302,4 +304,4 @@ bool QSvgIOHandler::canRead(QIODevice *device)
QT_END_NAMESPACE
#endif // QT_NO_SVGRENDERER
#endif// QT_NO_SVGRENDERER

View File

@@ -54,24 +54,24 @@ class QIODevice;
class QVariant;
class QSvgIOHandlerPrivate;
class QSvgIOHandler : public QImageIOHandler
class QSvgIOHandler: public QImageIOHandler
{
public:
QSvgIOHandler();
~QSvgIOHandler();
virtual bool canRead() const;
virtual QByteArray name() const;
virtual bool read(QImage *image);
static bool canRead(QIODevice *device);
virtual bool read(QImage* image);
static bool canRead(QIODevice* device);
virtual QVariant option(ImageOption option) const;
virtual void setOption(ImageOption option, const QVariant & value);
virtual void setOption(ImageOption option, const QVariant& value);
virtual bool supportsOption(ImageOption option) const;
private:
QSvgIOHandlerPrivate *d;
QSvgIOHandlerPrivate* d;
};
QT_END_NAMESPACE
#endif // QT_NO_SVGRENDERER
#endif // QSVGIOHANDLER_H
#endif// QT_NO_SVGRENDERER
#endif// QSVGIOHANDLER_H

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -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<QDesignerCustomWidgetInterface *> customWidgets () const;
CustomWidgetPlugin(QObject* parent = 0);
QList<QDesignerCustomWidgetInterface*> customWidgets() const;
};

View File

@@ -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<Wizard*>(object);
Wizard* widget = qobject_cast<Wizard*>(object);
if (widget && (iid == Q_TYPEID(QDesignerContainerExtension))) {
return new WizardExtension(widget, parent);
} else {
}
else {
return 0;
}
}

Some files were not shown because too many files have changed in this diff Show More