FreeCAD WebAssembly development snapshot
Some checks failed
FreeCAD master CI / Prepare (push) Has been cancelled
FreeCAD master CI / Pixi (push) Has been cancelled
FreeCAD master CI / Ubuntu (push) Has been cancelled
FreeCAD master CI / Windows (push) Has been cancelled
FreeCAD master CI / Lint (push) Has been cancelled
FreeCAD master CI / WrapUp (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
Stale Issues / stale (push) Has been cancelled
Some checks failed
FreeCAD master CI / Prepare (push) Has been cancelled
FreeCAD master CI / Pixi (push) Has been cancelled
FreeCAD master CI / Ubuntu (push) Has been cancelled
FreeCAD master CI / Windows (push) Has been cancelled
FreeCAD master CI / Lint (push) Has been cancelled
FreeCAD master CI / WrapUp (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
Stale Issues / stale (push) Has been cancelled
This commit is contained in:
18
src/Tools/.gitattributes
vendored
Normal file
18
src/Tools/.gitattributes
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
embedded export-ignore
|
||||
encode export-ignore
|
||||
ImageTools export-ignore
|
||||
offlinedoc export-ignore
|
||||
RegExp export-ignore
|
||||
thumbs export-ignore
|
||||
FreeCAD_widgets.sln export-ignore
|
||||
wizard.cpp export-ignore
|
||||
wizard.h export-ignore
|
||||
BuildDoc.py export-ignore
|
||||
BuildDocDoxy.cfg export-ignore
|
||||
astylerc export-ignore
|
||||
chm.css export-ignore
|
||||
examplePy2wiki.py export-ignore
|
||||
updateTranslations.py export-ignore
|
||||
updatets.py export-ignore
|
||||
wiki2chm.py export-ignore
|
||||
WixFileTool.py export-ignore
|
||||
2
src/Tools/.gitignore
vendored
Normal file
2
src/Tools/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
# ignore the pyc files created while compile
|
||||
*.pyc
|
||||
60
src/Tools/ArchiveNameFromVersionHeader.py
Normal file
60
src/Tools/ArchiveNameFromVersionHeader.py
Normal file
@@ -0,0 +1,60 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
###
|
||||
# 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
|
||||
|
||||
|
||||
def deserializeVersionHeader(path):
|
||||
version = {}
|
||||
try:
|
||||
dat = open(path, "r").readlines()
|
||||
except IOError:
|
||||
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('"', "")
|
||||
|
||||
return version
|
||||
|
||||
|
||||
def main():
|
||||
OSAbbrev = {"Windows": "WIN", "Darwin": "OSX"}
|
||||
SHA = None
|
||||
|
||||
if len(sys.argv) < 2:
|
||||
sys.stderr.write("Usage: archiveNameFromVersion <path to Version.h> [--git-SHA=]\n")
|
||||
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[2:], "g:", ["git-SHA="])
|
||||
except getopt.GetoptError:
|
||||
pass
|
||||
|
||||
for o, a in opts:
|
||||
if o in ("-g", "--git-SHA"):
|
||||
SHA = a
|
||||
|
||||
version = deserializeVersionHeader(sys.argv[1])
|
||||
if 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(),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
129
src/Tools/FCFileTools.py
Normal file
129
src/Tools/FCFileTools.py
Normal file
@@ -0,0 +1,129 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# 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()
|
||||
else:
|
||||
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
|
||||
fileTo.write(bytesFrom)
|
||||
# fileFrom.close()
|
||||
# fileTo.close()
|
||||
|
||||
|
||||
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)
|
||||
pathFrom = os.path.join(dirFrom, file)
|
||||
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)
|
||||
cpfile(pathFrom, pathTo)
|
||||
fcount = fcount + 1
|
||||
except Exception:
|
||||
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)
|
||||
try:
|
||||
os.mkdir(pathTo) # make new subdir
|
||||
cpall(pathFrom, pathTo) # recur into subdirs
|
||||
dcount = dcount + 1
|
||||
except Exception:
|
||||
print("Error creating ", pathTo, " -- skipped")
|
||||
print(sys.exc_info()[0], sys.exc_info()[1])
|
||||
|
||||
|
||||
def SetUpFilter(MatchList):
|
||||
RegList = []
|
||||
for regexp in MatchList:
|
||||
a = re.compile(regexp)
|
||||
RegList.append(a)
|
||||
return RegList
|
||||
|
||||
|
||||
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
|
||||
hitt = 0
|
||||
for matchpat in MatchList:
|
||||
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
|
||||
try:
|
||||
if verbose > 1:
|
||||
print("copying ", pathFrom, " to ", pathTo)
|
||||
cpfile(pathFrom, pathTo)
|
||||
fcount = fcount + 1
|
||||
except Exception:
|
||||
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)
|
||||
try:
|
||||
os.mkdir(pathTo) # make new subdir
|
||||
cpallWithFilter(pathFrom, pathTo, MatchList) # recur into subdirs
|
||||
dcount = dcount + 1
|
||||
except Exception:
|
||||
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
|
||||
# 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"
|
||||
################################################################
|
||||
|
||||
fcount = dcount = 0
|
||||
|
||||
|
||||
def rmall(dirPath): # delete dirPath and below
|
||||
global fcount, dcount
|
||||
namesHere = os.listdir(dirPath)
|
||||
for name in namesHere: # remove all contents first
|
||||
path = os.path.join(dirPath, name)
|
||||
if not os.path.isdir(path): # remove simple files
|
||||
os.remove(path)
|
||||
fcount = fcount + 1
|
||||
else: # recur to remove subdirs
|
||||
rmall(path)
|
||||
os.rmdir(dirPath) # remove now-empty dirPath
|
||||
dcount = dcount + 1
|
||||
1
src/Tools/InstallMsg.txt
Normal file
1
src/Tools/InstallMsg.txt
Normal file
@@ -0,0 +1 @@
|
||||
FreeCAD is distributed under the Gnu General Public Licence.
|
||||
99
src/Tools/LicenseChecker.py
Normal file
99
src/Tools/LicenseChecker.py
Normal file
@@ -0,0 +1,99 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2013 Werner Mayer LGPL
|
||||
#
|
||||
# Utility to search for source, header and Python files with a missing license text
|
||||
|
||||
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",
|
||||
]
|
||||
|
||||
|
||||
def startProcessing():
|
||||
fn = os.path.realpath(__file__)
|
||||
# get path of parent directory
|
||||
fn = os.path.dirname(fn)
|
||||
fn = os.path.dirname(fn)
|
||||
global ext
|
||||
global flt
|
||||
traverse(fn, ext, flt)
|
||||
|
||||
|
||||
def traverse(path, ext, flt):
|
||||
for r, d, f in os.walk(path):
|
||||
for i in f:
|
||||
fn = os.path.join(r, i)
|
||||
# filter out some file names
|
||||
stop = False
|
||||
for j in flt:
|
||||
if fn.find(j) >= 0:
|
||||
stop = True
|
||||
break
|
||||
if stop:
|
||||
continue
|
||||
bn = os.path.basename(fn).lower()
|
||||
for j in ext:
|
||||
if bn.endswith(j):
|
||||
parsefile(fn)
|
||||
break
|
||||
|
||||
|
||||
def parsefile(fn):
|
||||
data = codecs.open(fn, "r", "utf-8")
|
||||
try:
|
||||
lines = data.readlines()
|
||||
data.close()
|
||||
|
||||
global lic
|
||||
for i in lines:
|
||||
for j in lic:
|
||||
if i.find(j) >= 0:
|
||||
return
|
||||
|
||||
print("Missing license text in file %s") % (fn)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
startProcessing()
|
||||
37
src/Tools/MakeApp.py
Normal file
37
src/Tools/MakeApp.py
Normal file
@@ -0,0 +1,37 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2003 Werner Mayer LGPL
|
||||
# Create a new application module
|
||||
|
||||
import os, sys
|
||||
import MakeAppTools
|
||||
|
||||
|
||||
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)
|
||||
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")
|
||||
|
||||
# replace the _TEMPLATE_ string by <Application>
|
||||
sys.stdout.write("Modifying files...\n")
|
||||
MakeAppTools.replaceTemplate("../Mod/" + Application, "_TEMPLATE_", Application)
|
||||
# make the configure script executable
|
||||
# os.chmod("../Mod/" + Application + "/configure", 0777);
|
||||
sys.stdout.write("Modifying files done.\n")
|
||||
|
||||
sys.stdout.write(Application + " module created successfully.\n")
|
||||
85
src/Tools/MakeAppTools.py
Normal file
85
src/Tools/MakeAppTools.py
Normal file
@@ -0,0 +1,85 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
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
|
||||
"""
|
||||
for file in os.listdir(dirName):
|
||||
pathName = os.path.join(dirName, file)
|
||||
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
|
||||
for line in lines:
|
||||
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
|
||||
except Exception:
|
||||
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(sys.exc_info()[0], sys.exc_info()[1])
|
||||
|
||||
|
||||
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
|
||||
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
|
||||
hit = 0
|
||||
for matchpat in MatchFile:
|
||||
if re.match(matchpat, file):
|
||||
hit = 1
|
||||
break
|
||||
if hit:
|
||||
print("Ignore file " + file)
|
||||
continue
|
||||
try:
|
||||
if verbose > 1:
|
||||
print("copying ", pathFrom, " to ", pathTo)
|
||||
FCFileTools.cpfile(pathFrom, pathTo)
|
||||
fcount = fcount + 1
|
||||
except Exception:
|
||||
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):
|
||||
hit = 1
|
||||
break
|
||||
if hit:
|
||||
print("Ignore directory " + file)
|
||||
continue
|
||||
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
|
||||
except Exception:
|
||||
print("Error creating ", pathTo, " -- skipped")
|
||||
print(sys.exc_info()[0], sys.exc_info()[1])
|
||||
538
src/Tools/MakeMacBundleRelocatable.py
Executable file
538
src/Tools/MakeMacBundleRelocatable.py
Executable file
@@ -0,0 +1,538 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
import os
|
||||
import sys
|
||||
from subprocess import check_call, check_output
|
||||
import re
|
||||
import logging
|
||||
|
||||
# This script is intended to help copy dynamic libraries used by FreeCAD into
|
||||
# a Mac application bundle and change dyld commands as appropriate. There are
|
||||
# two key items that this currently does differently from other similar tools:
|
||||
#
|
||||
# * @rpath is used rather than @executable_path because the libraries need to
|
||||
# be loadable through a Python interpreter and the FreeCAD binaries.
|
||||
# * 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/",
|
||||
]
|
||||
|
||||
# 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
|
||||
# MacPorts or Homebrew won't end up in /Library/Frameworks, so we assume
|
||||
# that libraries found there aren't meant to be bundled.
|
||||
warnPaths = ["/Library/Frameworks/"]
|
||||
|
||||
# dynamically get homebrew prefix ie. `brew --prefix`
|
||||
brew_prefix = check_output(["brew", "--prefix"], text=True).strip()
|
||||
|
||||
|
||||
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
|
||||
if not children:
|
||||
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))
|
||||
|
||||
|
||||
class DepsGraph:
|
||||
graph = {}
|
||||
|
||||
def in_graph(self, node):
|
||||
return node.name in list(self.graph)
|
||||
|
||||
def add_node(self, node):
|
||||
self.graph[node.name] = node
|
||||
|
||||
def get_node(self, name):
|
||||
if name in self.graph:
|
||||
return self.graph[name]
|
||||
return None
|
||||
|
||||
def visit(self, operation, op_args=[]):
|
||||
""" "
|
||||
Perform a depth first visit of the graph, calling operation
|
||||
on each node.
|
||||
"""
|
||||
stack = []
|
||||
|
||||
for k in list(self.graph):
|
||||
self.graph[k]._marked = False
|
||||
|
||||
for k in list(self.graph):
|
||||
if not self.graph[k]._marked:
|
||||
stack.append(k)
|
||||
while stack:
|
||||
node_key = stack.pop()
|
||||
self.graph[node_key]._marked = True
|
||||
for ck in self.graph[node_key].children:
|
||||
if not self.graph[ck]._marked:
|
||||
stack.append(ck)
|
||||
operation(self, self.graph[node_key], *op_args)
|
||||
|
||||
|
||||
def is_macho(path):
|
||||
return b"Mach-O" in check_output(["file", path])
|
||||
|
||||
|
||||
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):
|
||||
return True
|
||||
for p in warnPaths:
|
||||
if lib.startswith(p):
|
||||
logging.warning("WARNING: library %s will not be bundled!" % lib)
|
||||
logging.warning("See MakeMacRelocatable.py for more information.")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def get_path(name, search_paths):
|
||||
for path in search_paths:
|
||||
full_path = os.path.join(path, name)
|
||||
if os.path.isfile(full_path):
|
||||
return path
|
||||
# also check if it's a symlink and resolve it
|
||||
if os.path.islink(full_path):
|
||||
real_path = os.path.realpath(full_path)
|
||||
if os.path.isfile(real_path):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def resolve_loader_path(lib_path, referencing_lib_path):
|
||||
"""
|
||||
resolve @loader_path in lib_path relative to referencing_lib_path
|
||||
"""
|
||||
if lib_path.startswith("@loader_path/"):
|
||||
# get directory containing the referencing library
|
||||
referencing_dir = os.path.dirname(referencing_lib_path)
|
||||
# replace @loader_path with referencing directory
|
||||
resolved_path = lib_path.replace("@loader_path/", referencing_dir + "/")
|
||||
return resolved_path
|
||||
return lib_path
|
||||
|
||||
|
||||
def get_rpaths_for_resolution(library_path):
|
||||
"""get rpaths from a library for resolving @rpath dependencies"""
|
||||
try:
|
||||
rpaths = get_rpaths(library_path)
|
||||
resolved_rpaths = []
|
||||
for rpath in rpaths:
|
||||
if rpath.startswith("@loader_path"):
|
||||
# resolve @loader_path in rpath
|
||||
lib_dir = os.path.dirname(library_path)
|
||||
resolved = rpath.replace("@loader_path", lib_dir)
|
||||
resolved_rpaths.append(resolved)
|
||||
else:
|
||||
resolved_rpaths.append(rpath)
|
||||
return resolved_rpaths
|
||||
except:
|
||||
return []
|
||||
|
||||
|
||||
def resolve_rpath(lib_path, search_paths, referencing_lib_path=None):
|
||||
"""
|
||||
resolve @rpath is lib_path by searching in search_paths and rpaths from referencing library
|
||||
"""
|
||||
if lib_path.startswith("@rpath/"):
|
||||
lib_name = lib_path.replace("@rpath/", "")
|
||||
|
||||
# first check rpaths from the referencing library
|
||||
if referencing_lib_path:
|
||||
rpaths = get_rpaths_for_resolution(referencing_lib_path)
|
||||
for rpath in rpaths:
|
||||
full_path = os.path.join(rpath, lib_name)
|
||||
if os.path.isfile(full_path):
|
||||
return full_path
|
||||
|
||||
# then check search paths as fallback
|
||||
# search for the library in all search paths
|
||||
for search_path in search_paths:
|
||||
full_path = os.path.join(search_path, lib_name)
|
||||
if os.path.isfile(full_path):
|
||||
return full_path
|
||||
if os.path.islink(full_path):
|
||||
real_path = os.path.realpath(full_path)
|
||||
if os.path.isfile(real_path):
|
||||
return full_path
|
||||
return lib_path
|
||||
|
||||
|
||||
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
|
||||
if path_macho.endswith(os.path.basename(get_token(lines[1]))):
|
||||
lines = lines[2:]
|
||||
else:
|
||||
lines = lines[1:]
|
||||
|
||||
for line in lines:
|
||||
lib = get_token(line)
|
||||
if not is_system_lib(lib):
|
||||
libs.append(lib)
|
||||
return libs
|
||||
|
||||
|
||||
def library_paths(install_names, search_paths):
|
||||
paths = []
|
||||
for name in install_names:
|
||||
path = os.path.dirname(name)
|
||||
lib_name = os.path.basename(name)
|
||||
|
||||
if path == "" or name[0] == "@":
|
||||
# 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, referencing_lib_path=None):
|
||||
"""
|
||||
Return a list of Node objects from the provided install names.
|
||||
referencing_lib_path: path to the library that references these dependencies
|
||||
"""
|
||||
nodes = []
|
||||
for lib in install_names:
|
||||
original_lib = lib
|
||||
|
||||
# resolve @loader_path if present
|
||||
if referencing_lib_path and lib.startswith("@loader_path/"):
|
||||
lib = resolve_loader_path(lib, referencing_lib_path)
|
||||
logging.debug(
|
||||
f"Resolved {original_lib} to {lib} (referencing from {referencing_lib_path})"
|
||||
)
|
||||
|
||||
# resolve @rpath if present
|
||||
elif lib.startswith("@rpath/"):
|
||||
resolved_lib = resolve_rpath(lib, search_paths)
|
||||
if resolved_lib != lib:
|
||||
lib = resolved_lib
|
||||
logging.debug(f"resolved {original_lib} to {lib}")
|
||||
|
||||
install_path = os.path.dirname(lib)
|
||||
lib_name = os.path.basename(lib)
|
||||
|
||||
path = get_path(lib_name, search_paths)
|
||||
|
||||
if install_path != "" and lib[0] != "@":
|
||||
# we have an absolute path install name
|
||||
if not path:
|
||||
path = install_path
|
||||
|
||||
if not path:
|
||||
logging.error("unable to find LC_DYLD_LOAD entry: " + original_lib)
|
||||
if referencing_lib_path:
|
||||
logging.error(f" referenced from: {referencing_lib_path}")
|
||||
logging.error(f" resolved to: {lib}")
|
||||
logging.error(f" searching for: {lib_name}")
|
||||
logging.error(f" search paths: {search_paths}")
|
||||
raise LibraryNotFound(lib_name + " not found in given search paths:")
|
||||
|
||||
nodes.append(Node(lib_name, path))
|
||||
|
||||
return nodes
|
||||
|
||||
|
||||
def paths_at_depth(prefix, paths, depth):
|
||||
filtered = []
|
||||
for p in paths:
|
||||
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("/")
|
||||
filters = []
|
||||
# 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
|
||||
return True
|
||||
|
||||
for pf in filters:
|
||||
s_filter = pf.strip("/").split("/")
|
||||
length = len(s_filter)
|
||||
matched = 0
|
||||
for i in range(len(s_path)):
|
||||
if s_path[i] == s_filter[i]:
|
||||
matched += 1
|
||||
if matched == length or matched == len(s_path):
|
||||
return True
|
||||
|
||||
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
|
||||
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))
|
||||
]
|
||||
|
||||
s_paths.insert(0, root)
|
||||
|
||||
# Automatically add Homebrew Cellar lib directories to search paths
|
||||
homebrew_cellar = os.path.join(brew_prefix, "Cellar")
|
||||
if os.path.exists(homebrew_cellar):
|
||||
for cellar_dir in os.listdir(homebrew_cellar):
|
||||
cellar_path = os.path.join(homebrew_cellar, cellar_dir)
|
||||
if os.path.isdir(cellar_path):
|
||||
# Look for version directories
|
||||
for version_dir in os.listdir(cellar_path):
|
||||
version_path = os.path.join(cellar_path, version_dir)
|
||||
lib_path = os.path.join(version_path, "lib")
|
||||
if os.path.isdir(lib_path):
|
||||
if lib_path not in s_paths:
|
||||
s_paths.append(lib_path)
|
||||
logging.debug(f"Auto-discovered Homebrew lib path: {lib_path}")
|
||||
|
||||
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":
|
||||
visited[fpath] = False
|
||||
|
||||
stack = []
|
||||
for k in list(visited):
|
||||
if not visited[k]:
|
||||
stack.append(k)
|
||||
while stack:
|
||||
k2 = stack.pop()
|
||||
visited[k2] = True
|
||||
|
||||
node = Node(os.path.basename(k2), os.path.dirname(k2))
|
||||
if not graph.in_graph(node):
|
||||
graph.add_node(node)
|
||||
|
||||
try:
|
||||
deps = create_dep_nodes(list_install_names(k2), s_paths, k2)
|
||||
except Exception:
|
||||
logging.error("Failed to resolve dependency in " + k2)
|
||||
raise
|
||||
|
||||
for d in deps:
|
||||
if d.name not in node.children:
|
||||
node.children.append(d.name)
|
||||
|
||||
dk = os.path.join(d.path, d.name)
|
||||
if dk not in list(visited):
|
||||
visited[dk] = False
|
||||
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])
|
||||
|
||||
node.path = os.path.dirname(target)
|
||||
|
||||
# fix permissions
|
||||
check_call(["chmod", "a+w", target])
|
||||
|
||||
|
||||
def get_rpaths(library):
|
||||
"Returns a list of rpaths specified within library"
|
||||
|
||||
out = check_output(["otool", "-l", library])
|
||||
|
||||
pathRegex = r"^path (.*) \(offset \d+\)$"
|
||||
expectingRpath = False
|
||||
rpaths = []
|
||||
for line in get_token(out, "\n", False):
|
||||
line = line.strip()
|
||||
|
||||
if "cmd LC_RPATH" in line:
|
||||
expectingRpath = True
|
||||
elif "Load command" in line:
|
||||
expectingRpath = False
|
||||
elif expectingRpath:
|
||||
m = re.match(pathRegex, line)
|
||||
if m:
|
||||
rpaths.append(m.group(1))
|
||||
expectingRpath = False
|
||||
|
||||
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)
|
||||
|
||||
# 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 = []
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
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))
|
||||
|
||||
|
||||
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]")
|
||||
quit()
|
||||
|
||||
path = sys.argv[1]
|
||||
bundle_path = os.path.abspath(os.path.join(path, "Contents"))
|
||||
graph = DepsGraph()
|
||||
dir_filter = ["MacOS", "lib", "Mod"]
|
||||
|
||||
# get the initial search paths
|
||||
initial_search_paths = [bundle_path + "/lib"] + sys.argv[2:]
|
||||
|
||||
# add additional search paths if required
|
||||
additional_search_paths = [os.path.join(brew_prefix, "lib", "gcc", "current")]
|
||||
|
||||
# combine the initial + additional search paths
|
||||
search_paths = initial_search_paths + [
|
||||
p for p in additional_search_paths if p not in initial_search_paths
|
||||
]
|
||||
|
||||
# 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])
|
||||
|
||||
logging.info("Copying external dependencies to bundle...")
|
||||
graph.visit(copy_into_bundle, [bundle_path])
|
||||
|
||||
logging.info("Updating dynamic loader paths...")
|
||||
graph.visit(add_rpaths, [bundle_path])
|
||||
|
||||
logging.info("Setting bundled library IDs...")
|
||||
graph.visit(change_libid, [bundle_path])
|
||||
|
||||
logging.info("Done.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
61
src/Tools/MakeNewBuildNbr.py
Normal file
61
src/Tools/MakeNewBuildNbr.py
Normal file
@@ -0,0 +1,61 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# ***************************************************************************
|
||||
# * 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
|
||||
#
|
||||
# Increase the Build Number in Version.h
|
||||
|
||||
import time
|
||||
|
||||
# reading the last Version information
|
||||
[FCVersionMajor, FCVersionMinor, FCVersionBuild, FCVersionDisDa, dummy] = open(
|
||||
"../Version.h", "r"
|
||||
).readlines()
|
||||
|
||||
# increasing build number
|
||||
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() + '"',
|
||||
]
|
||||
)
|
||||
|
||||
# writing the ChangeLog.txt
|
||||
open("../ChangeLog.txt", "a").write(
|
||||
"\nVersion: V"
|
||||
+ FCVersionMajor[23:-1]
|
||||
+ "."
|
||||
+ FCVersionMinor[23:-1]
|
||||
+ "B"
|
||||
+ str(BuildNumber)
|
||||
+ " Date: "
|
||||
+ time.asctime()
|
||||
+ " +++++++++++++++++++++++++++++++\n"
|
||||
)
|
||||
50
src/Tools/PythonToCPP.py
Normal file
50
src/Tools/PythonToCPP.py
Normal file
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2004 Werner Mayer LGPL
|
||||
|
||||
import os, sys
|
||||
|
||||
# os.chdir("E:\\Develop\\FreeCADWin\\scripts")
|
||||
|
||||
|
||||
try:
|
||||
file = open(sys.argv[1], encoding="utf-8")
|
||||
except TypeError:
|
||||
file = open(sys.argv[1])
|
||||
|
||||
if len(sys.argv) > 4:
|
||||
sys.stderr.write("Wrong Parameter\n Usage:\n PythonToCPP Infile.py [Outfile][Variable]\n")
|
||||
|
||||
if len(sys.argv) > 2:
|
||||
try:
|
||||
out = open(sys.argv[2], "w", encoding="utf-8")
|
||||
except TypeError:
|
||||
out = open(sys.argv[2], "w")
|
||||
else:
|
||||
out = sys.stdout
|
||||
|
||||
if len(sys.argv) > 3:
|
||||
identifier = sys.argv[3]
|
||||
else:
|
||||
identifier = os.path.basename(sys.argv[1])
|
||||
identifier = identifier[:-3]
|
||||
|
||||
lines = file.readlines()
|
||||
|
||||
# We want to use this script for files in another directory, so we extract the actual file name
|
||||
out.write("const char " + identifier + "[] =")
|
||||
|
||||
for line in lines:
|
||||
# remove new line
|
||||
line2 = line.rstrip()
|
||||
# replace special chars
|
||||
line2 = line2.replace("\\", "\\\\")
|
||||
line2 = line2.replace('"', '\\"')
|
||||
line2 = line2.replace("'", "\\'")
|
||||
|
||||
# output
|
||||
# out.write(line)
|
||||
out.write('"' + line2 + '\\n"\n')
|
||||
|
||||
out.write(";\n\n\n")
|
||||
544
src/Tools/SubWCRev.py
Normal file
544
src/Tools/SubWCRev.py
Normal file
@@ -0,0 +1,544 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2006 Werner Mayer LGPL
|
||||
#
|
||||
# FreeCAD RevInfo script to get the revision information from Subversion, Bazaar, and Git.
|
||||
#
|
||||
# Under Linux the Subversion tool SubWCRev shipped with TortoiseSVN isn't
|
||||
# available which is provided by this script.
|
||||
# 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, datetime, time, getopt
|
||||
from urllib.parse import urlparse
|
||||
import xml.sax
|
||||
import xml.sax.handler
|
||||
import xml.sax.xmlreader
|
||||
|
||||
try:
|
||||
from StringIO import StringIO
|
||||
except ImportError:
|
||||
from io import StringIO
|
||||
|
||||
|
||||
# SAX handler to parse the subversion output
|
||||
class SvnHandler(xml.sax.handler.ContentHandler):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.inUrl = 0
|
||||
self.inDate = 0
|
||||
self.mapping = {}
|
||||
|
||||
def startElement(self, name, attributes):
|
||||
if name == "entry":
|
||||
self.buffer = ""
|
||||
self.mapping["Rev"] = attributes["revision"]
|
||||
elif name == "url":
|
||||
self.inUrl = 1
|
||||
elif name == "date":
|
||||
self.inDate = 1
|
||||
|
||||
def characters(self, data):
|
||||
if self.inUrl:
|
||||
self.buffer += data
|
||||
elif self.inDate:
|
||||
self.buffer += data
|
||||
|
||||
def endElement(self, name):
|
||||
if name == "url":
|
||||
self.inUrl = 0
|
||||
self.mapping["Url"] = self.buffer
|
||||
self.buffer = ""
|
||||
elif name == "date":
|
||||
self.inDate = 0
|
||||
self.mapping["Date"] = self.buffer
|
||||
self.buffer = ""
|
||||
|
||||
|
||||
class VersionControl:
|
||||
def __init__(self):
|
||||
self.rev = ""
|
||||
self.date = ""
|
||||
self.url = ""
|
||||
|
||||
def extractInfo(self, srcdir, bindir):
|
||||
return False
|
||||
|
||||
def printInfo(self):
|
||||
print("")
|
||||
|
||||
def writeVersion(self, lines):
|
||||
content = []
|
||||
for line in lines:
|
||||
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"):
|
||||
return False
|
||||
self.rev = "Unknown"
|
||||
self.date = "Unknown"
|
||||
self.url = "Unknown"
|
||||
return True
|
||||
|
||||
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"):
|
||||
return False
|
||||
try:
|
||||
f = open(srcdir + "/debian/changelog")
|
||||
except Exception:
|
||||
return False
|
||||
c = f.readline()
|
||||
f.close()
|
||||
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.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()
|
||||
if len(info) == 0:
|
||||
return False
|
||||
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)
|
||||
if r is not None:
|
||||
self.date = r.groups()[0]
|
||||
continue
|
||||
return True
|
||||
|
||||
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
|
||||
def extractInfo(self, srcdir, bindir):
|
||||
try:
|
||||
f = open(srcdir + "/debian/git-build-recipe.manifest")
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# Read the first two lines
|
||||
recipe = f.readline()
|
||||
commit = f.readline()
|
||||
f.close()
|
||||
|
||||
base_url = "https://api.github.com"
|
||||
owner = "FreeCAD"
|
||||
repo = "FreeCAD"
|
||||
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
|
||||
)
|
||||
commit_req = requests.get(request_url)
|
||||
if not commit_req.ok:
|
||||
return False
|
||||
|
||||
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]
|
||||
|
||||
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,
|
||||
)
|
||||
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,
|
||||
)
|
||||
|
||||
self.date = commit_date
|
||||
self.branch = "unknown"
|
||||
|
||||
try:
|
||||
# Try to determine the branch of the sha
|
||||
# There is no function of the rest API of GH but with the url below we get HTML code
|
||||
branch_url = "https://github.com/{}/{}/branch_commits/{}".format(owner, repo, sha)
|
||||
branch_req = requests.get(branch_url)
|
||||
if branch_req.ok:
|
||||
html = branch_req.text
|
||||
pattern = '<li class="branch"><a href='
|
||||
start = html.find(pattern) + len(pattern)
|
||||
end = html.find("\n", start)
|
||||
link = html[start:end]
|
||||
start = link.find(">") + 1
|
||||
end = link.find("<", start)
|
||||
self.branch = link[start:end]
|
||||
|
||||
link = commit_req.headers.get("link")
|
||||
beg = link.rfind("&page=") + 6
|
||||
end = link.rfind(">")
|
||||
self.rev = link[beg:end] + " (GitHub)"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
self.url = "git://github.com/{}/{}.git {}".format(owner, repo, self.branch)
|
||||
return True
|
||||
|
||||
def writeVersion(self, lines):
|
||||
content = VersionControl.writeVersion(self, lines)
|
||||
content.append("// Git relevant stuff\n")
|
||||
content.append('#define FCRepositoryHash "%s"\n' % (self.hash))
|
||||
content.append('#define FCRepositoryBranch "%s"\n' % (self.branch))
|
||||
return content
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
def geturl(self):
|
||||
urls = []
|
||||
for ref in self.branchlst:
|
||||
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(r"git@github\.com:(\S+?)/(\S+\.git)", url) or re.match(
|
||||
r"https://github\.com/(\S+)/(\S+\.git)", url
|
||||
)
|
||||
if match is not None:
|
||||
url = "git://github.com/%s/%s" % match.groups()
|
||||
match = re.match(r"ssh://\S+?@(\S+)", url)
|
||||
if match is not None:
|
||||
url = "git://%s" % match.group(1)
|
||||
parsed_url = urlparse(url)
|
||||
entryscore = (
|
||||
url == "git://github.com/FreeCAD/FreeCAD.git",
|
||||
parsed_url.netloc == "github.com",
|
||||
branch == self.branch,
|
||||
branch == "main",
|
||||
"@" 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):
|
||||
"""sets the revision number
|
||||
for main 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 main repository. The second part (separated by " +") reflects
|
||||
the number of commits that are different from the main repository"""
|
||||
referencecommit = "7d8e53aaab17961d85c5009de34f69f2af084e8b"
|
||||
referencerevision = 14555
|
||||
|
||||
result = None
|
||||
null_device = "nul" if os.name == "nt" else "/dev/null"
|
||||
countallfh = os.popen(f"git rev-list --count {referencecommit}..HEAD 2>{null_device}")
|
||||
countallstr = countallfh.read().strip()
|
||||
if countallfh.close() is not None: # reference commit not present, use the date
|
||||
date_object = datetime.datetime.strptime(self.date, "%Y/%m/%d %H:%M:%S")
|
||||
formatted_date = date_object.strftime("%Y%m%d")
|
||||
self.rev = f"{formatted_date} (Git shallow)"
|
||||
return
|
||||
else:
|
||||
countall = int(countallstr)
|
||||
|
||||
if (
|
||||
origin is not None
|
||||
and self.branch.lower() != "main"
|
||||
and "release" not in self.branch.lower()
|
||||
):
|
||||
mbfh = os.popen("git merge-base %s/main HEAD" % origin)
|
||||
mergebase = mbfh.read().strip()
|
||||
if mbfh.close() is None: # exit code == 0
|
||||
try:
|
||||
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,
|
||||
)
|
||||
except ValueError:
|
||||
pass
|
||||
self.rev = result or ("%04d (Git)" % (countall + referencerevision))
|
||||
|
||||
def namebranchbyparents(self):
|
||||
"""name multiple branches in case that the last commit was a merge
|
||||
a merge is identified by having two or more parents
|
||||
if the describe does not return a ref name (the hash is added)
|
||||
if one parent is the main 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
|
||||
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
|
||||
parentrefs.append(refs)
|
||||
names.append(refs[-1])
|
||||
hasnames += 1
|
||||
else:
|
||||
parentrefs.append(p)
|
||||
names.append(p[:7])
|
||||
if hasnames >= 2: # merging main 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()
|
||||
if self.hash == "":
|
||||
return False # not a git repo
|
||||
# date/time
|
||||
import time
|
||||
|
||||
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(r"\*", self.branch) is not None:
|
||||
break
|
||||
self.branch = self.branch[2:]
|
||||
self.getremotes() # setup self.remotes and branchlst
|
||||
|
||||
self.geturl()
|
||||
origin = None # remote for the blessed main
|
||||
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() != "main" and "release" not in self.branch.lower():
|
||||
self.namebranchbyparents()
|
||||
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
|
||||
if self.url == "Unknown":
|
||||
for i in info:
|
||||
r = re.match("origin\\W+(\\S+)", i)
|
||||
if r is not None:
|
||||
self.url = r.groups()[0]
|
||||
break
|
||||
return True
|
||||
|
||||
def printInfo(self):
|
||||
print("git")
|
||||
|
||||
def writeVersion(self, lines):
|
||||
content = VersionControl.writeVersion(self, lines)
|
||||
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
|
||||
|
||||
def printInfo(self):
|
||||
print("mercurial")
|
||||
|
||||
|
||||
class Subversion(VersionControl):
|
||||
def extractInfo(self, srcdir, bindir):
|
||||
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()
|
||||
try:
|
||||
inpsrc = xml.sax.InputSource()
|
||||
strio = StringIO.StringIO(Info)
|
||||
inpsrc.setByteStream(strio)
|
||||
parser.parse(inpsrc)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 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("-", "/")
|
||||
|
||||
# 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
|
||||
self.time = time.strftime("%Y/%m/%d %H:%M:%S")
|
||||
|
||||
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)
|
||||
if r is not None:
|
||||
self.mods = "Src modified"
|
||||
|
||||
# if version string contains a range
|
||||
r = re.match("^\\d+\\:\\d+", Ver)
|
||||
if r is not None:
|
||||
self.mixed = "Src mixed"
|
||||
self.range = Ver[: r.end()]
|
||||
return True
|
||||
|
||||
def printInfo(self):
|
||||
print("subversion")
|
||||
|
||||
|
||||
def main():
|
||||
# if(len(sys.argv) != 2):
|
||||
# sys.stderr.write("Usage: SubWCRev \"`svn info .. --xml`\"\n")
|
||||
|
||||
srcdir = "."
|
||||
bindir = "."
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[1:], "sb:", ["srcdir=", "bindir="])
|
||||
except getopt.GetoptError:
|
||||
pass
|
||||
|
||||
for o, a in opts:
|
||||
if o in ("-s", "--srcdir"):
|
||||
srcdir = a
|
||||
if o in ("-b", "--bindir"):
|
||||
bindir = a
|
||||
|
||||
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
|
||||
inp = open("%s/src/Build/Version.h.in" % (bindir))
|
||||
lines = inp.readlines()
|
||||
inp.close()
|
||||
lines = i.writeVersion(lines)
|
||||
out = open("%s/src/Build/Version.h.out" % (bindir), "w")
|
||||
out.writelines(lines)
|
||||
out.write("\n")
|
||||
out.close()
|
||||
i.printInfo()
|
||||
sys.stdout.write("%s/src/Build/Version.h.out written\n" % (bindir))
|
||||
break
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
103
src/Tools/ThumbnailProvider/CMakeLists.txt
Normal file
103
src/Tools/ThumbnailProvider/CMakeLists.txt
Normal file
@@ -0,0 +1,103 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
project(ThumbnailProvider)
|
||||
|
||||
cmake_minimum_required(VERSION 2.6.0 FATAL_ERROR)
|
||||
|
||||
add_definitions(-D_UNICODE -D_CRT_SECURE_NO_WARNINGS)
|
||||
|
||||
#=================================================
|
||||
# zlib
|
||||
#=================================================
|
||||
|
||||
find_package(ZLIB REQUIRED)
|
||||
|
||||
#=================================================
|
||||
# FCStdThumbnail
|
||||
#=================================================
|
||||
|
||||
|
||||
include_directories(
|
||||
.
|
||||
../../../
|
||||
)
|
||||
|
||||
include_directories(
|
||||
SYSTEM
|
||||
${ZLIB_INCLUDE_DIR}
|
||||
)
|
||||
|
||||
set(THUMBS_LIBS
|
||||
Shlwapi.lib
|
||||
${ZLIB_LIBRARIES}
|
||||
)
|
||||
|
||||
set(zipios_DIR ../../..)
|
||||
SET(zipios_SRCS
|
||||
${zipios_DIR}/zipios++/backbuffer.h
|
||||
#${zipios_DIR}/zipios++/basicentry.cpp
|
||||
#${zipios_DIR}/zipios++/basicentry.h
|
||||
${zipios_DIR}/zipios++/collcoll.cpp
|
||||
${zipios_DIR}/zipios++/collcoll.h
|
||||
${zipios_DIR}/zipios++/deflateoutputstreambuf.cpp
|
||||
${zipios_DIR}/zipios++/deflateoutputstreambuf.h
|
||||
#${zipios_DIR}/zipios++/dircoll.cpp
|
||||
#${zipios_DIR}/zipios++/dircoll.h
|
||||
#${zipios_DIR}/zipios++/directory.cpp
|
||||
#${zipios_DIR}/zipios++/directory.h
|
||||
${zipios_DIR}/zipios++/fcoll.cpp
|
||||
${zipios_DIR}/zipios++/fcoll.h
|
||||
${zipios_DIR}/zipios++/fcollexceptions.cpp
|
||||
${zipios_DIR}/zipios++/fcollexceptions.h
|
||||
${zipios_DIR}/zipios++/fileentry.cpp
|
||||
${zipios_DIR}/zipios++/fileentry.h
|
||||
${zipios_DIR}/zipios++/filepath.cpp
|
||||
${zipios_DIR}/zipios++/filepath.h
|
||||
${zipios_DIR}/zipios++/filterinputstreambuf.cpp
|
||||
${zipios_DIR}/zipios++/filterinputstreambuf.h
|
||||
${zipios_DIR}/zipios++/filteroutputstreambuf.cpp
|
||||
${zipios_DIR}/zipios++/filteroutputstreambuf.h
|
||||
${zipios_DIR}/zipios++/gzipoutputstream.cpp
|
||||
${zipios_DIR}/zipios++/gzipoutputstream.h
|
||||
${zipios_DIR}/zipios++/gzipoutputstreambuf.cpp
|
||||
${zipios_DIR}/zipios++/gzipoutputstreambuf.h
|
||||
${zipios_DIR}/zipios++/inflateinputstreambuf.cpp
|
||||
${zipios_DIR}/zipios++/inflateinputstreambuf.h
|
||||
${zipios_DIR}/zipios++/meta-iostreams.h
|
||||
${zipios_DIR}/zipios++/outputstringstream.h
|
||||
${zipios_DIR}/zipios++/simplesmartptr.h
|
||||
${zipios_DIR}/zipios++/virtualseeker.h
|
||||
${zipios_DIR}/zipios++/zipfile.cpp
|
||||
${zipios_DIR}/zipios++/zipfile.h
|
||||
${zipios_DIR}/zipios++/ziphead.cpp
|
||||
${zipios_DIR}/zipios++/ziphead.h
|
||||
${zipios_DIR}/zipios++/zipheadio.cpp
|
||||
${zipios_DIR}/zipios++/zipheadio.h
|
||||
${zipios_DIR}/zipios++/zipinputstream.cpp
|
||||
${zipios_DIR}/zipios++/zipinputstream.h
|
||||
${zipios_DIR}/zipios++/zipinputstreambuf.cpp
|
||||
${zipios_DIR}/zipios++/zipinputstreambuf.h
|
||||
${zipios_DIR}/zipios++/zipios_common.h
|
||||
${zipios_DIR}/zipios++/zipios-config.h
|
||||
${zipios_DIR}/zipios++/zipios_defs.h
|
||||
${zipios_DIR}/zipios++/zipoutputstreambuf.cpp
|
||||
${zipios_DIR}/zipios++/zipoutputstreambuf.h
|
||||
${zipios_DIR}/zipios++/zipoutputstream.cpp
|
||||
${zipios_DIR}/zipios++/zipoutputstream.h
|
||||
)
|
||||
SOURCE_GROUP("zipios++" FILES ${zipios_SRCS})
|
||||
|
||||
SET(THUMBS_SRCS
|
||||
${zipios_SRCS}
|
||||
ClassFactory.cpp
|
||||
ClassFactory.h
|
||||
Common.h
|
||||
FCConfig.h
|
||||
Main.cpp
|
||||
ThumbnailProvider.cpp
|
||||
ThumbnailProvider.def
|
||||
ThumbnailProvider.h
|
||||
)
|
||||
|
||||
add_library(FCStdThumbnail SHARED ${THUMBS_SRCS})
|
||||
target_link_libraries(FCStdThumbnail ${THUMBS_LIBS})
|
||||
110
src/Tools/ThumbnailProvider/ClassFactory.cpp
Normal file
110
src/Tools/ThumbnailProvider/ClassFactory.cpp
Normal file
@@ -0,0 +1,110 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) 2011 Werner Mayer <wmayer@users.sourceforge.net> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#define INITGUID
|
||||
#include "ClassFactory.h"
|
||||
#include "Common.h"
|
||||
|
||||
STDAPI CThumbnailProvider_CreateInstance(REFIID riid, void** ppvObject);
|
||||
|
||||
|
||||
CClassFactory::CClassFactory()
|
||||
{
|
||||
m_cRef = 1;
|
||||
DllAddRef();
|
||||
}
|
||||
|
||||
|
||||
CClassFactory::~CClassFactory()
|
||||
{
|
||||
DllRelease();
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP CClassFactory::QueryInterface(REFIID riid, void** ppvObject)
|
||||
{
|
||||
static const QITAB qit[] = {
|
||||
QITABENT(CClassFactory, IClassFactory),
|
||||
{0},
|
||||
};
|
||||
return QISearch(this, qit, riid, ppvObject);
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP_(ULONG) CClassFactory::AddRef()
|
||||
{
|
||||
LONG cRef = InterlockedIncrement(&m_cRef);
|
||||
return (ULONG)cRef;
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP_(ULONG) CClassFactory::Release()
|
||||
{
|
||||
LONG cRef = InterlockedDecrement(&m_cRef);
|
||||
if (0 == cRef) {
|
||||
delete this;
|
||||
}
|
||||
return (ULONG)cRef;
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP CClassFactory::CreateInstance(IUnknown* punkOuter, REFIID riid, void** ppvObject)
|
||||
{
|
||||
if (NULL != punkOuter) {
|
||||
return CLASS_E_NOAGGREGATION;
|
||||
}
|
||||
|
||||
return CThumbnailProvider_CreateInstance(riid, ppvObject);
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP CClassFactory::LockServer(BOOL fLock)
|
||||
{
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
|
||||
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void** ppv)
|
||||
{
|
||||
if (NULL == ppv) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
if (!IsEqualCLSID(CLSID_SampleThumbnailProvider, rclsid)) {
|
||||
return CLASS_E_CLASSNOTAVAILABLE;
|
||||
}
|
||||
|
||||
CClassFactory* pcf;
|
||||
HRESULT hr;
|
||||
|
||||
pcf = new CClassFactory();
|
||||
if (NULL == pcf) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
hr = pcf->QueryInterface(riid, ppv);
|
||||
pcf->Release();
|
||||
return hr;
|
||||
}
|
||||
46
src/Tools/ThumbnailProvider/ClassFactory.h
Normal file
46
src/Tools/ThumbnailProvider/ClassFactory.h
Normal file
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) 2011 Werner Mayer <wmayer@users.sourceforge.net> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
class CClassFactory: public IClassFactory
|
||||
{
|
||||
private:
|
||||
LONG m_cRef;
|
||||
|
||||
~CClassFactory();
|
||||
|
||||
public:
|
||||
CClassFactory();
|
||||
|
||||
// IUnknown methods
|
||||
STDMETHOD(QueryInterface)(REFIID, void**);
|
||||
STDMETHOD_(ULONG, AddRef)();
|
||||
STDMETHOD_(ULONG, Release)();
|
||||
|
||||
// IClassFactory methods
|
||||
STDMETHOD(CreateInstance)(IUnknown*, REFIID, void**);
|
||||
STDMETHOD(LockServer)(BOOL);
|
||||
};
|
||||
54
src/Tools/ThumbnailProvider/Common.h
Normal file
54
src/Tools/ThumbnailProvider/Common.h
Normal file
@@ -0,0 +1,54 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) 2011 Werner Mayer <wmayer@users.sourceforge.net> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <shlobj.h>
|
||||
#include <shlwapi.h>
|
||||
#include <strsafe.h>
|
||||
#include <tchar.h>
|
||||
#include <thumbcache.h>
|
||||
#include <windows.h>
|
||||
|
||||
STDAPI_(ULONG) DllAddRef();
|
||||
STDAPI_(ULONG) DllRelease();
|
||||
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
|
||||
);
|
||||
171
src/Tools/ThumbnailProvider/FCConfig.h
Normal file
171
src/Tools/ThumbnailProvider/FCConfig.h
Normal file
@@ -0,0 +1,171 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) 2004 Jürgen Riegel <juergen.riegel@web.de> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
/** \file FCConfig.h
|
||||
* \brief Include all needed defines and macros
|
||||
* Here all defines and macro switching is done for FreeCAD.
|
||||
* Every used library has its own section to define the configuration.
|
||||
* This file keeps the makefiles and project files cleaner.
|
||||
*/
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
//**************************************************************************
|
||||
// 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
|
||||
#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
|
||||
#elif defined(__MWERKS__) && defined(__INTEL__)
|
||||
# ifndef FC_OS_WIN32
|
||||
# define FC_OS_WIN32
|
||||
# endif
|
||||
#elif defined(__APPLE__)
|
||||
# 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
|
||||
#elif defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
|
||||
# ifndef FC_OS_BSD
|
||||
# define FC_OS_BSD
|
||||
# endif
|
||||
#elif defined(__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
|
||||
# endif
|
||||
#else
|
||||
# error "FreeCAD is not ported to this OS yet. For help see www.freecad.org"
|
||||
#endif
|
||||
|
||||
#ifdef FC_OS_WIN32
|
||||
# define PATHSEP '\\'
|
||||
#else
|
||||
# define PATHSEP '/'
|
||||
#endif
|
||||
|
||||
//**************************************************************************
|
||||
// Standard types for Windows
|
||||
|
||||
#if defined(__MINGW32__)
|
||||
// nothing specific here
|
||||
#elif defined(FC_OS_WIN64) || defined(FC_OS_WIN32)
|
||||
|
||||
# ifndef HAVE_INT8_T
|
||||
# define HAVE_INT8_T
|
||||
typedef signed char int8_t;
|
||||
# endif
|
||||
|
||||
# ifndef HAVE_UINT8_T
|
||||
# define HAVE_UINT8_T
|
||||
typedef unsigned char uint8_t;
|
||||
# endif
|
||||
|
||||
# ifndef HAVE_INT16_T
|
||||
# define HAVE_INT16_T
|
||||
typedef short int16_t;
|
||||
# endif
|
||||
|
||||
# ifndef HAVE_UINT16_T
|
||||
# define HAVE_UINT16_T
|
||||
typedef unsigned short uint16_t;
|
||||
# endif
|
||||
|
||||
# ifndef HAVE_INT32_T
|
||||
# define HAVE_INT32_T
|
||||
typedef int int32_t;
|
||||
# endif
|
||||
|
||||
# ifndef HAVE_UINT32_T
|
||||
# define HAVE_UINT32_T
|
||||
typedef unsigned int uint32_t;
|
||||
# endif
|
||||
|
||||
# ifndef HAVE_INT64_T
|
||||
# define HAVE_INT64_T
|
||||
typedef __int64 int64_t;
|
||||
# endif
|
||||
|
||||
# ifndef HAVE_UINT64_T
|
||||
# define HAVE_UINT64_T
|
||||
typedef unsigned __int64 uint64_t;
|
||||
# endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
//**************************************************************************
|
||||
// Windows import export DLL defines
|
||||
#ifndef BaseExport
|
||||
# define BaseExport
|
||||
#endif
|
||||
#ifndef GuiExport
|
||||
# define GuiExport
|
||||
#endif
|
||||
#ifndef AppExport
|
||||
# define AppExport
|
||||
#endif
|
||||
#ifndef 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()
|
||||
# if defined(WIN64) || defined(_WIN64) || defined(__WIN64__)
|
||||
# pragma warning(disable : 4244)
|
||||
# pragma warning(disable : 4267)
|
||||
# endif
|
||||
#endif
|
||||
219
src/Tools/ThumbnailProvider/Main.cpp
Normal file
219
src/Tools/ThumbnailProvider/Main.cpp
Normal file
@@ -0,0 +1,219 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) 2011 Werner Mayer <wmayer@users.sourceforge.net> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#define INITGUID
|
||||
#include "Common.h"
|
||||
|
||||
HINSTANCE g_hinstDll = NULL;
|
||||
LONG g_cRef = 0;
|
||||
|
||||
|
||||
typedef struct _REGKEY_DELETEKEY
|
||||
{
|
||||
HKEY hKey;
|
||||
LPCWSTR lpszSubKey;
|
||||
} REGKEY_DELETEKEY;
|
||||
|
||||
|
||||
typedef struct _REGKEY_SUBKEY_AND_VALUE
|
||||
{
|
||||
HKEY hKey;
|
||||
LPCWSTR lpszSubKey;
|
||||
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)
|
||||
{
|
||||
switch (dwReason) {
|
||||
case DLL_PROCESS_ATTACH:
|
||||
g_hinstDll = hinstDll;
|
||||
break;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
STDAPI_(HINSTANCE) DllInstance()
|
||||
{
|
||||
return g_hinstDll;
|
||||
}
|
||||
|
||||
STDAPI DllCanUnloadNow()
|
||||
{
|
||||
return g_cRef ? S_FALSE : S_OK;
|
||||
}
|
||||
|
||||
STDAPI_(ULONG) DllAddRef()
|
||||
{
|
||||
LONG cRef = InterlockedIncrement(&g_cRef);
|
||||
return cRef;
|
||||
}
|
||||
|
||||
STDAPI_(ULONG) DllRelease()
|
||||
{
|
||||
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.
|
||||
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
|
||||
|
||||
WCHAR szModule[MAX_PATH];
|
||||
|
||||
ZeroMemory(szModule, sizeof(szModule));
|
||||
GetModuleFileName(g_hinstDll, szModule, ARRAYSIZE(szModule));
|
||||
|
||||
// uncomment the following
|
||||
REGKEY_SUBKEY_AND_VALUE keys[] = {
|
||||
{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},
|
||||
#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}
|
||||
};
|
||||
|
||||
return CreateRegistryKeys(keys, ARRAYSIZE(keys));
|
||||
}
|
||||
|
||||
STDAPI DllUnregisterServer()
|
||||
{
|
||||
REGKEY_DELETEKEY keys[] = {{HKEY_CLASSES_ROOT, L"CLSID\\" szCLSID_SampleThumbnailProvider}};
|
||||
return DeleteRegistryKeys(keys, ARRAYSIZE(keys));
|
||||
}
|
||||
|
||||
|
||||
STDAPI CreateRegistryKey(REGKEY_SUBKEY_AND_VALUE* pKey)
|
||||
{
|
||||
size_t cbData;
|
||||
LPVOID pvData = NULL;
|
||||
HRESULT hr = S_OK;
|
||||
|
||||
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;
|
||||
|
||||
default:
|
||||
hr = E_INVALIDARG;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
return hr;
|
||||
}
|
||||
|
||||
|
||||
STDAPI CreateRegistryKeys(REGKEY_SUBKEY_AND_VALUE* aKeys, ULONG cKeys)
|
||||
{
|
||||
HRESULT hr = S_OK;
|
||||
|
||||
for (ULONG iKey = 0; iKey < cKeys; iKey++) {
|
||||
HRESULT hrTemp = CreateRegistryKey(&aKeys[iKey]);
|
||||
if (FAILED(hrTemp)) {
|
||||
hr = hrTemp;
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
|
||||
STDAPI DeleteRegistryKeys(REGKEY_DELETEKEY* aKeys, ULONG cKeys)
|
||||
{
|
||||
HRESULT hr = S_OK;
|
||||
LSTATUS status;
|
||||
|
||||
for (ULONG iKey = 0; iKey < cKeys; iKey++) {
|
||||
status = RegDeleteTree(aKeys[iKey].hKey, aKeys[iKey].lpszSubKey);
|
||||
if (NOERROR != status) {
|
||||
hr = HRESULT_FROM_WIN32(status);
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
334
src/Tools/ThumbnailProvider/ThumbnailProvider.cpp
Normal file
334
src/Tools/ThumbnailProvider/ThumbnailProvider.cpp
Normal file
@@ -0,0 +1,334 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) 2011 Werner Mayer <wmayer@users.sourceforge.net> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#pragma warning(disable : 4995)
|
||||
|
||||
#include "ThumbnailProvider.h"
|
||||
#include "Common.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <wincodec.h>
|
||||
#include <wincodecsdk.h>
|
||||
#include <zipios++/zipfile.h>
|
||||
#include <zipios++/zipinputstream.h>
|
||||
#pragma comment(lib, "WindowsCodecs.lib")
|
||||
|
||||
// The functions
|
||||
// * CreateStreamOnResource
|
||||
// * LoadBitmapFromStream
|
||||
// * CreateHBITMAP
|
||||
// are taken from https://faithlife.codes/blog/2008/09/displaying_a_splash_screen_with_c_part_i/
|
||||
// The code is released under an MIT-style license
|
||||
|
||||
// Creates a stream object initialized with the data from an executable resource.
|
||||
IStream* CreateStreamOnResource(void* buffer, size_t length)
|
||||
{
|
||||
// initialize return value
|
||||
IStream* ipStream = NULL;
|
||||
|
||||
// allocate memory to hold the resource data
|
||||
HGLOBAL hgblResourceData = GlobalAlloc(GMEM_MOVEABLE, length);
|
||||
if (hgblResourceData == NULL) {
|
||||
goto Return;
|
||||
}
|
||||
|
||||
// get a pointer to the allocated memory
|
||||
LPVOID pvResourceData = GlobalLock(hgblResourceData);
|
||||
if (pvResourceData == NULL) {
|
||||
goto FreeData;
|
||||
}
|
||||
|
||||
// copy the data from the resource to the new memory block
|
||||
CopyMemory(pvResourceData, buffer, length);
|
||||
GlobalUnlock(hgblResourceData);
|
||||
|
||||
// create a stream on the HGLOBAL containing the data
|
||||
|
||||
if (SUCCEEDED(CreateStreamOnHGlobal(hgblResourceData, TRUE, &ipStream))) {
|
||||
goto Return;
|
||||
}
|
||||
|
||||
FreeData:
|
||||
// couldn't create stream; free the memory
|
||||
|
||||
GlobalFree(hgblResourceData);
|
||||
|
||||
Return:
|
||||
// no need to unlock or free the resource
|
||||
return ipStream;
|
||||
}
|
||||
|
||||
IWICBitmapSource* LoadBitmapFromStream(IStream* ipImageStream)
|
||||
{
|
||||
// initialize return value
|
||||
IWICBitmapSource* ipBitmap = NULL;
|
||||
|
||||
// load WIC's PNG decoder
|
||||
IWICBitmapDecoder* ipDecoder = NULL;
|
||||
if (FAILED(CoCreateInstance(
|
||||
CLSID_WICPngDecoder,
|
||||
NULL,
|
||||
CLSCTX_INPROC_SERVER,
|
||||
__uuidof(ipDecoder),
|
||||
reinterpret_cast<void**>(&ipDecoder)
|
||||
))) {
|
||||
goto Return;
|
||||
}
|
||||
|
||||
// load the PNG
|
||||
if (FAILED(ipDecoder->Initialize(ipImageStream, WICDecodeMetadataCacheOnLoad))) {
|
||||
goto ReleaseDecoder;
|
||||
}
|
||||
|
||||
// check for the presence of the first frame in the bitmap
|
||||
UINT nFrameCount = 0;
|
||||
if (FAILED(ipDecoder->GetFrameCount(&nFrameCount)) || nFrameCount != 1) {
|
||||
goto ReleaseDecoder;
|
||||
}
|
||||
|
||||
// load the first frame (i.e., the image)
|
||||
IWICBitmapFrameDecode* ipFrame = NULL;
|
||||
if (FAILED(ipDecoder->GetFrame(0, &ipFrame))) {
|
||||
goto ReleaseDecoder;
|
||||
}
|
||||
|
||||
// convert the image to 32bpp BGRA format with pre-multiplied alpha
|
||||
// (it may not be stored in that format natively in the PNG resource,
|
||||
// but we need this format to create the DIB to use on-screen)
|
||||
WICConvertBitmapSource(GUID_WICPixelFormat32bppPBGRA, ipFrame, &ipBitmap);
|
||||
ipFrame->Release();
|
||||
|
||||
ReleaseDecoder:
|
||||
ipDecoder->Release();
|
||||
Return:
|
||||
return ipBitmap;
|
||||
}
|
||||
|
||||
HBITMAP CreateHBITMAP(IWICBitmapSource* ipBitmap)
|
||||
{
|
||||
// initialize return value
|
||||
HBITMAP hbmp = NULL;
|
||||
|
||||
// get image attributes and check for valid image
|
||||
UINT width = 0;
|
||||
UINT height = 0;
|
||||
if (FAILED(ipBitmap->GetSize(&width, &height)) || width == 0 || height == 0) {
|
||||
goto Return;
|
||||
}
|
||||
|
||||
// prepare structure giving bitmap information (negative height indicates a top-down DIB)
|
||||
BITMAPINFO bminfo;
|
||||
ZeroMemory(&bminfo, sizeof(bminfo));
|
||||
bminfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
|
||||
bminfo.bmiHeader.biWidth = width;
|
||||
bminfo.bmiHeader.biHeight = -((LONG)height);
|
||||
bminfo.bmiHeader.biPlanes = 1;
|
||||
bminfo.bmiHeader.biBitCount = 32;
|
||||
bminfo.bmiHeader.biCompression = BI_RGB;
|
||||
|
||||
// create a DIB section that can hold the image
|
||||
void* pvImageBits = NULL;
|
||||
HDC hdcScreen = GetDC(NULL);
|
||||
hbmp = CreateDIBSection(hdcScreen, &bminfo, DIB_RGB_COLORS, &pvImageBits, NULL, 0);
|
||||
ReleaseDC(NULL, hdcScreen);
|
||||
if (hbmp == NULL) {
|
||||
goto Return;
|
||||
}
|
||||
|
||||
// extract the image into the HBITMAP
|
||||
|
||||
const UINT cbStride = width * 4;
|
||||
const UINT cbImage = cbStride * height;
|
||||
if (FAILED(ipBitmap->CopyPixels(NULL, cbStride, cbImage, static_cast<BYTE*>(pvImageBits)))) {
|
||||
// couldn't extract image; delete HBITMAP
|
||||
|
||||
DeleteObject(hbmp);
|
||||
hbmp = NULL;
|
||||
}
|
||||
|
||||
Return:
|
||||
return hbmp;
|
||||
}
|
||||
|
||||
CThumbnailProvider::CThumbnailProvider()
|
||||
{
|
||||
DllAddRef();
|
||||
m_cRef = 1;
|
||||
m_pSite = NULL;
|
||||
}
|
||||
|
||||
|
||||
CThumbnailProvider::~CThumbnailProvider()
|
||||
{
|
||||
if (m_pSite) {
|
||||
m_pSite->Release();
|
||||
m_pSite = NULL;
|
||||
}
|
||||
DllRelease();
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP CThumbnailProvider::QueryInterface(REFIID riid, void** ppvObject)
|
||||
{
|
||||
static const QITAB qit[] = {
|
||||
// QITABENT(CThumbnailProvider, IInitializeWithStream),
|
||||
QITABENT(CThumbnailProvider, IInitializeWithFile),
|
||||
QITABENT(CThumbnailProvider, IThumbnailProvider),
|
||||
QITABENT(CThumbnailProvider, IObjectWithSite),
|
||||
{0},
|
||||
};
|
||||
return QISearch(this, qit, riid, ppvObject);
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP_(ULONG) CThumbnailProvider::AddRef()
|
||||
{
|
||||
LONG cRef = InterlockedIncrement(&m_cRef);
|
||||
return (ULONG)cRef;
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP_(ULONG) CThumbnailProvider::Release()
|
||||
{
|
||||
LONG cRef = InterlockedDecrement(&m_cRef);
|
||||
if (0 == cRef) {
|
||||
delete this;
|
||||
}
|
||||
return (ULONG)cRef;
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP CThumbnailProvider::Initialize(IStream* pstm, DWORD grfMode)
|
||||
{
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
STDMETHODIMP CThumbnailProvider::Initialize(LPCWSTR pszFilePath, DWORD grfMode)
|
||||
{
|
||||
wcscpy_s(m_szFile, pszFilePath);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
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++) {
|
||||
unsigned char c;
|
||||
if (!zip.get((char&)c)) {
|
||||
return false;
|
||||
}
|
||||
if (c != pk[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
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
|
||||
if (!CheckZip()) {
|
||||
return NOERROR;
|
||||
}
|
||||
|
||||
std::ifstream file(m_szFile, std::ios::in | std::ios::binary);
|
||||
zipios::ZipInputStream zipstream(file);
|
||||
zipios::ConstEntryPointer entry;
|
||||
entry = zipstream.getNextEntry();
|
||||
while (entry->isValid() && entry->getName() != "thumbnails/Thumbnail.png") {
|
||||
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::vector<unsigned char> content;
|
||||
unsigned char c;
|
||||
while (str->get((char&)c)) {
|
||||
content.push_back(c);
|
||||
}
|
||||
|
||||
// pass the memory buffer to an IStream to create the bitmap handle
|
||||
IStream* stream = CreateStreamOnResource(&(content[0]), content.size());
|
||||
if (stream) {
|
||||
IWICBitmapSource* bmpSrc = LoadBitmapFromStream(stream);
|
||||
stream->Release();
|
||||
if (bmpSrc) {
|
||||
*phbmp = CreateHBITMAP(bmpSrc);
|
||||
*pdwAlpha = WTSAT_UNKNOWN;
|
||||
bmpSrc->Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (...) {
|
||||
// This may happen if the file is corrupted, not a valid zip file
|
||||
// or whatever could go wrong
|
||||
}
|
||||
|
||||
return NOERROR;
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP CThumbnailProvider::GetSite(REFIID riid, void** ppvSite)
|
||||
{
|
||||
if (m_pSite) {
|
||||
return m_pSite->QueryInterface(riid, ppvSite);
|
||||
}
|
||||
return E_NOINTERFACE;
|
||||
}
|
||||
|
||||
|
||||
STDMETHODIMP CThumbnailProvider::SetSite(IUnknown* pUnkSite)
|
||||
{
|
||||
if (m_pSite) {
|
||||
m_pSite->Release();
|
||||
m_pSite = NULL;
|
||||
}
|
||||
|
||||
m_pSite = pUnkSite;
|
||||
if (m_pSite) {
|
||||
m_pSite->AddRef();
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
|
||||
STDAPI CThumbnailProvider_CreateInstance(REFIID riid, void** ppvObject)
|
||||
{
|
||||
*ppvObject = NULL;
|
||||
|
||||
CThumbnailProvider* ptp = new CThumbnailProvider();
|
||||
if (!ptp) {
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
HRESULT hr = ptp->QueryInterface(riid, ppvObject);
|
||||
ptp->Release();
|
||||
return hr;
|
||||
}
|
||||
7
src/Tools/ThumbnailProvider/ThumbnailProvider.def
Normal file
7
src/Tools/ThumbnailProvider/ThumbnailProvider.def
Normal file
@@ -0,0 +1,7 @@
|
||||
LIBRARY "FCStdThumbnail"
|
||||
|
||||
EXPORTS
|
||||
DllRegisterServer PRIVATE
|
||||
DllUnregisterServer PRIVATE
|
||||
DllGetClassObject PRIVATE
|
||||
DllCanUnloadNow PRIVATE
|
||||
58
src/Tools/ThumbnailProvider/ThumbnailProvider.h
Normal file
58
src/Tools/ThumbnailProvider/ThumbnailProvider.h
Normal file
@@ -0,0 +1,58 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) 2011 Werner Mayer <wmayer@users.sourceforge.net> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
// class CThumbnailProvider : public IThumbnailProvider, IObjectWithSite, IInitializeWithStream
|
||||
class CThumbnailProvider: public IThumbnailProvider, IObjectWithSite, IInitializeWithFile
|
||||
{
|
||||
private:
|
||||
LONG m_cRef;
|
||||
IUnknown* m_pSite;
|
||||
TCHAR m_szFile[1000];
|
||||
|
||||
~CThumbnailProvider();
|
||||
bool CheckZip() const;
|
||||
|
||||
public:
|
||||
CThumbnailProvider();
|
||||
|
||||
// IUnknown methods
|
||||
STDMETHOD(QueryInterface)(REFIID, void**);
|
||||
STDMETHOD_(ULONG, AddRef)();
|
||||
STDMETHOD_(ULONG, Release)();
|
||||
|
||||
// IInitializeWithSteam methods
|
||||
STDMETHOD(Initialize)(IStream*, DWORD);
|
||||
// IInitializeWithFile methods
|
||||
STDMETHOD(Initialize)(LPCWSTR, DWORD);
|
||||
|
||||
// IThumbnailProvider methods
|
||||
STDMETHOD(GetThumbnail)(UINT, HBITMAP*, WTS_ALPHATYPE*);
|
||||
|
||||
// IObjectWithSite methods
|
||||
STDMETHOD(GetSite)(REFIID, void**);
|
||||
STDMETHOD(SetSite)(IUnknown*);
|
||||
};
|
||||
31
src/Tools/ThumbnailProvider/ThumbnailProvider.sln
Normal file
31
src/Tools/ThumbnailProvider/ThumbnailProvider.sln
Normal file
@@ -0,0 +1,31 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.31410.357
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FCStdThumbnail", "ThumbnailProvider.vcxproj", "{B4F22D8C-736E-46BF-85FB-259EF73EA0FC}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{B4F22D8C-736E-46BF-85FB-259EF73EA0FC}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{B4F22D8C-736E-46BF-85FB-259EF73EA0FC}.Debug|x64.Build.0 = Debug|x64
|
||||
{B4F22D8C-736E-46BF-85FB-259EF73EA0FC}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
{B4F22D8C-736E-46BF-85FB-259EF73EA0FC}.Debug|x86.Build.0 = Debug|Win32
|
||||
{B4F22D8C-736E-46BF-85FB-259EF73EA0FC}.Release|x64.ActiveCfg = Release|x64
|
||||
{B4F22D8C-736E-46BF-85FB-259EF73EA0FC}.Release|x64.Build.0 = Release|x64
|
||||
{B4F22D8C-736E-46BF-85FB-259EF73EA0FC}.Release|x86.ActiveCfg = Release|Win32
|
||||
{B4F22D8C-736E-46BF-85FB-259EF73EA0FC}.Release|x86.Build.0 = Release|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {7336F399-F2B2-4F65-A701-52024EB9A7A0}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
245
src/Tools/ThumbnailProvider/ThumbnailProvider.vcxproj
Normal file
245
src/Tools/ThumbnailProvider/ThumbnailProvider.vcxproj
Normal file
@@ -0,0 +1,245 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectName>FCStdThumbnail</ProjectName>
|
||||
<ProjectGuid>{B4F22D8C-736E-46BF-85FB-259EF73EA0FC}</ProjectGuid>
|
||||
<RootNamespace>ThumbnailProvider</RootNamespace>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<PlatformToolset>v142</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<PlatformToolset>v142</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<PlatformToolset>v142</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<PlatformToolset>v142</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>16.0.31401.40</_ProjectFileVersion>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(Platform)\$(Configuration)\</IntDir>
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(Platform)\$(Configuration)\</IntDir>
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(Platform)\$(Configuration)\</IntDir>
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<OutDir>$(SolutionDir)$(Platform)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(Platform)\$(Configuration)\</IntDir>
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\..\..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;THUMBNAILPROVIDER_EXPORTS;FreeCADBase_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<PrecompiledHeader />
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>shlwapi.lib;comctl32.lib;propsys.lib;zlibstatic.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<ModuleDefinitionFile>ThumbnailProvider.def</ModuleDefinitionFile>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<TargetMachine>MachineX86</TargetMachine>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<Midl>
|
||||
<TargetEnvironment>X64</TargetEnvironment>
|
||||
</Midl>
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\..\..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN64;_DEBUG;_WINDOWS;_USRDLL;THUMBNAILPROVIDER_EXPORTS;FreeCADBase_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
|
||||
<PrecompiledHeader />
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>shlwapi.lib;comctl32.lib;propsys.lib;zlibstatic.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<ModuleDefinitionFile>ThumbnailProvider.def</ModuleDefinitionFile>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<TargetMachine>MachineX64</TargetMachine>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<AdditionalIncludeDirectories>.;..\..\..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;THUMBNAILPROVIDER_EXPORTS;FreeCADBase_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<PrecompiledHeader />
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>shlwapi.lib;comctl32.lib;propsys.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<ModuleDefinitionFile>ThumbnailProvider.def</ModuleDefinitionFile>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<TargetMachine>MachineX86</TargetMachine>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<Midl>
|
||||
<TargetEnvironment>X64</TargetEnvironment>
|
||||
</Midl>
|
||||
<ClCompile>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<AdditionalIncludeDirectories>.;..\..\..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>WIN64;NDEBUG;_WINDOWS;THUMBNAILPROVIDER_EXPORTS;FreeCADBase_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<PrecompiledHeader />
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>shlwapi.lib;comctl32.lib;propsys.lib;zlibstatic.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<ModuleDefinitionFile>ThumbnailProvider.def</ModuleDefinitionFile>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Windows</SubSystem>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<TargetMachine>MachineX64</TargetMachine>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\..\..\zipios++\basicentry.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\collcoll.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\deflateoutputstreambuf.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\dircoll.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\directory.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\fcoll.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\fcollexceptions.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\fileentry.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\filepath.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\filterinputstreambuf.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\filteroutputstreambuf.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\gzipoutputstream.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\gzipoutputstreambuf.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\inflateinputstreambuf.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\zipfile.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\ziphead.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\zipheadio.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\zipinputstream.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\zipinputstreambuf.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\zipoutputstream.cpp" />
|
||||
<ClCompile Include="..\..\..\zipios++\zipoutputstreambuf.cpp" />
|
||||
<ClCompile Include="ClassFactory.cpp" />
|
||||
<ClCompile Include="Main.cpp" />
|
||||
<ClCompile Include="ThumbnailProvider.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="ThumbnailProvider.def" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\..\..\zipios++\backbuffer.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\basicentry.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\collcoll.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\deflateoutputstreambuf.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\dircoll.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\directory.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\fcoll.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\fcollexceptions.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\fileentry.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\filepath.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\filterinputstreambuf.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\filteroutputstreambuf.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\gzipoutputstream.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\gzipoutputstreambuf.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\inflateinputstreambuf.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\meta-iostreams.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\outputstringstream.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\simplesmartptr.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\virtualseeker.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\zipfile.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\ziphead.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\zipheadio.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\zipinputstream.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\zipinputstreambuf.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\zipios-config.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\zipios_common.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\zipios_defs.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\zipoutputstream.h" />
|
||||
<ClInclude Include="..\..\..\zipios++\zipoutputstreambuf.h" />
|
||||
<ClInclude Include="ClassFactory.h" />
|
||||
<ClInclude Include="Common.h" />
|
||||
<ClInclude Include="ThumbnailProvider.h" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
41
src/Tools/_TEMPLATEPY_/CMakeLists.txt
Normal file
41
src/Tools/_TEMPLATEPY_/CMakeLists.txt
Normal file
@@ -0,0 +1,41 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
IF (BUILD_GUI)
|
||||
PYSIDE_WRAP_RC(_TEMPLATEPY__QRC_SRCS Resources/_TEMPLATEPY_.qrc)
|
||||
ENDIF (BUILD_GUI)
|
||||
|
||||
SET(_TEMPLATEPY__SRCS
|
||||
Init.py
|
||||
InitGui.py
|
||||
_TEMPLATEPY_.py
|
||||
_TEMPLATEPY_Gui.py
|
||||
)
|
||||
SOURCE_GROUP("" FILES ${_TEMPLATEPY__SRCS})
|
||||
|
||||
SET(_TEMPLATEPY_GuiIcon_SVG
|
||||
Resources/icons/_TEMPLATEPY_Workbench.svg
|
||||
)
|
||||
|
||||
ADD_CUSTOM_TARGET(_TEMPLATEPY_ ALL
|
||||
SOURCES ${_TEMPLATEPY__SRCS} ${_TEMPLATEPY__QRC_SRCS} ${_TEMPLATEPY_GuiIcon_SVG}
|
||||
)
|
||||
|
||||
fc_copy_sources(_TEMPLATEPY_ "${CMAKE_BINARY_DIR}/Mod/_TEMPLATEPY_" ${_TEMPLATEPY__SRCS})
|
||||
fc_copy_sources(_TEMPLATEPY_ "${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_DATADIR}/Mod/_TEMPLATEPY_" ${_TEMPLATEPY_GuiIcon_SVG})
|
||||
|
||||
IF (BUILD_GUI)
|
||||
fc_target_copy_resource(_TEMPLATEPY_
|
||||
${CMAKE_CURRENT_BINARY_DIR}
|
||||
${CMAKE_BINARY_DIR}/Mod/_TEMPLATEPY_
|
||||
_TEMPLATEPY__rc.py)
|
||||
ENDIF (BUILD_GUI)
|
||||
|
||||
INSTALL(
|
||||
FILES
|
||||
${_TEMPLATEPY__SRCS}
|
||||
${_TEMPLATEPY__QRC_SRCS}
|
||||
DESTINATION
|
||||
Mod/_TEMPLATEPY_
|
||||
)
|
||||
|
||||
INSTALL(FILES ${_TEMPLATEPY_GuiIcon_SVG} DESTINATION "Mod/_TEMPLATEPY_/Resources/icons")
|
||||
5
src/Tools/_TEMPLATEPY_/Init.py
Normal file
5
src/Tools/_TEMPLATEPY_/Init.py
Normal file
@@ -0,0 +1,5 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# FreeCAD init script of the _TEMPLATEPY_ module
|
||||
# (c) 2001 Juergen Riegel
|
||||
# License LGPL
|
||||
26
src/Tools/_TEMPLATEPY_/InitGui.py
Normal file
26
src/Tools/_TEMPLATEPY_/InitGui.py
Normal file
@@ -0,0 +1,26 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# _TEMPLATEPY_ gui init module
|
||||
# (c) 2001 Juergen Riegel
|
||||
# License LGPL
|
||||
|
||||
|
||||
class _TEMPLATEPY_Workbench(Workbench):
|
||||
"_TEMPLATEPY_ workbench object"
|
||||
|
||||
Icon = FreeCAD.getResourceDir() + "Mod/_TEMPLATEPY_/Resources/icons/_TEMPLATEPY_Workbench.svg"
|
||||
MenuText = "_TEMPLATEPY_"
|
||||
ToolTip = "_TEMPLATEPY_ workbench"
|
||||
|
||||
def Initialize(self):
|
||||
# load the module
|
||||
import _TEMPLATEPY_Gui
|
||||
|
||||
self.appendToolbar("_TEMPLATEPY_", ["_TEMPLATEPY__HelloWorld"])
|
||||
self.appendMenu("_TEMPLATEPY_", ["_TEMPLATEPY__HelloWorld"])
|
||||
|
||||
def GetClassName(self):
|
||||
return "Gui::PythonWorkbench"
|
||||
|
||||
|
||||
Gui.addWorkbench(_TEMPLATEPY_Workbench())
|
||||
5
src/Tools/_TEMPLATEPY_/Resources/_TEMPLATEPY_.qrc
Normal file
5
src/Tools/_TEMPLATEPY_/Resources/_TEMPLATEPY_.qrc
Normal file
@@ -0,0 +1,5 @@
|
||||
<!DOCTYPE RCC><RCC version="1.0">
|
||||
<qresource>
|
||||
<file>icons/_TEMPLATEPY_Workbench.svg</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="64"
|
||||
height="64"
|
||||
id="svg3140"
|
||||
version="1.1"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<defs
|
||||
id="defs3142" />
|
||||
<metadata
|
||||
id="metadata3145">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
id="layer1">
|
||||
<g
|
||||
id="layer1-4"
|
||||
transform="translate(-6e-6,-0.36363683)">
|
||||
<g
|
||||
transform="matrix(0.8506406,0,0,0.8506406,187.82699,-0.1960013)"
|
||||
id="g3813-3">
|
||||
<g
|
||||
id="g2"
|
||||
transform="matrix(2.7626237,0,0,2.7626237,-216.92708,5.3602404)">
|
||||
<path
|
||||
d="m 22,3.9997423 -3.999742,4.0002581 h -8 V 10.999806 H 14 v 4.000259 h -3.999742 v 4.999678 L 5.9999997,24 h 4.0503843 c 0.30326,-1e-6 0.571883,-0.195269 0.66559,-0.48369 l 0.723985,-2.22828 c 0.06925,-0.213087 0.236489,-0.379833 0.449583,-0.449065 l 0.556553,-0.180868 c 0.213108,-0.06926 0.446577,-0.03248 0.627866,0.09922 l 1.894968,1.377173 c 0.245331,0.178232 0.57787,0.178229 0.823203,0 l 1.698598,-1.234547 c 0.245363,-0.178242 0.347963,-0.493948 0.254247,-0.782378 l -0.723984,-2.22828 c -0.06926,-0.213109 -0.03197,-0.446575 0.09974,-0.627866 l 0.344164,-0.473355 c 0.131697,-0.181276 0.34179,-0.288856 0.565855,-0.28887 l 2.343001,5.1e-4 c 0.303278,10e-6 0.571885,-0.19577 0.66559,-0.484207 l 0.649054,-1.996771 c 0.0937,-0.288413 -0.0089,-0.60465 -0.254247,-0.782895 L 19.538664,11.858666 C 19.357381,11.726957 19.250306,11.516889 19.250311,11.292812 V 10.70732 c 1.9e-5,-0.224072 0.107062,-0.434681 0.288353,-0.566372 L 21.711646,8.5622376 C 21.892924,8.4305313 21.999999,8.219938 22,7.9958659 Z"
|
||||
style="fill:#418fde;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.64567;stroke-linecap:square"
|
||||
id="path8" />
|
||||
<path
|
||||
id="path7"
|
||||
style="display:inline;fill:#ff585d;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.64567;stroke-linecap:square"
|
||||
d="m 18,0 -4,4 h 4 V 8 L 22,4 V 0 Z M 6,16 2,20 v 4 h 4 l 4,-4 H 6 Z" />
|
||||
<path
|
||||
d="M 6,0 2,4 V 20 L 6,16 V 4 h 8 l 4,-4 z"
|
||||
style="fill:#cb333b;fill-rule:evenodd;stroke-width:2.64567;stroke-linecap:square"
|
||||
id="path3" />
|
||||
<path
|
||||
d="M 5.9999997,19.999743 H 10.000258 V 15.000065 H 14 V 10.999806 H 10.000258 V 8.0000004 h 8 V 3.9997423 H 5.9999997 Z"
|
||||
style="fill:#fefefe;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.64567;stroke-linecap:square"
|
||||
id="path9" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.0 KiB |
2
src/Tools/_TEMPLATEPY_/_TEMPLATEPY_.dox
Normal file
2
src/Tools/_TEMPLATEPY_/_TEMPLATEPY_.dox
Normal file
@@ -0,0 +1,2 @@
|
||||
/** \defgroup TEMPLATE _TEMPLATEPY_
|
||||
* \ingroup WORKBENCHES */
|
||||
1
src/Tools/_TEMPLATEPY_/_TEMPLATEPY_.py
Normal file
1
src/Tools/_TEMPLATEPY_/_TEMPLATEPY_.py
Normal file
@@ -0,0 +1 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
25
src/Tools/_TEMPLATEPY_/_TEMPLATEPY_Gui.py
Normal file
25
src/Tools/_TEMPLATEPY_/_TEMPLATEPY_Gui.py
Normal file
@@ -0,0 +1,25 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# FreeCAD tools of the _TEMPLATEPY_ workbench
|
||||
# (c) 2001 Juergen Riegel
|
||||
# License LGPL
|
||||
|
||||
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())
|
||||
72
src/Tools/_TEMPLATE_/App/App_TEMPLATE_.cpp
Normal file
72
src/Tools/_TEMPLATE_/App/App_TEMPLATE_.cpp
Normal file
@@ -0,0 +1,72 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) YEAR YOUR NAME <Your e-mail address> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#include <Python.h>
|
||||
|
||||
|
||||
#include <Base/Console.h>
|
||||
#include <Base/Interpreter.h>
|
||||
#include <Base/PyObjectBase.h>
|
||||
|
||||
#include <CXX/Extensions.hxx>
|
||||
#include <CXX/Objects.hxx>
|
||||
|
||||
|
||||
namespace _TEMPLATE_
|
||||
{
|
||||
class Module: public Py::ExtensionModule<Module>
|
||||
{
|
||||
public:
|
||||
Module()
|
||||
: Py::ExtensionModule<Module>("_TEMPLATE_")
|
||||
{
|
||||
initialize("This module is the _TEMPLATE_ module."); // register with Python
|
||||
}
|
||||
|
||||
virtual ~Module()
|
||||
{}
|
||||
|
||||
private:
|
||||
};
|
||||
|
||||
PyObject* initModule()
|
||||
{
|
||||
return Base::Interpreter().addModule(new Module);
|
||||
}
|
||||
|
||||
|
||||
} // namespace _TEMPLATE_
|
||||
|
||||
|
||||
/* Python entry */
|
||||
PyMOD_INIT_FUNC(_TEMPLATE_)
|
||||
{
|
||||
// ADD YOUR CODE HERE
|
||||
//
|
||||
//
|
||||
PyObject* mod = _TEMPLATE_::initModule();
|
||||
Base::Console().log("Loading _TEMPLATE_ module... done\n");
|
||||
PyMOD_Return(mod);
|
||||
}
|
||||
19
src/Tools/_TEMPLATE_/App/CMakeLists.txt
Normal file
19
src/Tools/_TEMPLATE_/App/CMakeLists.txt
Normal file
@@ -0,0 +1,19 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
set(_TEMPLATE__LIBS
|
||||
FreeCADApp
|
||||
)
|
||||
|
||||
SET(_TEMPLATE__SRCS
|
||||
App_TEMPLATE_.cpp
|
||||
PreCompiled.h
|
||||
)
|
||||
|
||||
add_library(_TEMPLATE_ SHARED ${_TEMPLATE__SRCS})
|
||||
target_link_libraries(_TEMPLATE_ ${_TEMPLATE__LIBS})
|
||||
|
||||
|
||||
SET_BIN_DIR(_TEMPLATE_ _TEMPLATE_ /Mod/_TEMPLATE_)
|
||||
SET_PYTHON_PREFIX_SUFFIX(_TEMPLATE_)
|
||||
|
||||
install(TARGETS _TEMPLATE_ DESTINATION ${CMAKE_INSTALL_LIBDIR})
|
||||
55
src/Tools/_TEMPLATE_/App/PreCompiled.h
Normal file
55
src/Tools/_TEMPLATE_/App/PreCompiled.h
Normal file
@@ -0,0 +1,55 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) YEAR YOUR NAME <Your e-mail address> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <FCConfig.h>
|
||||
|
||||
// Exporting of App classes
|
||||
#ifdef FC_OS_WIN32
|
||||
# define _TEMPLATE_AppExport __declspec(dllexport)
|
||||
#else // for Linux
|
||||
# define _TEMPLATE_AppExport
|
||||
#endif
|
||||
|
||||
// standard
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
|
||||
// STL
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <stack>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// Xerces
|
||||
#include <xercesc/util/XercesDefs.hpp>
|
||||
31
src/Tools/_TEMPLATE_/CMakeLists.txt
Normal file
31
src/Tools/_TEMPLATE_/CMakeLists.txt
Normal file
@@ -0,0 +1,31 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
add_subdirectory(App)
|
||||
if(BUILD_GUI)
|
||||
add_subdirectory(Gui)
|
||||
endif(BUILD_GUI)
|
||||
|
||||
set(_TEMPLATE__Scripts
|
||||
Init.py
|
||||
)
|
||||
|
||||
if(BUILD_GUI)
|
||||
list (APPEND _TEMPLATE__Scripts InitGui.py)
|
||||
endif(BUILD_GUI)
|
||||
|
||||
add_custom_target(_TEMPLATE_Scripts ALL
|
||||
SOURCES ${_TEMPLATE__Scripts}
|
||||
)
|
||||
|
||||
fc_target_copy_resource_flat(_TEMPLATE_Scripts
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
${CMAKE_BINARY_DIR}/Mod/_TEMPLATE_
|
||||
${_TEMPLATE__Scripts}
|
||||
)
|
||||
|
||||
install(
|
||||
FILES
|
||||
${_TEMPLATE__Scripts}
|
||||
DESTINATION
|
||||
Mod/_TEMPLATE_
|
||||
)
|
||||
86
src/Tools/_TEMPLATE_/Gui/App_TEMPLATE_Gui.cpp
Normal file
86
src/Tools/_TEMPLATE_/Gui/App_TEMPLATE_Gui.cpp
Normal file
@@ -0,0 +1,86 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) YEAR YOUR NAME <Your e-mail address> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#include <Python.h>
|
||||
|
||||
|
||||
#include <Base/Console.h>
|
||||
#include <Base/Interpreter.h>
|
||||
#include <Base/PyObjectBase.h>
|
||||
#include <Gui/Application.h>
|
||||
|
||||
#include "Workbench.h"
|
||||
|
||||
#include <CXX/Extensions.hxx>
|
||||
#include <CXX/Objects.hxx>
|
||||
|
||||
// use a different name to CreateCommand()
|
||||
void Create_TEMPLATE_Commands(void);
|
||||
|
||||
|
||||
namespace _TEMPLATE_Gui
|
||||
{
|
||||
class Module: public Py::ExtensionModule<Module>
|
||||
{
|
||||
public:
|
||||
Module()
|
||||
: Py::ExtensionModule<Module>("_TEMPLATE_Gui")
|
||||
{
|
||||
initialize("This module is the _TEMPLATE_Gui module."); // register with Python
|
||||
}
|
||||
|
||||
virtual ~Module()
|
||||
{}
|
||||
|
||||
private:
|
||||
};
|
||||
|
||||
PyObject* initModule()
|
||||
{
|
||||
return Base::Interpreter().addModule(new Module);
|
||||
}
|
||||
|
||||
} // namespace _TEMPLATE_Gui
|
||||
|
||||
|
||||
/* Python entry */
|
||||
PyMOD_INIT_FUNC(_TEMPLATE_Gui)
|
||||
{
|
||||
if (!Gui::Application::Instance) {
|
||||
PyErr_SetString(PyExc_ImportError, "Cannot load Gui module in console application.");
|
||||
PyMOD_Return(0);
|
||||
}
|
||||
|
||||
// instantiating the commands
|
||||
Create_TEMPLATE_Commands();
|
||||
_TEMPLATE_Gui::Workbench::init();
|
||||
|
||||
// ADD YOUR CODE HERE
|
||||
//
|
||||
//
|
||||
PyObject* mod = _TEMPLATE_Gui::initModule();
|
||||
Base::Console().log("Loading GUI of _TEMPLATE_ module... done\n");
|
||||
PyMOD_Return(mod);
|
||||
}
|
||||
30
src/Tools/_TEMPLATE_/Gui/CMakeLists.txt
Normal file
30
src/Tools/_TEMPLATE_/Gui/CMakeLists.txt
Normal file
@@ -0,0 +1,30 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
include_directories(
|
||||
${CMAKE_SOURCE_DIR}/src
|
||||
${CMAKE_CURRENT_BINARY_DIR}
|
||||
)
|
||||
|
||||
set(_TEMPLATE_Gui_LIBS
|
||||
_TEMPLATE_
|
||||
FreeCADGui
|
||||
)
|
||||
|
||||
qt_add_resources(_TEMPLATE__QRC_SRCS Resources/_TEMPLATE_.qrc)
|
||||
|
||||
SET(_TEMPLATE_Gui_SRCS
|
||||
${_TEMPLATE__QRC_SRCS}
|
||||
App_TEMPLATE_Gui.cpp
|
||||
Command.cpp
|
||||
PreCompiled.h
|
||||
Workbench.cpp
|
||||
Workbench.h
|
||||
)
|
||||
|
||||
add_library(_TEMPLATE_Gui SHARED ${_TEMPLATE_Gui_SRCS})
|
||||
target_link_libraries(_TEMPLATE_Gui ${_TEMPLATE_Gui_LIBS})
|
||||
|
||||
SET_BIN_DIR(_TEMPLATE_Gui _TEMPLATE_Gui /Mod/_TEMPLATE_)
|
||||
SET_PYTHON_PREFIX_SUFFIX(_TEMPLATE_Gui)
|
||||
|
||||
install(TARGETS _TEMPLATE_Gui DESTINATION ${CMAKE_INSTALL_LIBDIR})
|
||||
60
src/Tools/_TEMPLATE_/Gui/Command.cpp
Normal file
60
src/Tools/_TEMPLATE_/Gui/Command.cpp
Normal file
@@ -0,0 +1,60 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) YEAR YOUR NAME <Your e-mail address> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
#include <App/Document.h>
|
||||
#include <Base/Console.h>
|
||||
#include <Gui/Application.h>
|
||||
#include <Gui/Command.h>
|
||||
|
||||
|
||||
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
||||
|
||||
//===========================================================================
|
||||
// Cmd_TEMPLATE_Test THIS IS JUST A TEST COMMAND
|
||||
//===========================================================================
|
||||
DEF_STD_CMD(Cmd_TEMPLATE_Test)
|
||||
|
||||
Cmd_TEMPLATE_Test::Cmd_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";
|
||||
}
|
||||
|
||||
void Cmd_TEMPLATE_Test::activated(int)
|
||||
{
|
||||
Base::Console().message("Hello, World!\n");
|
||||
}
|
||||
|
||||
void Create_TEMPLATE_Commands(void)
|
||||
{
|
||||
Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager();
|
||||
rcCmdMgr.addCommand(new Cmd_TEMPLATE_Test());
|
||||
}
|
||||
63
src/Tools/_TEMPLATE_/Gui/PreCompiled.h
Normal file
63
src/Tools/_TEMPLATE_/Gui/PreCompiled.h
Normal file
@@ -0,0 +1,63 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) YEAR YOUR NAME <Your e-mail address> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <FCConfig.h>
|
||||
|
||||
// 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
|
||||
#endif
|
||||
|
||||
// standard
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
|
||||
// STL
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <queue>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <stack>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// Xerces
|
||||
#include <xercesc/util/XercesDefs.hpp>
|
||||
|
||||
#ifdef FC_OS_WIN32
|
||||
# include <windows.h>
|
||||
#endif
|
||||
|
||||
// Qt Toolkit
|
||||
#include <Gui/QtAll.h>
|
||||
5
src/Tools/_TEMPLATE_/Gui/Resources/_TEMPLATE_.qrc
Normal file
5
src/Tools/_TEMPLATE_/Gui/Resources/_TEMPLATE_.qrc
Normal file
@@ -0,0 +1,5 @@
|
||||
<!DOCTYPE RCC><RCC version="1.0">
|
||||
<qresource>
|
||||
<file>icons/_TEMPLATE_Workbench.svg</file>
|
||||
</qresource>
|
||||
</RCC>
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<!-- Created with Inkscape (http://www.inkscape.org/) -->
|
||||
|
||||
<svg
|
||||
width="64"
|
||||
height="64"
|
||||
id="svg3140"
|
||||
version="1.1"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<defs
|
||||
id="defs3142" />
|
||||
<metadata
|
||||
id="metadata3145">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<g
|
||||
id="layer1">
|
||||
<g
|
||||
id="layer1-4"
|
||||
transform="translate(-6e-6,-0.36363683)">
|
||||
<g
|
||||
transform="matrix(0.8506406,0,0,0.8506406,187.82699,-0.1960013)"
|
||||
id="g3813-3">
|
||||
<g
|
||||
id="g2"
|
||||
transform="matrix(2.7626237,0,0,2.7626237,-216.92708,5.3602404)">
|
||||
<path
|
||||
d="m 22,3.9997423 -3.999742,4.0002581 h -8 V 10.999806 H 14 v 4.000259 h -3.999742 v 4.999678 L 5.9999997,24 h 4.0503843 c 0.30326,-1e-6 0.571883,-0.195269 0.66559,-0.48369 l 0.723985,-2.22828 c 0.06925,-0.213087 0.236489,-0.379833 0.449583,-0.449065 l 0.556553,-0.180868 c 0.213108,-0.06926 0.446577,-0.03248 0.627866,0.09922 l 1.894968,1.377173 c 0.245331,0.178232 0.57787,0.178229 0.823203,0 l 1.698598,-1.234547 c 0.245363,-0.178242 0.347963,-0.493948 0.254247,-0.782378 l -0.723984,-2.22828 c -0.06926,-0.213109 -0.03197,-0.446575 0.09974,-0.627866 l 0.344164,-0.473355 c 0.131697,-0.181276 0.34179,-0.288856 0.565855,-0.28887 l 2.343001,5.1e-4 c 0.303278,10e-6 0.571885,-0.19577 0.66559,-0.484207 l 0.649054,-1.996771 c 0.0937,-0.288413 -0.0089,-0.60465 -0.254247,-0.782895 L 19.538664,11.858666 C 19.357381,11.726957 19.250306,11.516889 19.250311,11.292812 V 10.70732 c 1.9e-5,-0.224072 0.107062,-0.434681 0.288353,-0.566372 L 21.711646,8.5622376 C 21.892924,8.4305313 21.999999,8.219938 22,7.9958659 Z"
|
||||
style="fill:#418fde;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.64567;stroke-linecap:square"
|
||||
id="path8" />
|
||||
<path
|
||||
id="path7"
|
||||
style="display:inline;fill:#ff585d;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.64567;stroke-linecap:square"
|
||||
d="m 18,0 -4,4 h 4 V 8 L 22,4 V 0 Z M 6,16 2,20 v 4 h 4 l 4,-4 H 6 Z" />
|
||||
<path
|
||||
d="M 6,0 2,4 V 20 L 6,16 V 4 h 8 l 4,-4 z"
|
||||
style="fill:#cb333b;fill-rule:evenodd;stroke-width:2.64567;stroke-linecap:square"
|
||||
id="path3" />
|
||||
<path
|
||||
d="M 5.9999997,19.999743 H 10.000258 V 15.000065 H 14 V 10.999806 H 10.000258 V 8.0000004 h 8 V 3.9997423 H 5.9999997 Z"
|
||||
style="fill:#fefefe;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.64567;stroke-linecap:square"
|
||||
id="path9" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.0 KiB |
58
src/Tools/_TEMPLATE_/Gui/Workbench.cpp
Normal file
58
src/Tools/_TEMPLATE_/Gui/Workbench.cpp
Normal file
@@ -0,0 +1,58 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) YEAR YOUR NAME <Your e-mail address> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
#include "Workbench.h"
|
||||
#include <Gui/MenuManager.h>
|
||||
#include <Gui/ToolBarManager.h>
|
||||
|
||||
using namespace _TEMPLATE_Gui;
|
||||
|
||||
/// @namespace _TEMPLATE_Gui @class Workbench
|
||||
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* test = new Gui::MenuItem;
|
||||
root->insertItem(item, test);
|
||||
test->setCommand("_TEMPLATE_");
|
||||
*test << "_TEMPLATE__Test";
|
||||
return root;
|
||||
}
|
||||
|
||||
Gui::ToolBarItem* Workbench::setupToolBars() const
|
||||
{
|
||||
Gui::ToolBarItem* root = StdWorkbench::setupToolBars();
|
||||
Gui::ToolBarItem* test = new Gui::ToolBarItem(root);
|
||||
test->setCommand("_TEMPLATE_ Tools");
|
||||
*test << "_TEMPLATE__Test";
|
||||
return root;
|
||||
}
|
||||
46
src/Tools/_TEMPLATE_/Gui/Workbench.h
Normal file
46
src/Tools/_TEMPLATE_/Gui/Workbench.h
Normal file
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) YEAR YOUR NAME <Your e-mail address> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Gui/Workbench.h>
|
||||
|
||||
namespace _TEMPLATE_Gui
|
||||
{
|
||||
|
||||
class Workbench: public Gui::StdWorkbench
|
||||
{
|
||||
TYPESYSTEM_HEADER();
|
||||
|
||||
public:
|
||||
Workbench();
|
||||
virtual ~Workbench();
|
||||
|
||||
protected:
|
||||
Gui::MenuItem* setupMenuBar() const;
|
||||
Gui::ToolBarItem* setupToolBars() const;
|
||||
};
|
||||
|
||||
} // namespace _TEMPLATE_Gui
|
||||
4
src/Tools/_TEMPLATE_/Init.py
Normal file
4
src/Tools/_TEMPLATE_/Init.py
Normal file
@@ -0,0 +1,4 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# FreeCAD init script of the _TEMPLATE_ module
|
||||
# (c) 2001 Juergen Riegel LGPL
|
||||
21
src/Tools/_TEMPLATE_/InitGui.py
Normal file
21
src/Tools/_TEMPLATE_/InitGui.py
Normal file
@@ -0,0 +1,21 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# _TEMPLATE_ gui init module
|
||||
# (c) 2001 Juergen Riegel LGPL
|
||||
|
||||
|
||||
class _TEMPLATE_Workbench(Workbench):
|
||||
"_TEMPLATE_ workbench object"
|
||||
|
||||
MenuText = "_TEMPLATE_"
|
||||
ToolTip = "_TEMPLATE_ workbench"
|
||||
|
||||
def Initialize(self):
|
||||
# load the module
|
||||
import _TEMPLATE_Gui
|
||||
|
||||
def GetClassName(self):
|
||||
return "_TEMPLATE_Gui::Workbench"
|
||||
|
||||
|
||||
Gui.addWorkbench(_TEMPLATE_Workbench())
|
||||
2
src/Tools/_TEMPLATE_/_TEMPLATE_.dox
Normal file
2
src/Tools/_TEMPLATE_/_TEMPLATE_.dox
Normal file
@@ -0,0 +1,2 @@
|
||||
/** \defgroup TEMPLATE _TEMPLATE_
|
||||
* \ingroup WORKBENCHES */
|
||||
46
src/Tools/_TEMPLATE_/_TEMPLATE_Global.h
Normal file
46
src/Tools/_TEMPLATE_/_TEMPLATE_Global.h
Normal file
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) 2022 Werner Mayer <wmayer[at]users.sourceforge.net> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
#include <FCGlobal.h>
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
// _TEMPLATE_
|
||||
#ifndef _TEMPLATE_Export
|
||||
# ifdef _TEMPLATE__EXPORTS
|
||||
# define _TEMPLATE_Export FREECAD_DECL_EXPORT
|
||||
# else
|
||||
# define _TEMPLATE_Export FREECAD_DECL_IMPORT
|
||||
# endif
|
||||
#endif
|
||||
|
||||
// _TEMPLATE_Gui
|
||||
#ifndef _TEMPLATE_GuiExport
|
||||
# ifdef _TEMPLATE_Gui_EXPORTS
|
||||
# define _TEMPLATE_GuiExport FREECAD_DECL_EXPORT
|
||||
# else
|
||||
# define _TEMPLATE_GuiExport FREECAD_DECL_IMPORT
|
||||
# endif
|
||||
#endif
|
||||
3
src/Tools/bindings/.gitignore
vendored
Normal file
3
src/Tools/bindings/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# ignore the pyc files created while compile
|
||||
model/*.pyc
|
||||
templates/*.pyc
|
||||
113
src/Tools/bindings/generate.py
Normal file
113
src/Tools/bindings/generate.py
Normal file
@@ -0,0 +1,113 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2006 Jürgen Riegel GPL
|
||||
|
||||
import os
|
||||
import sys
|
||||
import getopt
|
||||
import model.generateModel_Module
|
||||
import model.generateModel_Python
|
||||
import templates.templateModule
|
||||
import templates.templateClassPyExport
|
||||
|
||||
|
||||
Usage = """generate - generates a FreeCAD Module out of an XML or Python model
|
||||
|
||||
Usage:
|
||||
generate [Optionen] Model.xml/py Model2.xml/py Model3.xml/py ...
|
||||
|
||||
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
|
||||
Licence: GPL
|
||||
|
||||
Version:
|
||||
0.3
|
||||
"""
|
||||
|
||||
|
||||
# Globals
|
||||
|
||||
|
||||
def generate_model(filename):
|
||||
if filename.endswith(".xml"):
|
||||
return model.generateModel_Module.parse(filename)
|
||||
elif filename.endswith(".pyi"):
|
||||
return model.generateModel_Python.parse(filename)
|
||||
raise ValueError("invalid file extension")
|
||||
|
||||
|
||||
def generate(filename, outputPath):
|
||||
GenerateModelInst = generate_model(filename)
|
||||
|
||||
if len(GenerateModelInst.Module) != 0:
|
||||
Module = templates.templateModule.TemplateModule()
|
||||
Module.outputDir = outputPath
|
||||
Module.module = GenerateModelInst.Module[0]
|
||||
Module.Generate()
|
||||
print("Done generating: " + GenerateModelInst.Module[0].Name)
|
||||
else:
|
||||
Export = templates.templateClassPyExport.TemplateClassPyExport()
|
||||
Export.outputDir = outputPath + "/"
|
||||
Export.inputDir = os.path.dirname(filename) + "/"
|
||||
Export.export = GenerateModelInst.PythonExport[0]
|
||||
Export.is_python = filename.endswith(".pyi")
|
||||
Export.Generate()
|
||||
if Export.is_python:
|
||||
Export.Compare()
|
||||
print("Done generating: " + GenerateModelInst.PythonExport[0].Name)
|
||||
|
||||
|
||||
def main():
|
||||
verbose = False
|
||||
outputPath = ""
|
||||
|
||||
class generateOutput:
|
||||
def write(self, data):
|
||||
pass
|
||||
|
||||
def flush(self): # mandatory for file-like objects
|
||||
pass
|
||||
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[1:], "hvo:", ["help", "verbose", "outputPath="])
|
||||
except getopt.GetoptError:
|
||||
# print help information and exit:
|
||||
sys.stderr.write(Usage)
|
||||
sys.exit(2)
|
||||
|
||||
# checking on the options
|
||||
for o, a in opts:
|
||||
if o in ("-h", "--help"):
|
||||
sys.stderr.write(Usage)
|
||||
sys.exit()
|
||||
if o in ("-o", "--outputPath"):
|
||||
outputPath = a
|
||||
if o in ("-v", "--verbose"):
|
||||
verbose = True
|
||||
|
||||
if not verbose:
|
||||
sys.stdout = generateOutput()
|
||||
|
||||
# running through the files
|
||||
if len(args) == 0:
|
||||
sys.stderr.write(Usage)
|
||||
else:
|
||||
for i in args:
|
||||
filename = os.path.abspath(i)
|
||||
if outputPath == "":
|
||||
head, _ = os.path.split(filename)
|
||||
generate(filename, head)
|
||||
else:
|
||||
generate(filename, outputPath)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
1
src/Tools/bindings/model/__init__.py
Normal file
1
src/Tools/bindings/model/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
3476
src/Tools/bindings/model/generateDS.py
Normal file
3476
src/Tools/bindings/model/generateDS.py
Normal file
File diff suppressed because it is too large
Load Diff
205
src/Tools/bindings/model/generateMetaModel_Module.xsd
Normal file
205
src/Tools/bindings/model/generateMetaModel_Module.xsd
Normal file
@@ -0,0 +1,205 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!-- Mit XMLSpy v2006 rel. 3 U bearbeitet (http://www.altova.com) von juergen Riegel (DCX) -->
|
||||
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
|
||||
<xs:element name="GenerateModel">
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element ref="Module" minOccurs="0" maxOccurs="unbounded"/>
|
||||
<xs:element name="PythonExport" minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element ref="Documentation" minOccurs="0"/>
|
||||
<xs:element name="Methode" minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element ref="Documentation"/>
|
||||
<xs:element ref="Parameter" minOccurs="0" maxOccurs="unbounded"/>
|
||||
</xs:sequence>
|
||||
<xs:attribute name="Name" type="xs:string" use="required"/>
|
||||
<xs:attribute name="Const" type="xs:boolean" use="optional"/>
|
||||
<xs:attribute name="Keyword" type="xs:boolean" use="optional" default="false"/>
|
||||
<xs:attribute name="NoArgs" type="xs:boolean" use="optional" default="false"/>
|
||||
<xs:attribute name="Class" type="xs:boolean" use="optional" default="false"/>
|
||||
<xs:attribute name="Static" type="xs:boolean" use="optional" default="false"/>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="Attribute" minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element ref="Documentation"/>
|
||||
<xs:element ref="Parameter"/>
|
||||
</xs:sequence>
|
||||
<xs:attribute name="Name" type="xs:string" use="required"/>
|
||||
<xs:attribute name="ReadOnly" type="xs:boolean" use="required"/>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="Sequence" minOccurs="0" maxOccurs="1">
|
||||
<xs:complexType>
|
||||
<xs:attribute name="sq_length" type="xs:boolean" use="required"/>
|
||||
<xs:attribute name="sq_concat" type="xs:boolean" use="required"/>
|
||||
<xs:attribute name="sq_repeat" type="xs:boolean" use="required"/>
|
||||
<xs:attribute name="sq_item" type="xs:boolean" use="required"/>
|
||||
<xs:attribute name="mp_subscript" type="xs:boolean" use="required"/>
|
||||
<xs:attribute name="sq_ass_item" type="xs:boolean" use="required"/>
|
||||
<xs:attribute name="mp_ass_subscript" type="xs:boolean" use="required"/>
|
||||
<xs:attribute name="sq_contains" type="xs:boolean" use="required"/>
|
||||
<xs:attribute name="sq_inplace_concat" type="xs:boolean" use="required"/>
|
||||
<xs:attribute name="sq_inplace_repeat" type="xs:boolean" use="required"/>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="CustomAttributes" minOccurs="0"/>
|
||||
<xs:element name="ClassDeclarations" type="xs:string"/>
|
||||
<xs:element name="ForwardDeclarations" type="xs:string"/>
|
||||
</xs:sequence>
|
||||
<xs:attribute name="Name" type="xs:string" use="required"/>
|
||||
<xs:attribute name="PythonName" type="xs:string" use="optional"/>
|
||||
<xs:attribute name="Include" type="xs:string" use="required"/>
|
||||
<xs:attribute name="Father" type="xs:string" use="required"/>
|
||||
<xs:attribute name="Twin" type="xs:string" use="required"/>
|
||||
<xs:attribute name="Namespace" type="xs:string" use="required"/>
|
||||
<xs:attribute name="FatherInclude" type="xs:string" use="required"/>
|
||||
<xs:attribute name="FatherNamespace" type="xs:string" use="required"/>
|
||||
<xs:attribute name="Constructor" type="xs:boolean" use="optional" default="false"/>
|
||||
<xs:attribute name="NumberProtocol" type="xs:boolean" use="optional" default="false"/>
|
||||
<xs:attribute name="RichCompare" type="xs:boolean" use="optional" default="false"/>
|
||||
<xs:attribute name="TwinPointer" type="xs:string" use="required"/>
|
||||
<xs:attribute name="Delete" type="xs:boolean" use="optional" default="false"/>
|
||||
<xs:attribute name="Reference" type="xs:boolean" use="optional"/>
|
||||
<xs:attribute name="Initialization" type="xs:boolean" use="optional" default="false"/>
|
||||
<xs:attribute name="DisableNotify" type="xs:boolean" use="optional" default="false"/>
|
||||
<xs:attribute name="DescriptorGetter" type="xs:boolean" use="optional" default="false"/>
|
||||
<xs:attribute name="DescriptorSetter" type="xs:boolean" use="optional" default="false"/>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="Module">
|
||||
<xs:annotation>
|
||||
<xs:documentation>This is the module root element</xs:documentation>
|
||||
</xs:annotation>
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element ref="Documentation" minOccurs="0"/>
|
||||
<xs:element name="Dependencies" minOccurs="0">
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element name="Module" minOccurs="0" maxOccurs="unbounded"/>
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="Content">
|
||||
<xs:annotation>
|
||||
<xs:documentation>This element holds the content of the module</xs:documentation>
|
||||
</xs:annotation>
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element name="Property" minOccurs="0" maxOccurs="unbounded"/>
|
||||
<xs:element name="Feature" minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Represent a Feature in the module</xs:documentation>
|
||||
</xs:annotation>
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element ref="Documentation" minOccurs="0">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Documentation of this object</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:element>
|
||||
<xs:element ref="Property" minOccurs="0" maxOccurs="unbounded"/>
|
||||
<xs:element ref="ViewProvider" minOccurs="0"/>
|
||||
</xs:sequence>
|
||||
<xs:attribute name="Name" type="xs:string" use="required"/>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="DocObject" minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Represents a Document Object in the module</xs:documentation>
|
||||
</xs:annotation>
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element ref="Documentation" minOccurs="0"/>
|
||||
<xs:element ref="Property" minOccurs="0" maxOccurs="unbounded"/>
|
||||
</xs:sequence>
|
||||
<xs:attribute name="Name" type="xs:string" use="required"/>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="GuiCommand" minOccurs="0" maxOccurs="unbounded">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Creates a GuiCommand in this module</xs:documentation>
|
||||
</xs:annotation>
|
||||
</xs:element>
|
||||
<xs:element name="PreferencesPage" minOccurs="0" maxOccurs="unbounded"/>
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:sequence>
|
||||
<xs:attribute name="Name" type="xs:string" use="required"/>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="Property">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Defines a class property</xs:documentation>
|
||||
</xs:annotation>
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element ref="Documentation" minOccurs="0"/>
|
||||
</xs:sequence>
|
||||
<xs:attribute name="Name" type="xs:string" use="required"/>
|
||||
<xs:attribute name="Type" type="xs:string" use="required"/>
|
||||
<xs:attribute name="StartValue" type="xs:string" use="optional"/>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="Documentation">
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element name="Author" minOccurs="0">
|
||||
<xs:complexType>
|
||||
<xs:simpleContent>
|
||||
<xs:extension base="xs:string">
|
||||
<xs:attribute name="Name" type="xs:string" use="required"/>
|
||||
<xs:attribute name="EMail" type="xs:string" use="required"/>
|
||||
<xs:attribute name="Licence" type="xs:string" use="optional" default="LGPL"/>
|
||||
</xs:extension>
|
||||
</xs:simpleContent>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="DeveloperDocu" type="xs:string" minOccurs="0"/>
|
||||
<xs:element name="UserDocu" type="xs:string" minOccurs="0"/>
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="ViewProvider">
|
||||
<xs:annotation>
|
||||
<xs:documentation>Defines a ViewProvider for an Object</xs:documentation>
|
||||
</xs:annotation>
|
||||
<xs:complexType>
|
||||
<xs:sequence>
|
||||
<xs:element ref="Property" minOccurs="0" maxOccurs="unbounded"/>
|
||||
</xs:sequence>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
<xs:element name="Parameter">
|
||||
<xs:complexType>
|
||||
<xs:attribute name="Name" type="xs:string" use="required"/>
|
||||
<xs:attribute name="Type" use="required">
|
||||
<xs:simpleType>
|
||||
<xs:restriction base="xs:string">
|
||||
<xs:enumeration value="Int"/>
|
||||
<xs:enumeration value="Long"/>
|
||||
<xs:enumeration value="String"/>
|
||||
<xs:enumeration value="Object"/>
|
||||
<xs:enumeration value="Float"/>
|
||||
<xs:enumeration value="Complex"/>
|
||||
<xs:enumeration value="Char"/>
|
||||
<xs:enumeration value="Tuple"/>
|
||||
<xs:enumeration value="List"/>
|
||||
<xs:enumeration value="Dict"/>
|
||||
<xs:enumeration value="Module"/>
|
||||
<xs:enumeration value="Callable"/>
|
||||
</xs:restriction>
|
||||
</xs:simpleType>
|
||||
</xs:attribute>
|
||||
</xs:complexType>
|
||||
</xs:element>
|
||||
</xs:schema>
|
||||
3230
src/Tools/bindings/model/generateModel_Module.py
Normal file
3230
src/Tools/bindings/model/generateModel_Module.py
Normal file
File diff suppressed because it is too large
Load Diff
16
src/Tools/bindings/model/generateModel_ModuleTest.xml
Normal file
16
src/Tools/bindings/model/generateModel_ModuleTest.xml
Normal file
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<GenerateModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="generateMetaModel_Module.xsd">
|
||||
<Module Name="GenerateTestDummy">
|
||||
<Content>
|
||||
<Feature Name="Test1">
|
||||
<Documentation><Author EMail="juergen.riegel@web.de" Name="Juergen Riegel"/></Documentation>
|
||||
<Property Type="App::PropertyString" Name="Name"/>
|
||||
<Property Type="App::PropertyInteger" Name="Count"/>
|
||||
<Property Type="App::PropertyFloat" Name="Distance"/>
|
||||
<ViewProvider>
|
||||
<Property Type="App::PropertyInt" Name="VisMode"></Property>
|
||||
</ViewProvider>
|
||||
</Feature>
|
||||
</Content>
|
||||
</Module>
|
||||
</GenerateModel>
|
||||
778
src/Tools/bindings/model/generateModel_Python.py
Normal file
778
src/Tools/bindings/model/generateModel_Python.py
Normal file
@@ -0,0 +1,778 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
"""Parses Python binding interface files into a typed AST model."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
import ast
|
||||
import re
|
||||
from typing import List
|
||||
from model.typedModel import (
|
||||
GenerateModel,
|
||||
PythonExport,
|
||||
Methode,
|
||||
Attribute,
|
||||
Documentation,
|
||||
Author,
|
||||
Parameter,
|
||||
ParameterType,
|
||||
SequenceProtocol,
|
||||
)
|
||||
|
||||
SIGNATURE_SEP = re.compile(r"\s+--\s+", re.DOTALL)
|
||||
SELF_CLS_ARG = re.compile(r"\(\s*(self|cls)(\s*,\s*)?")
|
||||
|
||||
|
||||
class ArgumentKind(Enum):
|
||||
PositionOnly = 0
|
||||
Arg = 1
|
||||
VarArg = 2
|
||||
KwOnly = 3
|
||||
KwArg = 4
|
||||
|
||||
|
||||
@dataclass
|
||||
class FuncArgument:
|
||||
name: str
|
||||
annotation: str
|
||||
kind: ArgumentKind
|
||||
|
||||
|
||||
class FunctionSignature:
|
||||
"""
|
||||
Parse function arguments with correct classification and order.
|
||||
"""
|
||||
|
||||
args: list[FuncArgument]
|
||||
has_keywords: bool
|
||||
docstring: str
|
||||
annotated_text: str
|
||||
text: str
|
||||
|
||||
const_flag: bool = False
|
||||
static_flag: bool = False
|
||||
class_flag: bool = False
|
||||
noargs_flag: bool = False
|
||||
is_overload: bool = False
|
||||
|
||||
def __init__(self, func: ast.FunctionDef):
|
||||
self.args = []
|
||||
self.has_keywords = False
|
||||
self.is_overload = False
|
||||
self.docstring = ast.get_docstring(func) or ""
|
||||
|
||||
args = func.args
|
||||
self.update_flags(func)
|
||||
|
||||
self.args.extend(
|
||||
(
|
||||
FuncArgument(
|
||||
arg.arg,
|
||||
self.get_annotation_str(arg.annotation),
|
||||
ArgumentKind.PositionOnly,
|
||||
)
|
||||
for arg in args.posonlyargs
|
||||
),
|
||||
)
|
||||
|
||||
self.args.extend(
|
||||
(
|
||||
FuncArgument(
|
||||
arg.arg,
|
||||
self.get_annotation_str(arg.annotation),
|
||||
ArgumentKind.Arg,
|
||||
)
|
||||
for arg in args.args
|
||||
),
|
||||
)
|
||||
|
||||
# tricky part to determine if there are keyword arguments or not
|
||||
if args.args:
|
||||
if args.args[0].arg in ("self", "cls"):
|
||||
instance_args = len(args.args) > 1
|
||||
else:
|
||||
instance_args = True
|
||||
else:
|
||||
instance_args = False
|
||||
|
||||
self.has_keywords = bool(instance_args or args.kwonlyargs or args.kwarg)
|
||||
|
||||
if args.vararg:
|
||||
self.args.append(
|
||||
FuncArgument(
|
||||
args.vararg.arg,
|
||||
self.get_annotation_str(args.vararg.annotation),
|
||||
ArgumentKind.VarArg,
|
||||
),
|
||||
)
|
||||
|
||||
self.args.extend(
|
||||
(
|
||||
FuncArgument(
|
||||
arg.arg,
|
||||
self.get_annotation_str(arg.annotation),
|
||||
ArgumentKind.KwOnly,
|
||||
)
|
||||
for arg in args.kwonlyargs
|
||||
),
|
||||
)
|
||||
|
||||
if args.kwarg:
|
||||
self.args.append(
|
||||
FuncArgument(
|
||||
args.kwarg.arg,
|
||||
self.get_annotation_str(args.kwarg.annotation),
|
||||
ArgumentKind.KwArg,
|
||||
),
|
||||
)
|
||||
|
||||
# Annotated signatures (Not supported by __text_signature__)
|
||||
returns = ast.unparse(func.returns) if func.returns else "object"
|
||||
parameters = ast.unparse(func.args)
|
||||
self.annotated_text = SELF_CLS_ARG.sub("(", f"{func.name}({parameters}) -> {returns}", 1)
|
||||
|
||||
# Not Annotated signatures (supported by __text_signature__)
|
||||
all_args = [*args.posonlyargs, *args.args, args.vararg, *args.kwonlyargs, args.kwarg]
|
||||
for item in all_args:
|
||||
if item:
|
||||
item.annotation = None
|
||||
parameters = ast.unparse(args)
|
||||
self.text = SELF_CLS_ARG.sub(r"($\1\2", f"{func.name}({parameters})", 1)
|
||||
|
||||
def get_annotation_str(self, node: ast.AST | None) -> str:
|
||||
if not node:
|
||||
return "object"
|
||||
return ast.unparse(node)
|
||||
|
||||
def update_flags(self, func: ast.FunctionDef) -> None:
|
||||
for deco in func.decorator_list:
|
||||
match deco:
|
||||
case ast.Name(id, _):
|
||||
name = id
|
||||
case ast.Attribute(_, attr, _):
|
||||
name = attr
|
||||
case _:
|
||||
continue
|
||||
|
||||
match name:
|
||||
case "constmethod":
|
||||
self.const_flag = True
|
||||
case "classmethod":
|
||||
self.class_flag = True
|
||||
case "no_args":
|
||||
self.noargs_flag = True
|
||||
case "staticmethod":
|
||||
self.static_flag = True
|
||||
case "overload":
|
||||
self.is_overload = True
|
||||
|
||||
|
||||
class Function:
|
||||
name: str
|
||||
signatures: list[FunctionSignature]
|
||||
|
||||
def __init__(self, func: ast.FunctionDef) -> None:
|
||||
self.name = func.name
|
||||
self.signatures = [FunctionSignature(func)]
|
||||
|
||||
def update(self, func: ast.FunctionDef) -> None:
|
||||
self.signatures.append(FunctionSignature(func))
|
||||
|
||||
@property
|
||||
def docstring(self) -> str:
|
||||
return "\n".join((f.docstring for f in self.signatures))
|
||||
|
||||
@property
|
||||
def has_keywords(self) -> bool:
|
||||
overloads = len(self.signatures) > 1
|
||||
if overloads:
|
||||
return any(sig.has_keywords for sig in self.signatures if sig.is_overload)
|
||||
return self.signatures[0].has_keywords
|
||||
|
||||
@property
|
||||
def signature(self) -> FunctionSignature | None:
|
||||
"""First non overload signature"""
|
||||
for sig in self.signatures:
|
||||
if not sig.is_overload:
|
||||
return sig
|
||||
return None
|
||||
|
||||
@property
|
||||
def static_flag(self) -> bool:
|
||||
return any(sig.static_flag for sig in self.signatures)
|
||||
|
||||
@property
|
||||
def const_flag(self) -> bool:
|
||||
return any(sig.const_flag for sig in self.signatures)
|
||||
|
||||
@property
|
||||
def class_flag(self) -> bool:
|
||||
return any(sig.class_flag for sig in self.signatures)
|
||||
|
||||
@property
|
||||
def noargs_flag(self) -> bool:
|
||||
return any(sig.noargs_flag for sig in self.signatures)
|
||||
|
||||
def add_signature_docs(self, doc: Documentation) -> None:
|
||||
if len(self.signatures) == 1:
|
||||
docstring = [self.signatures[0].text]
|
||||
signature = [self.signatures[0].annotated_text]
|
||||
else:
|
||||
docstring = [sig.text for sig in self.signatures if not sig.is_overload]
|
||||
signature = [sig.annotated_text for sig in self.signatures if sig.is_overload]
|
||||
|
||||
if not docstring:
|
||||
return
|
||||
|
||||
user_doc = doc.UserDocu or ""
|
||||
marker = SIGNATURE_SEP.search(user_doc)
|
||||
if marker:
|
||||
user_doc = user_doc[marker.end() :].strip()
|
||||
|
||||
docstring.append("--\n") # mark __text_signature__
|
||||
docstring.extend(signature) # Include real annotated signature in user docstring
|
||||
docstring.append(f"\n{user_doc}") # Rest of the docstring
|
||||
doc.UserDocu = "\n".join(docstring)
|
||||
|
||||
|
||||
def _extract_decorator_kwargs(decorator: ast.expr) -> dict:
|
||||
"""
|
||||
Extract keyword arguments from a decorator call like `@export(Father="...", Name="...")`.
|
||||
Returns them in a dict.
|
||||
"""
|
||||
if not isinstance(decorator, ast.Call):
|
||||
return {}
|
||||
result = {}
|
||||
for kw in decorator.keywords:
|
||||
match kw.value:
|
||||
case ast.Constant(value=val):
|
||||
result[kw.arg] = val
|
||||
case _:
|
||||
pass
|
||||
return result
|
||||
|
||||
|
||||
def _parse_docstring_for_documentation(docstring: str) -> Documentation:
|
||||
"""
|
||||
Given a docstring, parse out DeveloperDocu, UserDocu, Author, Licence, etc.
|
||||
This is a simple heuristic-based parser. Adjust as needed for your format.
|
||||
"""
|
||||
dev_docu = None
|
||||
user_docu = None
|
||||
author_name = None
|
||||
author_email = None
|
||||
author_licence = None
|
||||
|
||||
if not docstring:
|
||||
return Documentation()
|
||||
|
||||
import textwrap
|
||||
|
||||
# Remove common indentation
|
||||
dedented_docstring = textwrap.dedent(docstring).strip()
|
||||
lines = dedented_docstring.split("\n")
|
||||
user_docu_lines = []
|
||||
|
||||
for raw_line in lines:
|
||||
stripped_line = raw_line.strip()
|
||||
if stripped_line.startswith("DeveloperDocu:"):
|
||||
dev_docu = stripped_line.split("DeveloperDocu:", 1)[1].strip()
|
||||
elif stripped_line.startswith("UserDocu:"):
|
||||
user_docu = stripped_line.split("UserDocu:", 1)[1].strip()
|
||||
elif stripped_line.startswith("Author:"):
|
||||
# e.g. "Author: John Doe (john@example.com)"
|
||||
author_part = stripped_line.split("Author:", 1)[1].strip()
|
||||
match = re.search(r"(.*?)\s*\((.*?)\)", author_part)
|
||||
if match:
|
||||
author_name = match.group(1).strip()
|
||||
author_email = match.group(2).strip()
|
||||
else:
|
||||
author_name = author_part
|
||||
elif stripped_line.startswith("Licence:"):
|
||||
author_licence = stripped_line.split("Licence:", 1)[1].strip()
|
||||
else:
|
||||
user_docu_lines.append(raw_line)
|
||||
|
||||
if user_docu is None:
|
||||
user_docu = "\n".join(user_docu_lines)
|
||||
|
||||
author_obj = None
|
||||
if author_name or author_email or author_licence:
|
||||
author_obj = Author(
|
||||
content=docstring,
|
||||
Name=author_name or "",
|
||||
EMail=author_email or "",
|
||||
Licence=author_licence or "LGPL",
|
||||
)
|
||||
|
||||
return Documentation(
|
||||
Author=author_obj,
|
||||
DeveloperDocu=dev_docu,
|
||||
UserDocu=user_docu,
|
||||
)
|
||||
|
||||
|
||||
def _get_type_str(node):
|
||||
"""Recursively convert an AST node for a type annotation to its string representation."""
|
||||
match node:
|
||||
case ast.Name(id=name):
|
||||
# Handle qualified names (e.g., typing.List)
|
||||
return name
|
||||
case ast.Attribute(value=val, attr=attr):
|
||||
# For annotations like List[str] (or Final[List[str]]), build the string recursively.
|
||||
return f"{_get_type_str(val)}.{attr}"
|
||||
case ast.Subscript(value=val, slice=slice_node):
|
||||
value_str = _get_type_str(val)
|
||||
slice_str = _get_type_str(slice_node)
|
||||
return f"{value_str}[{slice_str}]"
|
||||
case ast.Tuple(elts=elts):
|
||||
# For multiple types (e.g., Tuple[int, str])
|
||||
return ", ".join(_get_type_str(elt) for elt in elts)
|
||||
case _:
|
||||
# Fallback for unsupported node types
|
||||
return "object"
|
||||
|
||||
|
||||
def _python_type_to_parameter_type(py_type: str) -> ParameterType:
|
||||
"""
|
||||
Map a Python type annotation (as a string) to the ParameterType enum if possible.
|
||||
Fallback to OBJECT if unrecognized.
|
||||
"""
|
||||
py_type = py_type.lower()
|
||||
match py_type:
|
||||
case _ if py_type in ("int", "builtins.int"):
|
||||
return ParameterType.LONG
|
||||
case _ if py_type in ("float", "builtins.float"):
|
||||
return ParameterType.FLOAT
|
||||
case _ if py_type in ("str", "builtins.str"):
|
||||
return ParameterType.STRING
|
||||
case _ if py_type in ("bool", "builtins.bool"):
|
||||
return ParameterType.BOOLEAN
|
||||
case _ if py_type.startswith(("list", "typing.list")):
|
||||
return ParameterType.LIST
|
||||
case _ if py_type.startswith(("dict", "typing.dict")):
|
||||
return ParameterType.DICT
|
||||
case _ if py_type.startswith(("callable", "typing.callable")):
|
||||
return ParameterType.CALLABLE
|
||||
case _ if py_type.startswith(("sequence", "typing.sequence")):
|
||||
return ParameterType.SEQUENCE
|
||||
case _ if py_type.startswith(("tuple", "typing.tuple")):
|
||||
return ParameterType.TUPLE
|
||||
case _ if py_type.startswith(("pycxxvector")):
|
||||
return ParameterType.VECTOR
|
||||
case _:
|
||||
return ParameterType.OBJECT
|
||||
|
||||
|
||||
def _parse_class_attributes(class_node: ast.ClassDef, source_code: str) -> List[Attribute]:
|
||||
"""
|
||||
Parse top-level attributes (e.g. `TypeId: str = ""`) from the class AST node.
|
||||
We'll create an `Attribute` for each. For the `Documentation` of each attribute,
|
||||
we might store minimal or none if there's no docstring.
|
||||
"""
|
||||
attributes = []
|
||||
default_doc = Documentation(DeveloperDocu="", UserDocu="", Author=None)
|
||||
|
||||
for idx, stmt in enumerate(class_node.body):
|
||||
if isinstance(stmt, ast.AnnAssign):
|
||||
# e.g.: `TypeId: Final[str] = ""`
|
||||
name = stmt.target.id if isinstance(stmt.target, ast.Name) else "unknown"
|
||||
# Evaluate the type annotation and detect Final for read-only attributes
|
||||
if isinstance(stmt.annotation, ast.Name):
|
||||
# e.g. `str`
|
||||
type_name = stmt.annotation.id
|
||||
readonly = False
|
||||
elif isinstance(stmt.annotation, ast.Subscript):
|
||||
# Check if this is a Final type hint, e.g. Final[int] or typing.Final[int]
|
||||
is_final = (
|
||||
isinstance(stmt.annotation.value, ast.Name)
|
||||
and stmt.annotation.value.id == "Final"
|
||||
) or (
|
||||
isinstance(stmt.annotation.value, ast.Attribute)
|
||||
and stmt.annotation.value.attr == "Final"
|
||||
)
|
||||
if is_final:
|
||||
readonly = True
|
||||
# Extract the inner type from the Final[...] annotation
|
||||
type_name = _get_type_str(stmt.annotation.slice)
|
||||
else:
|
||||
type_name = _get_type_str(stmt.annotation)
|
||||
readonly = False
|
||||
else:
|
||||
type_name = "object"
|
||||
readonly = False
|
||||
|
||||
param_type = _python_type_to_parameter_type(type_name)
|
||||
|
||||
# Look for a docstring immediately following the attribute definition.
|
||||
attr_doc = default_doc
|
||||
if idx + 1 < len(class_node.body):
|
||||
next_stmt = class_node.body[idx + 1]
|
||||
if (
|
||||
isinstance(next_stmt, ast.Expr)
|
||||
and isinstance(next_stmt.value, ast.Constant)
|
||||
and isinstance(next_stmt.value.value, str)
|
||||
):
|
||||
docstring = next_stmt.value.value
|
||||
|
||||
# Parse the docstring to build a Documentation object.
|
||||
attr_doc = _parse_docstring_for_documentation(docstring)
|
||||
|
||||
param = Parameter(Name=name, Type=param_type)
|
||||
attr = Attribute(
|
||||
Documentation=attr_doc,
|
||||
Parameter=param,
|
||||
Name=name,
|
||||
ReadOnly=readonly,
|
||||
)
|
||||
attributes.append(attr)
|
||||
|
||||
return attributes
|
||||
|
||||
|
||||
def _parse_methods(class_node: ast.ClassDef) -> List[Methode]:
|
||||
"""
|
||||
Parse methods from the class AST node, extracting:
|
||||
- Method name
|
||||
- Parameters (from the function signature / annotations)
|
||||
- Docstring
|
||||
"""
|
||||
methods = []
|
||||
|
||||
def collect_function_defs(nodes) -> list[ast.FunctionDef]:
|
||||
funcs = []
|
||||
for node in nodes:
|
||||
if isinstance(node, ast.FunctionDef):
|
||||
funcs.append(node)
|
||||
elif isinstance(node, ast.If):
|
||||
funcs.extend(collect_function_defs(node.body))
|
||||
funcs.extend(collect_function_defs(node.orelse))
|
||||
return funcs
|
||||
|
||||
# Collect including overloads
|
||||
functions: dict[str, Function] = {}
|
||||
for func_node in collect_function_defs(class_node.body):
|
||||
if func := functions.get(func_node.name):
|
||||
func.update(func_node)
|
||||
else:
|
||||
functions[func_node.name] = Function(func_node)
|
||||
|
||||
for func in functions.values():
|
||||
doc_obj = _parse_docstring_for_documentation(func.docstring)
|
||||
func.add_signature_docs(doc_obj)
|
||||
method_params = []
|
||||
|
||||
signature = func.signature
|
||||
if signature is None:
|
||||
continue
|
||||
|
||||
# Process positional parameters (skipping self/cls)
|
||||
for arg_i, arg in enumerate(signature.args):
|
||||
param_name = arg.name
|
||||
if arg_i == 0 and param_name in ("self", "cls"):
|
||||
continue
|
||||
param_type = _python_type_to_parameter_type(arg.annotation)
|
||||
method_params.append(Parameter(Name=param_name, Type=param_type))
|
||||
|
||||
method = Methode(
|
||||
Name=func.name,
|
||||
Documentation=doc_obj,
|
||||
Parameter=method_params,
|
||||
Const=func.const_flag,
|
||||
Static=func.static_flag,
|
||||
Class=func.class_flag,
|
||||
Keyword=func.has_keywords,
|
||||
NoArgs=func.noargs_flag,
|
||||
)
|
||||
|
||||
methods.append(method)
|
||||
|
||||
return methods
|
||||
|
||||
|
||||
def _get_module_from_path(path: str) -> str:
|
||||
"""
|
||||
Returns the name of the FreeCAD module from the path.
|
||||
Examples:
|
||||
.../src/Base/Persistence.py -> "Base"
|
||||
.../src/Mod/CAM/Path/__init__.py -> "CAM"
|
||||
"""
|
||||
# 1. Split the path by the OS separator.
|
||||
import os
|
||||
|
||||
parts = path.split(os.sep)
|
||||
|
||||
# 2. Attempt to find "src" in the path components.
|
||||
try:
|
||||
idx_src = len(parts) - 1 - list(reversed(parts)).index("src")
|
||||
except ValueError:
|
||||
# If "src" is not found, we cannot determine the module name.
|
||||
return None
|
||||
|
||||
# 3. Check if there is a path component immediately after "src".
|
||||
# If there isn't, we have nothing to return.
|
||||
if idx_src + 1 >= len(parts):
|
||||
return None
|
||||
|
||||
next_part = parts[idx_src + 1]
|
||||
|
||||
# 4. If the next component is "Mod", then the module name is the
|
||||
# component AFTER "Mod" (e.g. "CAM" in "Mod/CAM").
|
||||
if next_part == "Mod":
|
||||
if idx_src + 2 < len(parts):
|
||||
return parts[idx_src + 2]
|
||||
else:
|
||||
# "Mod" is the last component
|
||||
return None
|
||||
else:
|
||||
# 5. Otherwise, if it's not "Mod", we treat that next component
|
||||
# itself as the module name (e.g. "Base").
|
||||
return next_part
|
||||
|
||||
|
||||
def _extract_module_name(import_path: str, default_module: str) -> str:
|
||||
"""
|
||||
Given an import_path like "Base.Foo", return "Base".
|
||||
If import_path has no dot (e.g., "Foo"), return default_module.
|
||||
|
||||
Examples:
|
||||
extract_module_name("Base.Foo", default_module="Fallback") -> "Base"
|
||||
extract_module_name("Foo", default_module="Fallback") -> "Fallback"
|
||||
"""
|
||||
if "." in import_path:
|
||||
# Take everything before the first dot
|
||||
return import_path.split(".", 1)[0]
|
||||
else:
|
||||
# No dot, return the fallback module name
|
||||
return default_module
|
||||
|
||||
|
||||
def _get_module_path(module_name: str) -> str:
|
||||
if module_name in ["Base", "App", "Gui"]:
|
||||
return module_name
|
||||
return "Mod/" + module_name
|
||||
|
||||
|
||||
def _parse_imports(tree) -> dict:
|
||||
"""
|
||||
Parses the given source_code for import statements and constructs
|
||||
a mapping from imported name -> module path.
|
||||
|
||||
For example, code like:
|
||||
|
||||
from Metadata import export, forward_declarations, constmethod
|
||||
from PyObjectBase import PyObjectBase
|
||||
from Base.Foo import Foo
|
||||
from typing import List, Final
|
||||
|
||||
yields a mapping of:
|
||||
{
|
||||
"export": "Metadata",
|
||||
"forward_declarations": "Metadata",
|
||||
"constmethod": "Metadata",
|
||||
"PyObjectBase": "PyObjectBase",
|
||||
"Foo": "Base.Foo",
|
||||
"List": "typing",
|
||||
"Final": "typing"
|
||||
}
|
||||
"""
|
||||
name_to_module_map = {}
|
||||
|
||||
for node in tree.body:
|
||||
match node:
|
||||
# Handle 'import X' or 'import X as Y'
|
||||
case ast.Import(names=names):
|
||||
# e.g. import foo, import foo as bar
|
||||
for alias in names:
|
||||
imported_name = alias.asname if alias.asname else alias.name
|
||||
name_to_module_map[imported_name] = alias.name
|
||||
# Handle 'from X import Y, Z as W'
|
||||
case ast.ImportFrom(module=module, names=names):
|
||||
module_name = module if module is not None else ""
|
||||
for alias in names:
|
||||
imported_name = alias.asname if alias.asname else alias.name
|
||||
name_to_module_map[imported_name] = module_name
|
||||
case _:
|
||||
pass
|
||||
|
||||
return name_to_module_map
|
||||
|
||||
|
||||
def _get_native_class_name(klass: str) -> str:
|
||||
return klass
|
||||
|
||||
|
||||
def _get_native_python_class_name(klass: str) -> str:
|
||||
if klass == "PyObjectBase":
|
||||
return klass
|
||||
return klass + "Py"
|
||||
|
||||
|
||||
def _extract_base_class_name(base: ast.expr) -> str:
|
||||
"""
|
||||
Extract the base class name from an AST node using ast.unparse.
|
||||
For generic bases (e.g. GenericParent[T]), it removes the generic part.
|
||||
For qualified names (e.g. some_module.ParentClass), it returns only the last part.
|
||||
"""
|
||||
base_str = ast.unparse(base)
|
||||
# Remove generic parameters if present.
|
||||
if "[" in base_str:
|
||||
base_str = base_str.split("[", 1)[0]
|
||||
# For qualified names, take only the class name.
|
||||
if "." in base_str:
|
||||
base_str = base_str.split(".")[-1]
|
||||
return base_str
|
||||
|
||||
|
||||
def _parse_class(class_node, source_code: str, path: str, imports_mapping: dict) -> PythonExport:
|
||||
base_class_name = None
|
||||
for base in class_node.bases:
|
||||
base_class_name = _extract_base_class_name(base)
|
||||
break # Only consider the first base class.
|
||||
|
||||
assert base_class_name is not None
|
||||
|
||||
is_exported = False
|
||||
export_decorator_kwargs = {}
|
||||
forward_declarations_text = ""
|
||||
class_declarations_text = ""
|
||||
sequence_protocol_kwargs = None
|
||||
|
||||
for decorator in class_node.decorator_list:
|
||||
match decorator:
|
||||
case ast.Name(id="export"):
|
||||
export_decorator_kwargs = {}
|
||||
is_exported = True
|
||||
case ast.Call(func=ast.Name(id="export"), keywords=_, args=_):
|
||||
export_decorator_kwargs = _extract_decorator_kwargs(decorator)
|
||||
is_exported = True
|
||||
case ast.Call(func=ast.Name(id="forward_declarations"), args=args):
|
||||
if args:
|
||||
match args[0]:
|
||||
case ast.Constant(value=val):
|
||||
forward_declarations_text = val
|
||||
case ast.Call(func=ast.Name(id="class_declarations"), args=args):
|
||||
if args:
|
||||
match args[0]:
|
||||
case ast.Constant(value=val):
|
||||
class_declarations_text = val
|
||||
case ast.Call(func=ast.Name(id="sequence_protocol"), keywords=_, args=_):
|
||||
sequence_protocol_kwargs = _extract_decorator_kwargs(decorator)
|
||||
case _:
|
||||
pass
|
||||
|
||||
# Parse imports to compute module metadata
|
||||
module_name = _get_module_from_path(path)
|
||||
|
||||
imported_from_module = imports_mapping[base_class_name]
|
||||
parent_module_name = _extract_module_name(imported_from_module, module_name)
|
||||
|
||||
class_docstring = ast.get_docstring(class_node) or ""
|
||||
doc_obj = _parse_docstring_for_documentation(class_docstring)
|
||||
class_attributes = _parse_class_attributes(class_node, source_code)
|
||||
class_methods = _parse_methods(class_node)
|
||||
|
||||
native_class_name = _get_native_class_name(class_node.name)
|
||||
native_python_class_name = _get_native_python_class_name(class_node.name)
|
||||
include = _get_module_path(module_name) + "/" + native_class_name + ".h"
|
||||
|
||||
father_native_python_class_name = _get_native_python_class_name(base_class_name)
|
||||
father_include = (
|
||||
_get_module_path(parent_module_name) + "/" + father_native_python_class_name + ".h"
|
||||
)
|
||||
|
||||
py_export = PythonExport(
|
||||
Documentation=doc_obj,
|
||||
ModuleName=module_name,
|
||||
Name=export_decorator_kwargs.get("Name", "") or native_python_class_name,
|
||||
PythonName=export_decorator_kwargs.get("PythonName", "") or None,
|
||||
Include=export_decorator_kwargs.get("Include", "") or include,
|
||||
Father=export_decorator_kwargs.get("Father", "") or father_native_python_class_name,
|
||||
Twin=export_decorator_kwargs.get("Twin", "") or native_class_name,
|
||||
TwinPointer=export_decorator_kwargs.get("TwinPointer", "") or native_class_name,
|
||||
Namespace=export_decorator_kwargs.get("Namespace", "") or module_name,
|
||||
FatherInclude=export_decorator_kwargs.get("FatherInclude", "") or father_include,
|
||||
FatherNamespace=export_decorator_kwargs.get("FatherNamespace", "") or parent_module_name,
|
||||
Constructor=export_decorator_kwargs.get("Constructor", False),
|
||||
NumberProtocol=export_decorator_kwargs.get("NumberProtocol", False),
|
||||
RichCompare=export_decorator_kwargs.get("RichCompare", False),
|
||||
Delete=export_decorator_kwargs.get("Delete", False),
|
||||
Reference=export_decorator_kwargs.get("Reference", None),
|
||||
Initialization=export_decorator_kwargs.get("Initialization", False),
|
||||
DisableNotify=export_decorator_kwargs.get("DisableNotify", False),
|
||||
DescriptorGetter=export_decorator_kwargs.get("DescriptorGetter", False),
|
||||
DescriptorSetter=export_decorator_kwargs.get("DescriptorSetter", False),
|
||||
ForwardDeclarations=forward_declarations_text,
|
||||
ClassDeclarations=class_declarations_text,
|
||||
IsExplicitlyExported=is_exported,
|
||||
)
|
||||
|
||||
# Attach sequence protocol metadata if provided.
|
||||
if sequence_protocol_kwargs is not None:
|
||||
seq_protocol = SequenceProtocol(**sequence_protocol_kwargs)
|
||||
py_export.Sequence = seq_protocol
|
||||
|
||||
py_export.Attribute.extend(class_attributes)
|
||||
py_export.Methode.extend(class_methods)
|
||||
|
||||
return py_export
|
||||
|
||||
|
||||
def parse_python_code(path: str) -> GenerateModel:
|
||||
"""
|
||||
Parse the given Python source code and build a GenerateModel containing
|
||||
PythonExport entries. If any class is explicitly exported using @export,
|
||||
only those classes are used. If no classes have the @export decorator,
|
||||
then a single non-exported class is assumed to be the export. If there
|
||||
are multiple non-exported classes, an exception is raised.
|
||||
"""
|
||||
with open(path, "r") as file:
|
||||
source_code = file.read()
|
||||
|
||||
tree = ast.parse(source_code)
|
||||
imports_mapping = _parse_imports(tree)
|
||||
|
||||
explicit_exports = []
|
||||
non_explicit_exports = []
|
||||
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.ClassDef):
|
||||
py_export = _parse_class(node, source_code, path, imports_mapping)
|
||||
if py_export.IsExplicitlyExported:
|
||||
explicit_exports.append(py_export)
|
||||
else:
|
||||
non_explicit_exports.append(py_export)
|
||||
|
||||
model = GenerateModel()
|
||||
if explicit_exports:
|
||||
# Use only explicitly exported classes.
|
||||
model.PythonExport.extend(explicit_exports)
|
||||
else:
|
||||
# No explicit exports; allow only one non-exported class.
|
||||
if len(non_explicit_exports) == 1:
|
||||
model.PythonExport.append(non_explicit_exports[0])
|
||||
elif len(non_explicit_exports) > 1:
|
||||
raise Exception(
|
||||
"Multiple non explicitly-exported classes were found, please use @export."
|
||||
)
|
||||
else:
|
||||
raise Exception("No classes found for export.")
|
||||
|
||||
return model
|
||||
|
||||
|
||||
def parse(path):
|
||||
model = parse_python_code(path)
|
||||
return model
|
||||
|
||||
|
||||
def main():
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:]
|
||||
model = parse(args[0])
|
||||
model.dump()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
189
src/Tools/bindings/model/generateTools.py
Normal file
189
src/Tools/bindings/model/generateTools.py
Normal file
@@ -0,0 +1,189 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2007 Jürgen Riegel
|
||||
|
||||
import os
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def convertMultilineString(str):
|
||||
str = str.replace("\n", "\\n")
|
||||
str = str.replace('"', '\\"')
|
||||
return str
|
||||
|
||||
|
||||
"Yet Another Python Templating Utility, Version 1.2"
|
||||
|
||||
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
|
||||
|
||||
|
||||
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, cur_line=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 cur_line < last:
|
||||
line = block[cur_line]
|
||||
match = self.restat.match(line)
|
||||
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 = cur_line + 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
|
||||
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, cur_line + 1, j, nestat)
|
||||
cur_line = j # again, i is the last line to _not_ process
|
||||
j = j + 1
|
||||
stat = self.preproc(stat, "exec")
|
||||
stat = "%s _cb(%s,%s)" % (stat, cur_line + 1, j)
|
||||
# for debugging, uncomment...: print(f"-> Executing on line {cur_line}: {stat}")
|
||||
exec(stat, self.globals, self.locals)
|
||||
cur_line = 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))
|
||||
cur_line = cur_line + 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
|
||||
if dict is not None:
|
||||
self.globals = dict
|
||||
else:
|
||||
self.globals = {}
|
||||
self.globals["sys"] = sys
|
||||
self.locals = {"_cb": self.copyblock}
|
||||
self.restat = restat
|
||||
self.restend = restend
|
||||
self.recont = recont
|
||||
self.preproc = preproc
|
||||
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
|
||||
self.copyblock()
|
||||
|
||||
|
||||
def replace(template, dict, file):
|
||||
"Test: copy a block of lines, with full processing"
|
||||
import re
|
||||
|
||||
rex = re.compile(r"@([^@]+)@")
|
||||
rbe = re.compile(r"\+")
|
||||
ren = re.compile(r"-")
|
||||
rco = re.compile(r"= ")
|
||||
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(r"@([^@]+)@")
|
||||
rbe = re.compile(r"\+")
|
||||
ren = re.compile(r"-")
|
||||
rco = re.compile(r"= ")
|
||||
x = 23 # just a variable to try substitution
|
||||
cop = copier(rex, globals(), rbe, ren, rco)
|
||||
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
|
||||
-
|
||||
Now the substitutions are @x@.
|
||||
+ if x>23:
|
||||
After all, @x@ is rather large!
|
||||
= else:
|
||||
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"
|
||||
)
|
||||
]
|
||||
print("*** input:")
|
||||
print("".join(lines_block))
|
||||
print("*** output:")
|
||||
cop.copy(lines_block)
|
||||
328
src/Tools/bindings/model/typedModel.py
Normal file
328
src/Tools/bindings/model/typedModel.py
Normal file
@@ -0,0 +1,328 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import List, Optional
|
||||
|
||||
|
||||
#
|
||||
# Enums
|
||||
#
|
||||
|
||||
|
||||
class ParameterType(str, Enum):
|
||||
BOOLEAN = "Boolean"
|
||||
INT = "Int"
|
||||
LONG = "Long"
|
||||
STRING = "String"
|
||||
OBJECT = "Object"
|
||||
FLOAT = "Float"
|
||||
COMPLEX = "Complex"
|
||||
CHAR = "Char"
|
||||
TUPLE = "Tuple"
|
||||
LIST = "List"
|
||||
DICT = "Dict"
|
||||
MODULE = "Module"
|
||||
CALLABLE = "Callable"
|
||||
SEQUENCE = "Sequence"
|
||||
VECTOR = "Vector"
|
||||
|
||||
def __str__(self):
|
||||
return self.value
|
||||
|
||||
|
||||
#
|
||||
# Supporting Classes
|
||||
#
|
||||
|
||||
|
||||
@dataclass
|
||||
class Author:
|
||||
"""Represents the <Author> element inside <Documentation>."""
|
||||
|
||||
# The text content of <Author> is effectively a string;
|
||||
# we capture it in `content` to hold the text node if needed.
|
||||
content: Optional[str] = None
|
||||
|
||||
# Attributes
|
||||
Name: str = "FreeCAD Project"
|
||||
EMail: str = "example@freecad.org"
|
||||
Licence: str = "LGPL"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Documentation:
|
||||
"""
|
||||
Corresponds to the <Documentation> element.
|
||||
Can contain an <Author>, <DeveloperDocu>, and <UserDocu>.
|
||||
"""
|
||||
|
||||
Author: Optional[Author] = None
|
||||
DeveloperDocu: Optional[str] = None
|
||||
UserDocu: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Property:
|
||||
"""
|
||||
Corresponds to <Property> in the schema.
|
||||
It has required attributes Name, Type and optional StartValue,
|
||||
plus optional child <Documentation>.
|
||||
"""
|
||||
|
||||
# Child
|
||||
Documentation: Optional[Documentation] = None
|
||||
|
||||
# Attributes
|
||||
Name: str = ""
|
||||
Type: str = ""
|
||||
StartValue: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ViewProvider:
|
||||
"""
|
||||
Corresponds to <ViewProvider>, which can contain 0..∞ <Property> children.
|
||||
"""
|
||||
|
||||
Property: List[Property] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Parameter:
|
||||
"""
|
||||
Corresponds to <Parameter> in the schema.
|
||||
It has a required 'Name' (str) and a required 'Type' (enumeration).
|
||||
"""
|
||||
|
||||
Name: str
|
||||
Type: ParameterType
|
||||
|
||||
|
||||
#
|
||||
# Elements under <PythonExport>
|
||||
#
|
||||
|
||||
|
||||
@dataclass
|
||||
class Methode:
|
||||
"""
|
||||
Corresponds to <Methode> inside <PythonExport>.
|
||||
Contains an optional <Documentation> and 0..∞ <Parameter>.
|
||||
"""
|
||||
|
||||
Documentation: Optional[Documentation] = None
|
||||
Parameter: List[Parameter] = field(default_factory=list)
|
||||
|
||||
# Attributes
|
||||
Name: str = ""
|
||||
Const: Optional[bool] = None
|
||||
Keyword: bool = False
|
||||
NoArgs: bool = False
|
||||
Class: bool = False
|
||||
Static: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class Attribute:
|
||||
"""
|
||||
Corresponds to <Attribute> inside <PythonExport>.
|
||||
It has a required <Documentation>, a required <Parameter>,
|
||||
and attributes Name, ReadOnly.
|
||||
"""
|
||||
|
||||
Documentation: Documentation
|
||||
Parameter: Parameter
|
||||
|
||||
# Attributes
|
||||
Name: str
|
||||
ReadOnly: bool
|
||||
|
||||
|
||||
@dataclass
|
||||
class SequenceProtocol:
|
||||
"""
|
||||
Corresponds to the <Sequence> element inside <PythonExport>.
|
||||
All attributes are required booleans.
|
||||
"""
|
||||
|
||||
sq_length: bool = False
|
||||
sq_concat: bool = False
|
||||
sq_repeat: bool = False
|
||||
sq_item: bool = False
|
||||
mp_subscript: bool = False
|
||||
sq_ass_item: bool = False
|
||||
mp_ass_subscript: bool = False
|
||||
sq_contains: bool = False
|
||||
sq_inplace_concat: bool = False
|
||||
sq_inplace_repeat: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class PythonExport:
|
||||
"""
|
||||
Corresponds to <PythonExport> inside <GenerateModel>.
|
||||
It contains:
|
||||
- optional <Documentation>
|
||||
- 0..∞ <Methode>
|
||||
- 0..∞ <Attribute>
|
||||
- optional <Sequence>
|
||||
- optional <CustomAttributes>
|
||||
- one <ClassDeclarations> (type=string)
|
||||
- one <ForwardDeclarations> (type=string)
|
||||
Plus many attributes with required/optional flags.
|
||||
"""
|
||||
|
||||
Documentation: Optional[Documentation] = None
|
||||
Methode: List[Methode] = field(default_factory=list)
|
||||
Attribute: List[Attribute] = field(default_factory=list)
|
||||
Sequence: Optional[SequenceProtocol] = None
|
||||
CustomAttributes: Optional[str] = "" # To match the original XML model
|
||||
ClassDeclarations: str = ""
|
||||
ForwardDeclarations: str = ""
|
||||
NoArgs: bool = False
|
||||
|
||||
# Attributes
|
||||
ModuleName: str = ""
|
||||
Name: str = ""
|
||||
PythonName: Optional[str] = None
|
||||
Include: str = ""
|
||||
Father: str = ""
|
||||
Twin: str = ""
|
||||
Namespace: str = ""
|
||||
FatherInclude: str = ""
|
||||
FatherNamespace: str = ""
|
||||
Constructor: bool = False
|
||||
NumberProtocol: bool = False
|
||||
RichCompare: bool = False
|
||||
TwinPointer: str = ""
|
||||
Delete: bool = False
|
||||
Reference: Optional[bool] = None
|
||||
Initialization: bool = False
|
||||
DisableNotify: bool = False
|
||||
DescriptorGetter: bool = False
|
||||
DescriptorSetter: bool = False
|
||||
IsExplicitlyExported: bool = False
|
||||
|
||||
|
||||
#
|
||||
# Module-Related Classes
|
||||
#
|
||||
|
||||
|
||||
@dataclass
|
||||
class Dependencies:
|
||||
"""
|
||||
Corresponds to the <Dependencies> element inside <Module>.
|
||||
It contains 0..∞ local <Module> elements which are not typed in the XSD.
|
||||
We'll treat these as strings or possibly minimal structures.
|
||||
"""
|
||||
|
||||
Module: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Feature:
|
||||
"""
|
||||
Corresponds to <Feature> in <Module>'s <Content>.
|
||||
Has optional <Documentation>, 0..∞ <Property>, optional <ViewProvider>,
|
||||
and a required attribute 'Name'.
|
||||
"""
|
||||
|
||||
Documentation: Optional[Documentation] = None
|
||||
Property: List[Property] = field(default_factory=list)
|
||||
ViewProvider: Optional[ViewProvider] = None
|
||||
|
||||
# Attributes
|
||||
Name: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class DocObject:
|
||||
"""
|
||||
Corresponds to <DocObject> in <Module>'s <Content>.
|
||||
Has optional <Documentation>, 0..∞ <Property>, and a required 'Name' attribute.
|
||||
"""
|
||||
|
||||
Documentation: Optional[Documentation] = None
|
||||
Property: List[Property] = field(default_factory=list)
|
||||
|
||||
# Attributes
|
||||
Name: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class ModuleContent:
|
||||
"""
|
||||
Corresponds to the <Content> element in <Module>.
|
||||
Contains:
|
||||
- 0..∞ <Property>
|
||||
- 0..∞ <Feature>
|
||||
- 0..∞ <DocObject>
|
||||
- 0..∞ <GuiCommand>
|
||||
- 0..∞ <PreferencesPage>
|
||||
"""
|
||||
|
||||
Property: List[Property] = field(default_factory=list)
|
||||
Feature: List[Feature] = field(default_factory=list)
|
||||
DocObject: List[DocObject] = field(default_factory=list)
|
||||
GuiCommand: List[str] = field(default_factory=list)
|
||||
PreferencesPage: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Module:
|
||||
"""
|
||||
Corresponds to the top-level <Module> element.
|
||||
Has optional <Documentation>, optional <Dependencies>,
|
||||
a required <Content>, and a required attribute Name.
|
||||
"""
|
||||
|
||||
Documentation: Optional[Documentation] = None
|
||||
Dependencies: Optional[Dependencies] = None
|
||||
Content: ModuleContent = field(default_factory=ModuleContent)
|
||||
|
||||
# Attributes
|
||||
Name: str = ""
|
||||
|
||||
|
||||
#
|
||||
# Root Element
|
||||
#
|
||||
|
||||
|
||||
@dataclass
|
||||
class GenerateModel:
|
||||
"""
|
||||
Corresponds to the root element <GenerateModel>.
|
||||
Contains 0..∞ <Module> and 0..∞ <PythonExport>.
|
||||
"""
|
||||
|
||||
Module: List[Module] = field(default_factory=list)
|
||||
PythonExport: List[PythonExport] = field(default_factory=list)
|
||||
|
||||
def dump(self):
|
||||
# Print or process the resulting GenerateModel object
|
||||
print("Parsed GenerateModel object:")
|
||||
|
||||
if self.PythonExport:
|
||||
py_exp = self.PythonExport[0]
|
||||
print("PythonExport Name:", py_exp.Name)
|
||||
if py_exp.Documentation and py_exp.Documentation.Author:
|
||||
print("Author Name:", py_exp.Documentation.Author.Name)
|
||||
print("Author Email:", py_exp.Documentation.Author.EMail)
|
||||
print("Author Licence:", py_exp.Documentation.Author.Licence)
|
||||
print("DeveloperDocu:", py_exp.Documentation.DeveloperDocu)
|
||||
print("UserDocu:", py_exp.Documentation.UserDocu)
|
||||
|
||||
print("Class Attributes:")
|
||||
for attr in py_exp.Attribute:
|
||||
print(f" - {attr.Name} (type={attr.Parameter.Type}, readOnly={attr.ReadOnly})")
|
||||
|
||||
print("Methods:")
|
||||
for meth in py_exp.Methode:
|
||||
print(f" - {meth.Name}")
|
||||
# Each method might have parameters
|
||||
for param in meth.Parameter:
|
||||
print(f" * param: {param.Name}, type={param.Type}")
|
||||
457
src/Tools/bindings/readme.md
Normal file
457
src/Tools/bindings/readme.md
Normal file
@@ -0,0 +1,457 @@
|
||||
# FreeCAD C++ to Python Binding System Manual
|
||||
|
||||
Welcome to the new Python-based binding system for exposing FreeCAD C++ APIs to Python. This system replaces the previous XML-based approach with a more direct and flexible Python interface, allowing C++ developers to define Python bindings using native Python syntax, type annotations, and decorators.
|
||||
|
||||
* * *
|
||||
|
||||
## Table of Contents
|
||||
|
||||
* [Overview](#overview)
|
||||
* [Key Features](#key-features)
|
||||
* [Core Components](#core-components)
|
||||
* [Defining Bindings in Python](#defining-bindings-in-python)
|
||||
* [Metadata Decorators](#metadata-decorators)
|
||||
* [Class Definitions](#class-definitions)
|
||||
* [Method Overloading](#method-overloading)
|
||||
* [Attributes and Read-Only Properties](#attributes-and-read-only-properties)
|
||||
* [Example](#example)
|
||||
* [Getting Started](#getting-started)
|
||||
* [Advanced Topics](#advanced-topics)
|
||||
* [Conclusion](#conclusion)
|
||||
|
||||
* * *
|
||||
|
||||
## Overview
|
||||
|
||||
The new Python-based binding system allows you to create bindings between FreeCAD’s C++ APIs and Python directly within Python source files. By leveraging Python’s native features—such as type annotations, decorators, and overloads—you can produce well-documented, type-safe Python interfaces that closely mirror your C++ classes.
|
||||
|
||||
This system is designed to be fully compatible and backwards-compatible with the previous XML-based system but offers the following advantages:
|
||||
|
||||
* **Direct Python Syntax:** Write bindings directly in Python without an intermediary XML representation.
|
||||
* **Enhanced Readability:** Preserve detailed documentation and formatting in docstrings.
|
||||
* **Type Safety:** Use Python type hints to ensure that the Python interface accurately reflects the C++ API.
|
||||
* **Decorator-Based Metadata:** Attach metadata to classes and methods to control binding behavior.
|
||||
* **Method Overloads:** Define multiple method signatures using `@overload` for improved clarity and support of type hinting for Python overloads.
|
||||
* **Comprehensive Documentation:** Maintain detailed developer and user documentation directly in the Python stubs.
|
||||
|
||||
* * *
|
||||
|
||||
## Core Components
|
||||
|
||||
The binding system is built around a few core components:
|
||||
|
||||
* **Metadata Decorators:**
|
||||
A set of decorators (e.g., `@export`, `@constmethod`, `@sequence_protocol`) to annotate classes and methods with necessary metadata for the binding process. These decorators help bridge the gap between the C++ definitions and the Python interface.
|
||||
|
||||
* **C++ Python Stub Generation:**
|
||||
The system generates C++ Python stubs that act as a direct mapping to the corresponding C++ classes. These stubs include method signatures, attributes, and detailed docstrings and uses the same code
|
||||
as the previous XML-based system.
|
||||
|
||||
* **Type Annotations and Overloads:**
|
||||
Utilize Python's type hints and the `@overload` decorator from the `typing` module to accurately represent C++ method signatures, including support for overloaded methods.
|
||||
|
||||
* * *
|
||||
|
||||
## Defining Bindings in Python
|
||||
|
||||
### Metadata Decorators
|
||||
|
||||
The core decorator, `@export`, is used to attach binding-related metadata to a class. This metadata includes information such as the C++ class name, header files, namespaces, and more.
|
||||
|
||||
**Example:**
|
||||
|
||||
```python
|
||||
from Metadata import export, constmethod
|
||||
from PyObjectBase import PyObjectBase
|
||||
|
||||
@export(
|
||||
Father="PyObjectBase",
|
||||
Name="PrecisionPy",
|
||||
Twin="Precision",
|
||||
TwinPointer="Precision",
|
||||
Include="Base/Precision.h",
|
||||
Namespace="Base",
|
||||
FatherInclude="Base/PyObjectBase.h",
|
||||
FatherNamespace="Base",
|
||||
)
|
||||
class PrecisionPy(PyObjectBase):
|
||||
"""
|
||||
Base.Precision class.
|
||||
|
||||
This class provides precision values for various numerical operations
|
||||
in the FreeCAD environment.
|
||||
"""
|
||||
...
|
||||
```
|
||||
|
||||
### Class Definitions
|
||||
|
||||
Classes are defined in a way that closely mirrors the C++ counterparts. The Python classes use decorators to attach metadata and include docstrings that retain original formatting.
|
||||
|
||||
### Method Overloading
|
||||
|
||||
For methods that require multiple signatures (overloads), use the `@overload` decorator. A final implementation that handles variable arguments (`*args`, `**kwargs`) is provided as a placeholder.
|
||||
|
||||
**Example:**
|
||||
|
||||
```python
|
||||
from typing import overload
|
||||
|
||||
class QuantityPy(PyObjectBase):
|
||||
@overload
|
||||
def toStr(self) -> str: ...
|
||||
|
||||
@overload
|
||||
def toStr(self, decimals: int) -> str: ...
|
||||
|
||||
def toStr(self, decimals: int = ...) -> str:
|
||||
"""
|
||||
toStr([decimals])
|
||||
Returns a string representation of the quantity, rounded to the specified number of decimals.
|
||||
"""
|
||||
...
|
||||
```
|
||||
|
||||
The `@overload` variants are not actually used by the generator, but solely for the purpose of
|
||||
providing Python type hinting to be used by type checkers like mypy.
|
||||
|
||||
### Attributes and Read-Only Properties
|
||||
|
||||
Attributes defined as read-only are annotated with `Final` from Python’s `typing` module to indicate immutability.
|
||||
|
||||
**Example:**
|
||||
|
||||
```python
|
||||
from typing import Final, Tuple
|
||||
|
||||
class UnitPy(PyObjectBase):
|
||||
# holds the unit type as a string, e.g. 'Area'.
|
||||
Type: Final[str] = ...
|
||||
|
||||
# Returns the signature.
|
||||
Signature: Final[Tuple] = ...
|
||||
```
|
||||
|
||||
* * *
|
||||
|
||||
## Metadata Decorators Reference
|
||||
|
||||
This section details each metadata decorator and helper function used to attach auxiliary binding information to your Python classes and methods.
|
||||
|
||||
* * *
|
||||
|
||||
### 1. `metadata`
|
||||
|
||||
#### **Purpose**
|
||||
|
||||
The `metadata` decorator attaches a set of key-value pairs as metadata to a class. This metadata informs the binding generator about various aspects of the corresponding C++ API, such as its name, header file, namespace, inheritance, and twin (or native) types.
|
||||
|
||||
#### **Usage**
|
||||
|
||||
```python
|
||||
from Metadata import export
|
||||
|
||||
@export(
|
||||
Father="PyObjectBase",
|
||||
Name="PrecisionPy",
|
||||
Twin="Precision",
|
||||
TwinPointer="Precision",
|
||||
Include="Base/Precision.h",
|
||||
Namespace="Base",
|
||||
FatherInclude="Base/PyObjectBase.h",
|
||||
FatherNamespace="Base",
|
||||
)
|
||||
class PrecisionPy(PyObjectBase):
|
||||
"""
|
||||
Base.Precision class.
|
||||
|
||||
This class provides precision values for various numerical operations
|
||||
in the FreeCAD environment.
|
||||
"""
|
||||
# Class implementation goes here...
|
||||
```
|
||||
|
||||
#### **Parameters**
|
||||
|
||||
* **Arbitrary Keyword Arguments (`**kwargs`):**
|
||||
These may include:
|
||||
|
||||
* `Father`: The name of the parent class in Python.
|
||||
* `Name`: The name of the current Python binding C++ class.
|
||||
* `Twin`: The name of the corresponding C++ class.
|
||||
* `TwinPointer`: The pointer type of the twin C++ class.
|
||||
* `Include`: The header file where the C++ class is declared.
|
||||
* `Namespace`: The C++ namespace of the class.
|
||||
* `FatherInclude`: The header file for the parent class.
|
||||
* `FatherNamespace`: The C++ namespace for the parent class.
|
||||
|
||||
_(Additional keys can be added as required by the binding generator.)_
|
||||
|
||||
* * *
|
||||
|
||||
### 2. `constmethod`
|
||||
|
||||
#### **Purpose**
|
||||
|
||||
The `constmethod` decorator marks a method as a constant method. In C++ bindings, this means that the method does not modify the state of the object and should be treated as `const`. This can affect the generated C++ method signature and enforce read-only behavior in Python where applicable.
|
||||
|
||||
#### **Usage**
|
||||
|
||||
```python
|
||||
from Metadata import constmethod
|
||||
|
||||
class ExamplePy(PyObjectBase):
|
||||
|
||||
@constmethod()
|
||||
def getValue(self) -> int:
|
||||
"""
|
||||
Returns an integer value without modifying the object.
|
||||
"""
|
||||
# Actual implementation goes here...
|
||||
```
|
||||
|
||||
* * *
|
||||
|
||||
### 3. `no_args`
|
||||
|
||||
#### **Purpose**
|
||||
|
||||
The `no_args` decorator is used to indicate that a method should be called without any arguments. This is
|
||||
to signal that fact to the generator so it knows to generate the correct C++ API signature.
|
||||
|
||||
#### **Usage**
|
||||
|
||||
```python
|
||||
from Metadata import no_args
|
||||
|
||||
class ExamplePy(PyObjectBase):
|
||||
|
||||
@no_args()
|
||||
def reset(self) -> None:
|
||||
"""
|
||||
Resets the state of the object.
|
||||
"""
|
||||
# Implementation goes here...
|
||||
```
|
||||
|
||||
#### **Parameters**
|
||||
|
||||
* **None:**
|
||||
This decorator acts as a marker. It does not modify the method behavior at runtime but provides metadata to the binding generator.
|
||||
|
||||
#### **Behavior**
|
||||
|
||||
When the binding generator encounters the `no_args` decorator, it ensures that the generated Python stub does not expect any parameters beyond the implicit `self`, matching the no-argument signature of the underlying C++ method.
|
||||
|
||||
* * *
|
||||
|
||||
### 4. `forward_declarations`
|
||||
|
||||
#### **Purpose**
|
||||
|
||||
The `forward_declarations` decorator allows you to attach a snippet of source code containing forward declarations to a class. Forward declarations are useful when the binding process requires awareness of other classes or types before their full definitions are encountered.
|
||||
|
||||
#### **Usage**
|
||||
|
||||
```python
|
||||
from Metadata import forward_declarations
|
||||
|
||||
@forward_declarations("""
|
||||
class OtherType;
|
||||
struct HelperStruct;
|
||||
""")
|
||||
class ExamplePy(PyObjectBase):
|
||||
"""
|
||||
Example class that depends on OtherType and HelperStruct.
|
||||
"""
|
||||
# Class implementation goes here...
|
||||
```
|
||||
|
||||
#### **Parameters**
|
||||
|
||||
* **`source_code` (str):**
|
||||
A string containing the forward declarations in C++ syntax.
|
||||
|
||||
#### **Behavior**
|
||||
|
||||
This decorator attaches the provided forward declarations to the class (typically in a `__forward_declarations__` attribute). During stub generation or C++ header generation, these declarations are inserted at the appropriate location.
|
||||
|
||||
* * *
|
||||
|
||||
### 5. `class_declarations`
|
||||
|
||||
#### **Purpose**
|
||||
|
||||
The `class_declarations` decorator is similar to `forward_declarations` but is used for attaching additional class declarations. This may include extra helper classes, enums, or typedefs that are needed for the proper functioning of the bindings.
|
||||
|
||||
#### **Usage**
|
||||
|
||||
```python
|
||||
from Metadata import class_declarations
|
||||
|
||||
@class_declarations("""
|
||||
enum Status {
|
||||
SUCCESS,
|
||||
FAILURE
|
||||
};
|
||||
|
||||
typedef std::vector<int> IntVector;
|
||||
""")
|
||||
class ExamplePy(PyObjectBase):
|
||||
"""
|
||||
Example class with extra class declarations.
|
||||
"""
|
||||
# Class implementation goes here...
|
||||
```
|
||||
|
||||
#### **Parameters**
|
||||
|
||||
* **`source_code` (str):**
|
||||
A string containing extra class or type declarations that supplement the binding.
|
||||
|
||||
#### **Behavior**
|
||||
|
||||
The decorator stores the provided declarations in an attribute (e.g., `__class_declarations__`) so that the binding generator can include these in the final generated files.
|
||||
|
||||
* * *
|
||||
|
||||
### 6. `sequence_protocol`
|
||||
|
||||
#### **Purpose**
|
||||
|
||||
The `sequence_protocol` decorator is used to declare that a class implements Python’s sequence protocol. This includes support for operations like indexing, slicing, iteration, and length retrieval. By attaching protocol metadata, you can control how the binding system exposes these behaviors.
|
||||
|
||||
#### **Usage**
|
||||
|
||||
```python
|
||||
from Metadata import sequence_protocol
|
||||
|
||||
@sequence_protocol(
|
||||
sq_length=True,
|
||||
sq_concat=False,
|
||||
sq_repeat=False,
|
||||
sq_item=True,
|
||||
mp_subscript=True,
|
||||
sq_ass_item=True,
|
||||
mp_ass_subscript=False,
|
||||
sq_contains=False,
|
||||
sq_inplace_concat=False,
|
||||
sq_inplace_repeat=False,
|
||||
)
|
||||
class ContainerPy(PyObjectBase):
|
||||
"""
|
||||
A container class that implements Python's sequence protocol.
|
||||
"""
|
||||
...
|
||||
```
|
||||
|
||||
#### **Parameters**
|
||||
|
||||
* **Arbitrary Keyword Arguments (`**kwargs`):**
|
||||
* `sq_length` (bool): Whether the class supports element access via indexing.
|
||||
* `sq_concat` (bool): Whether the class is iterable.
|
||||
* `sq_repeat` (bool): Whether slicing operations are supported.
|
||||
* `sq_item` (bool): Whether the class supports element access via indexing.
|
||||
* `mp_subscript` (bool): Whether the class is iterable.
|
||||
* `sq_ass_item` (bool): Whether slicing operations are supported.
|
||||
* `sq_ass_item` (bool):
|
||||
* `mp_ass_subscript` (bool):
|
||||
* `sq_contains` (bool):
|
||||
* `sq_inplace_concat` (bool):
|
||||
* `sq_inplace_repeat` (bool):
|
||||
|
||||
#### **Behavior**
|
||||
|
||||
The decorator attaches a `__sequence_protocol__` attribute to the class with the provided dictionary. This metadata is later used to generate the appropriate sequence operations in the Python API stubs.
|
||||
|
||||
#### Sequence Protocol Callbacks
|
||||
|
||||
1. **`sq_length` → `static Py_ssize_t sequence_length(PyObject *)`**
|
||||
|
||||
* **Purpose:**
|
||||
Implements the “length” function for the object.
|
||||
* **Usage in Python:**
|
||||
When you call `len(obj)`, this function is invoked to determine how many items are in the sequence.
|
||||
* **C API Mapping:**
|
||||
This function fills the `sq_length` slot in the `PySequenceMethods` structure.
|
||||
2. **`sq_concat` → `static PyObject* sequence_concat(PyObject *, PyObject *)`**
|
||||
|
||||
* **Purpose:**
|
||||
Implements the concatenation operation for sequences.
|
||||
* **Usage in Python:**
|
||||
This is called when two sequence objects are added together using the `+` operator (e.g., `a + b`).
|
||||
* **C API Mapping:**
|
||||
This function is assigned to the `sq_concat` slot in `PySequenceMethods`.
|
||||
3. **`sq_repeat` → `static PyObject * sequence_repeat(PyObject *, Py_ssize_t)`**
|
||||
|
||||
* **Purpose:**
|
||||
Implements the repetition operation for sequences.
|
||||
* **Usage in Python:**
|
||||
It is invoked when a sequence is multiplied by an integer using the `*` operator (e.g., `a * n`), creating a new sequence with repeated elements.
|
||||
* **C API Mapping:**
|
||||
This function is installed in the `sq_repeat` slot of `PySequenceMethods`.
|
||||
4. **`sq_item` → `static PyObject * sequence_item(PyObject *, Py_ssize_t)`**
|
||||
|
||||
* **Purpose:**
|
||||
Implements element access via integer indexing.
|
||||
* **Usage in Python:**
|
||||
When you access an element using `obj[index]`, this function is called to retrieve the item.
|
||||
* **C API Mapping:**
|
||||
It fills the `sq_item` slot in `PySequenceMethods`.
|
||||
5. **`sq_ass_item` → `static int sequence_ass_item(PyObject *, Py_ssize_t, PyObject *)`**
|
||||
|
||||
* **Purpose:**
|
||||
Implements assignment (or deletion) of an element via an integer index.
|
||||
* **Usage in Python:**
|
||||
This function is used when an item is assigned (e.g., `obj[index] = value`) or deleted (`del obj[index]`).
|
||||
* **C API Mapping:**
|
||||
It is set into the `sq_ass_item` slot of the `PySequenceMethods` structure.
|
||||
6. **`sq_contains` → `static int sequence_contains(PyObject *, PyObject *)`**
|
||||
|
||||
* **Purpose:**
|
||||
Implements the membership test operation (the `in` operator).
|
||||
* **Usage in Python:**
|
||||
When evaluating `value in obj`, this function is used to determine if `value` is present in the sequence.
|
||||
* **C API Mapping:**
|
||||
This function populates the `sq_contains` slot in `PySequenceMethods`.
|
||||
7. **`sq_inplace_concat` → `static PyObject* sequence_inplace_concat(PyObject *, PyObject *)`**
|
||||
|
||||
* **Purpose:**
|
||||
Implements in-place concatenation of sequences.
|
||||
* **Usage in Python:**
|
||||
This is invoked when using the `+=` operator on sequences, modifying the sequence in place.
|
||||
* **C API Mapping:**
|
||||
It goes into the `sq_inplace_concat` slot of `PySequenceMethods`.
|
||||
8. **`sq_inplace_repeat` → `static PyObject * sequence_inplace_repeat(PyObject *, Py_ssize_t)`**
|
||||
|
||||
* **Purpose:**
|
||||
Implements in-place repetition of sequences.
|
||||
* **Usage in Python:**
|
||||
This function handles in-place multiplication (using `*=`) to repeat the sequence.
|
||||
* **C API Mapping:**
|
||||
It fills the `sq_inplace_repeat` slot in `PySequenceMethods`.
|
||||
|
||||
* * *
|
||||
|
||||
#### Mapping Protocol Callback
|
||||
|
||||
Although the code is primarily about the sequence protocol, it also provides functions for handling more general subscript operations via the mapping protocol:
|
||||
|
||||
1. **`mp_subscript` → `static PyObject * mapping_subscript(PyObject *, PyObject *)`**
|
||||
|
||||
* **Purpose:**
|
||||
Provides generalized subscript access.
|
||||
* **Usage in Python:**
|
||||
This function is used when the object is accessed with a subscript that is not necessarily an integer (for example, a slice or another key) using the `obj[key]` syntax.
|
||||
* **C API Mapping:**
|
||||
It fills the `mp_subscript` slot in the `PyMappingMethods` structure.
|
||||
2. **`mp_ass_subscript` → `static int mapping_ass_subscript(PyObject *, PyObject *, PyObject *)`**
|
||||
|
||||
* **Purpose:**
|
||||
Implements assignment (or deletion) via subscripting through the mapping protocol.
|
||||
* **Usage in Python:**
|
||||
When performing operations like `obj[key] = value` or `del obj[key]`, this function is called.
|
||||
* **C API Mapping:**
|
||||
This function is assigned to the `mp_ass_subscript` slot in the `PyMappingMethods` structure.
|
||||
|
||||
* * *
|
||||
9
src/Tools/bindings/templates/template.py
Normal file
9
src/Tools/bindings/templates/template.py
Normal file
@@ -0,0 +1,9 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2006 Juergen Riegel
|
||||
|
||||
|
||||
class ModelTemplate:
|
||||
def Generate(self):
|
||||
print("Generate() needs to be implemented in a Template class!")
|
||||
41
src/Tools/bindings/templates/templateCPPFile.py
Normal file
41
src/Tools/bindings/templates/templateCPPFile.py
Normal file
@@ -0,0 +1,41 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2006 Juergen Riegel
|
||||
|
||||
import template
|
||||
import model.generateModel_Module
|
||||
import model.generateTools
|
||||
|
||||
|
||||
class TemplateCPPFile(template.ModelTemplate):
|
||||
def Generate(self):
|
||||
model.generateTools.ensureDir(self.outputDir)
|
||||
print("Generate() App Dir")
|
||||
|
||||
|
||||
Template = """
|
||||
/***************************************************************************
|
||||
* Copyright (c) YEAR YOUR NAME <Your e-mail address> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library 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 library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
|
||||
"""
|
||||
1587
src/Tools/bindings/templates/templateClassPyExport.py
Normal file
1587
src/Tools/bindings/templates/templateClassPyExport.py
Normal file
File diff suppressed because it is too large
Load Diff
15
src/Tools/bindings/templates/templateModule.py
Normal file
15
src/Tools/bindings/templates/templateModule.py
Normal file
@@ -0,0 +1,15 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2006 Juergen Riegel
|
||||
|
||||
from . import template, templateModuleApp
|
||||
|
||||
|
||||
class TemplateModule(template.ModelTemplate):
|
||||
def Generate(self):
|
||||
print("model.generateModel_Module.Generate()\n")
|
||||
App = templateModuleApp.TemplateModuleApp()
|
||||
App.outputDir = self.outputDir
|
||||
App.module = self.module
|
||||
App.Generate()
|
||||
29
src/Tools/bindings/templates/templateModuleApp.py
Normal file
29
src/Tools/bindings/templates/templateModuleApp.py
Normal file
@@ -0,0 +1,29 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2007 Juergen Riegel
|
||||
|
||||
from . import template, templateModuleAppMain, templateModuleAppFeature
|
||||
import model.generateModel_Module
|
||||
import model.generateTools
|
||||
|
||||
|
||||
class TemplateModuleApp(template.ModelTemplate):
|
||||
def Generate(self):
|
||||
AppPath = self.outputDir + "/App/"
|
||||
model.generateTools.ensureDir(AppPath)
|
||||
|
||||
# the main module files
|
||||
AppMain = templateModuleAppMain.TemplateModuleAppMain()
|
||||
AppMain.outputDir = AppPath
|
||||
AppMain.module = self.module
|
||||
AppMain.Generate()
|
||||
|
||||
# Features
|
||||
model.generateTools.ensureDir(AppPath + "Features/")
|
||||
for i in self.module.Content.Feature:
|
||||
AppFeature = templateModuleAppFeature.TemplateFeature()
|
||||
AppFeature.outputDir = AppPath + "Features/"
|
||||
AppFeature.module = self.module
|
||||
AppFeature.feature = i
|
||||
AppFeature.Generate()
|
||||
88
src/Tools/bindings/templates/templateModuleAppFeature.py
Normal file
88
src/Tools/bindings/templates/templateModuleAppFeature.py
Normal file
@@ -0,0 +1,88 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2006 Juergen Riegel
|
||||
|
||||
from . import template
|
||||
import model.generateModel_Module
|
||||
import model.generateTools
|
||||
|
||||
|
||||
class TemplateFeature(template.ModelTemplate):
|
||||
def Generate(self):
|
||||
file = open(self.outputDir + self.feature.Name + "Imp.cpp", "w")
|
||||
model.generateTools.replace(self.TemplateImplement, locals(), file)
|
||||
file = open(self.outputDir + self.feature.Name + ".cpp", "w")
|
||||
model.generateTools.replace(self.TemplateModule, locals(), file)
|
||||
file = open(self.outputDir + self.feature.Name + ".h", "w")
|
||||
model.generateTools.replace(self.TemplateHeader, locals(), file)
|
||||
# file.write( model.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
|
||||
|
||||
#include <App/PropertyStandard.h>
|
||||
|
||||
#include <App/Feature.h>
|
||||
|
||||
namespace @self.module.Name@
|
||||
{
|
||||
|
||||
|
||||
class @self.feature.Name@ : public App::Feature
|
||||
{
|
||||
PROPERTY_HEADER(@self.module.Name@::@self.feature.Name@);
|
||||
|
||||
public:
|
||||
@self.feature.Name@();
|
||||
+ for i in self.feature.Property:
|
||||
@i.Type@ @i.Name@;
|
||||
-
|
||||
|
||||
/** @name Methods override feature */
|
||||
//@{
|
||||
/// Recalculate the feature
|
||||
virtual int execute(void);
|
||||
/// Return the type name of the ViewProvider
|
||||
virtual const char* getViewProviderName(void) const {
|
||||
return "@self.module.Name@Gui::ViewProviderBox";
|
||||
}
|
||||
//@}
|
||||
};
|
||||
|
||||
} //namespace @self.module.Name@
|
||||
|
||||
#endif // @self.module.Name.upper()@_FEATURE_@self.feature.Name.upper()@_H
|
||||
|
||||
"""
|
||||
TemplateModule = """
|
||||
|
||||
#include "@self.feature.Name@.h"
|
||||
|
||||
using namespace @self.module.Name@;
|
||||
|
||||
PROPERTY_SOURCE(@self.module.Name@::@self.feature.Name@, App::Feature)
|
||||
|
||||
@self.feature.Name@::@self.feature.Name@()
|
||||
{
|
||||
+ for i in self.feature.Property:
|
||||
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 = """
|
||||
//
|
||||
|
||||
#include "@self.feature.Name@.h"
|
||||
|
||||
using namespace @self.module.Name@;
|
||||
|
||||
// TODO This method implements the function of the feature
|
||||
int @self.feature.Name@::execute(void)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
"""
|
||||
53
src/Tools/bindings/templates/templateModuleAppMain.py
Normal file
53
src/Tools/bindings/templates/templateModuleAppMain.py
Normal file
@@ -0,0 +1,53 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2006 Juergen Riegel
|
||||
|
||||
from . import template
|
||||
import model.generateModel_Module
|
||||
import model.generateTools
|
||||
|
||||
|
||||
class TemplateModuleAppMain(template.ModelTemplate):
|
||||
def Generate(self):
|
||||
file = open(self.outputDir + "/App" + self.module.Name + ".cpp", "w")
|
||||
model.generateTools.replace(self.Template, locals(), file)
|
||||
# file.write( model.generateTools.replace(self.Template,locals()))
|
||||
|
||||
Template = """
|
||||
/***************************************************************************
|
||||
* This program is free software; you can redistribute it and/or modify *
|
||||
* it under the terms of the GNU Library General Public License 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. *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
# include <Python.h>
|
||||
|
||||
|
||||
#include <Base/Console.h>
|
||||
|
||||
+ for i in self.module.Content.Feature:
|
||||
#include "Feature/@i.Name@.h"
|
||||
-
|
||||
|
||||
extern struct PyMethodDef @self.module.Name@_methods[];
|
||||
|
||||
|
||||
extern "C" {
|
||||
void App@self.module.Name@Export init@self.module.Name@() {
|
||||
|
||||
Base::Console().log("Mod: Loading @self.module.Name@ module... done\\n");
|
||||
PyObject* partModule = Py_InitModule3("@self.module.Name@", @self.module.Name@_methods, module_@self.module.Name@_doc); /* mod name, table ptr */
|
||||
|
||||
+ for i in self.module.Content.Feature:
|
||||
@self.module.Name@::Feature@i.Name@::init();
|
||||
-
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
"""
|
||||
44
src/Tools/catfiles.py
Normal file
44
src/Tools/catfiles.py
Normal file
@@ -0,0 +1,44 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2018 Werner Mayer LGPL
|
||||
#
|
||||
|
||||
import sys, getopt
|
||||
|
||||
# import os # The code that needs this is commented out
|
||||
import shutil
|
||||
|
||||
|
||||
def main():
|
||||
outputfile = ""
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[1:], "o:", ["outputfile="])
|
||||
except getopt.GetoptError:
|
||||
pass
|
||||
|
||||
for o, a in opts:
|
||||
if o in ("-o", "--outputfile"):
|
||||
outputfile = a
|
||||
|
||||
# if os.path.exists(outputfile):
|
||||
# do_not_create = True
|
||||
# ts = os.path.getmtime(outputfile)
|
||||
# for f in args:
|
||||
# if os.path.getmtime(f) > ts:
|
||||
# do_not_create = False
|
||||
# break
|
||||
#
|
||||
# if do_not_create:
|
||||
# print ("Up-to-date file {0}".format(outputfile))
|
||||
# return
|
||||
|
||||
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))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
164
src/Tools/dir2qrc.py
Normal file
164
src/Tools/dir2qrc.py
Normal file
@@ -0,0 +1,164 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2007 Juergen Riegel GPL
|
||||
|
||||
Usage = """dir2qrc - merging all files in a directory in a qrc file
|
||||
|
||||
Usage:
|
||||
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
|
||||
Licence: GPL
|
||||
|
||||
Version:
|
||||
0.1
|
||||
"""
|
||||
|
||||
import os, sys, getopt
|
||||
from os.path import join
|
||||
|
||||
# Globals
|
||||
Verbose = False
|
||||
Automatic = False
|
||||
ExtraDist = False
|
||||
Dir = "."
|
||||
Output = "resources.qrc"
|
||||
|
||||
hhcHeader = """<RCC>
|
||||
<qresource%s>
|
||||
"""
|
||||
hhcFooter = """ </qresource>
|
||||
</RCC>
|
||||
"""
|
||||
|
||||
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/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/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
|
||||
|
||||
try:
|
||||
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)
|
||||
sys.exit(2)
|
||||
|
||||
# checking on the options
|
||||
for o, a in opts:
|
||||
if o == "-v":
|
||||
Verbose = True
|
||||
if o in ("-h", "--help"):
|
||||
sys.stderr.write(Usage)
|
||||
sys.exit()
|
||||
if o in ("-a", "--auto"):
|
||||
Automatic = True
|
||||
if o in ("--dist"):
|
||||
ExtraDist = True
|
||||
if o in ("-o", "--out-file"):
|
||||
Output = a
|
||||
if o in ("-d", "--directory"):
|
||||
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]))
|
||||
if len(i) > 2:
|
||||
updateResourceFile(qrcDir, i[1], i[2])
|
||||
else:
|
||||
updateResourceFile(qrcDir, i[1])
|
||||
if ExtraDist:
|
||||
makeTargetExtraDist(qrcDir)
|
||||
else:
|
||||
updateResourceFile(Dir, Output)
|
||||
if ExtraDist:
|
||||
makeTargetExtraDist(Dir)
|
||||
|
||||
|
||||
def updateResourceFile(Dir, Output, prefix=""):
|
||||
global Verbose
|
||||
Output = join(Dir, Output)
|
||||
file = open(Output, "w")
|
||||
file.write(hhcHeader % (prefix))
|
||||
DirPath = Dir + os.path.sep
|
||||
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)
|
||||
filelist.append(FilePath)
|
||||
|
||||
filelist.sort()
|
||||
for i in filelist:
|
||||
file.write(" <file>" + i + "</file>\n")
|
||||
|
||||
file.write(hhcFooter)
|
||||
file.close()
|
||||
|
||||
|
||||
def makeTargetExtraDist(Dir):
|
||||
extensions = EndingList[:]
|
||||
extensions.append(".qrc")
|
||||
extensions.append(".bat")
|
||||
extensions.append(".ts")
|
||||
print("EXTRA_DIST = \\")
|
||||
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("\\", "/")
|
||||
print("\t\t%s \\" % (FilePath))
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
73
src/Tools/doctools.py
Normal file
73
src/Tools/doctools.py
Normal file
@@ -0,0 +1,73 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2010 Werner Mayer LGPL
|
||||
# FreeCAD Python script to work with the FCStd file format.
|
||||
|
||||
import os
|
||||
from defusedxml import sax as defused_sax
|
||||
from xml.sax.handler import ContentHandler
|
||||
import zipfile
|
||||
|
||||
|
||||
# SAX handler to parse the Document.xml
|
||||
class DocumentHandler(ContentHandler):
|
||||
def __init__(self, dirname):
|
||||
super().__init__()
|
||||
self.files = []
|
||||
self.dirname = dirname
|
||||
|
||||
def startElement(self, name, attributes):
|
||||
item = attributes.get("file")
|
||||
if item is not None:
|
||||
self.files.append(os.path.join(self.dirname, str(item)))
|
||||
|
||||
def characters(self, data):
|
||||
return
|
||||
|
||||
def endElement(self, name):
|
||||
return
|
||||
|
||||
|
||||
def extractDocument(filename, outpath):
|
||||
zfile = zipfile.ZipFile(filename)
|
||||
files = zfile.namelist()
|
||||
|
||||
for i in files:
|
||||
data = zfile.read(i)
|
||||
dirs = i.split("/")
|
||||
if len(dirs) > 1:
|
||||
dirs.pop()
|
||||
curpath = outpath
|
||||
for j in dirs:
|
||||
curpath = curpath + "/" + j
|
||||
os.mkdir(curpath)
|
||||
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)
|
||||
for i in files:
|
||||
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 = defused_sax.make_parser()
|
||||
parser.setContentHandler(handler)
|
||||
parser.parse(filename)
|
||||
|
||||
files = []
|
||||
files.append(filename)
|
||||
files.extend(iter(handler.files))
|
||||
dirname = os.path.join(dirname, "GuiDocument.xml")
|
||||
if os.path.exists(dirname):
|
||||
files.append(dirname)
|
||||
return files
|
||||
60
src/Tools/embedded/PySide/mainwindow.py
Normal file
60
src/Tools/embedded/PySide/mainwindow.py
Normal file
@@ -0,0 +1,60 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
import sys
|
||||
|
||||
# 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):
|
||||
super(MainWindow, self).__init__(parent)
|
||||
from PySide import QtNetwork
|
||||
|
||||
QtNetwork.QNetworkConfigurationManager()
|
||||
|
||||
def showEvent(self, event):
|
||||
FreeCADGui.showMainWindow()
|
||||
self.setCentralWidget(FreeCADGui.getMainWindow())
|
||||
|
||||
# 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")
|
||||
|
||||
@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()
|
||||
ui.setupUi(mw)
|
||||
ui.actionEmbed.setVisible(False)
|
||||
mw.resize(1200, 800)
|
||||
mw.show()
|
||||
app.exec_()
|
||||
55
src/Tools/embedded/PySide/mainwindow.ui
Normal file
55
src/Tools/embedded/PySide/mainwindow.ui
Normal file
@@ -0,0 +1,55 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ui version="4.0">
|
||||
<class>MainWindow</class>
|
||||
<widget class="QMainWindow" name="MainWindow">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>800</width>
|
||||
<height>600</height>
|
||||
</rect>
|
||||
</property>
|
||||
<property name="windowTitle">
|
||||
<string>MainWindow</string>
|
||||
</property>
|
||||
<widget class="QWidget" name="centralwidget"/>
|
||||
<widget class="QMenuBar" name="menubar">
|
||||
<property name="geometry">
|
||||
<rect>
|
||||
<x>0</x>
|
||||
<y>0</y>
|
||||
<width>800</width>
|
||||
<height>25</height>
|
||||
</rect>
|
||||
</property>
|
||||
<widget class="QMenu" name="menuFreeCAD">
|
||||
<property name="title">
|
||||
<string>FreeCAD</string>
|
||||
</property>
|
||||
<addaction name="actionEmbed"/>
|
||||
<addaction name="actionDocument"/>
|
||||
<addaction name="actionCube"/>
|
||||
</widget>
|
||||
<addaction name="menuFreeCAD"/>
|
||||
</widget>
|
||||
<widget class="QStatusBar" name="statusbar"/>
|
||||
<action name="actionEmbed">
|
||||
<property name="text">
|
||||
<string>Embed</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="actionDocument">
|
||||
<property name="text">
|
||||
<string>Document</string>
|
||||
</property>
|
||||
</action>
|
||||
<action name="actionCube">
|
||||
<property name="text">
|
||||
<string>Cube</string>
|
||||
</property>
|
||||
</action>
|
||||
</widget>
|
||||
<resources/>
|
||||
<connections/>
|
||||
</ui>
|
||||
42
src/Tools/embedded/PySide/mainwindow2.py
Normal file
42
src/Tools/embedded/PySide/mainwindow2.py
Normal file
@@ -0,0 +1,42 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
import sys
|
||||
|
||||
# sys.path.append("")
|
||||
|
||||
from PySide import QtGui
|
||||
import FreeCADGui
|
||||
|
||||
|
||||
class MainWindow(QtGui.QMainWindow):
|
||||
def __init__(self, parent=None):
|
||||
super(MainWindow, self).__init__(parent)
|
||||
from PySide import QtNetwork
|
||||
|
||||
QtNetwork.QNetworkConfigurationManager()
|
||||
|
||||
def showEvent(self, event):
|
||||
FreeCADGui.showMainWindow()
|
||||
self.setCentralWidget(FreeCADGui.getMainWindow())
|
||||
|
||||
# Need version >= 0.16.5949
|
||||
class BlankWorkbench(FreeCADGui.Workbench):
|
||||
MenuText = "Blank"
|
||||
ToolTip = "Blank workbench"
|
||||
|
||||
def Initialize(self):
|
||||
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)
|
||||
mw.show()
|
||||
app.exec_()
|
||||
62
src/Tools/embedded/PySide/mainwindow3.py
Normal file
62
src/Tools/embedded/PySide/mainwindow3.py
Normal file
@@ -0,0 +1,62 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
import sys
|
||||
|
||||
# sys.path.append("")
|
||||
|
||||
from PySide import QtCore, QtGui
|
||||
import FreeCAD, FreeCADGui
|
||||
import ctypes
|
||||
|
||||
from ui_mainwindow import Ui_MainWindow
|
||||
|
||||
|
||||
class MainWindow(QtGui.QMainWindow):
|
||||
def __init__(self, parent=None):
|
||||
super(MainWindow, self).__init__(parent)
|
||||
from PySide import QtNetwork
|
||||
|
||||
QtNetwork.QNetworkConfigurationManager()
|
||||
|
||||
@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)
|
||||
)
|
||||
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")
|
||||
|
||||
@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()
|
||||
ui.setupUi(mw)
|
||||
mw.resize(1200, 800)
|
||||
mw.show()
|
||||
app.exec_()
|
||||
30
src/Tools/embedded/PySide/minimal.py
Normal file
30
src/Tools/embedded/PySide/minimal.py
Normal file
@@ -0,0 +1,30 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
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.show()
|
||||
|
||||
# must be done a few times to update the GUI
|
||||
app.processEvents()
|
||||
app.processEvents()
|
||||
app.processEvents()
|
||||
|
||||
import Part
|
||||
|
||||
cube = Part.makeBox(2, 2, 2)
|
||||
# creates a document and a Part feature with the cube
|
||||
Part.show(cube)
|
||||
app.processEvents()
|
||||
app.processEvents()
|
||||
66
src/Tools/embedded/PySide/ui_mainwindow.py
Normal file
66
src/Tools/embedded/PySide/ui_mainwindow.py
Normal file
@@ -0,0 +1,66 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# Form implementation generated from reading ui file 'mainwindow.ui'
|
||||
#
|
||||
# Created: Fri Nov 20 18:03:04 2015
|
||||
# by: pyside-uic 0.2.13 running on PySide 1.1.0
|
||||
#
|
||||
# WARNING! All changes made in this file will be lost!
|
||||
|
||||
from PySide import QtCore, QtGui
|
||||
|
||||
|
||||
class Ui_MainWindow(object):
|
||||
def setupUi(self, MainWindow):
|
||||
MainWindow.setObjectName("MainWindow")
|
||||
MainWindow.resize(800, 600)
|
||||
self.centralwidget = QtGui.QWidget(MainWindow)
|
||||
self.centralwidget.setObjectName("centralwidget")
|
||||
MainWindow.setCentralWidget(self.centralwidget)
|
||||
self.menubar = QtGui.QMenuBar(MainWindow)
|
||||
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 25))
|
||||
self.menubar.setObjectName("menubar")
|
||||
self.menuFreeCAD = QtGui.QMenu(self.menubar)
|
||||
self.menuFreeCAD.setObjectName("menuFreeCAD")
|
||||
MainWindow.setMenuBar(self.menubar)
|
||||
self.statusbar = QtGui.QStatusBar(MainWindow)
|
||||
self.statusbar.setObjectName("statusbar")
|
||||
MainWindow.setStatusBar(self.statusbar)
|
||||
self.actionEmbed = QtGui.QAction(MainWindow)
|
||||
self.actionEmbed.setObjectName("actionEmbed")
|
||||
self.actionDocument = QtGui.QAction(MainWindow)
|
||||
self.actionDocument.setObjectName("actionDocument")
|
||||
self.actionCube = QtGui.QAction(MainWindow)
|
||||
self.actionCube.setObjectName("actionCube")
|
||||
self.menuFreeCAD.addAction(self.actionEmbed)
|
||||
self.menuFreeCAD.addAction(self.actionDocument)
|
||||
self.menuFreeCAD.addAction(self.actionCube)
|
||||
self.menubar.addAction(self.menuFreeCAD.menuAction())
|
||||
|
||||
self.retranslateUi(MainWindow)
|
||||
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)
|
||||
)
|
||||
27
src/Tools/embedded/Qt/Qt.pro
Normal file
27
src/Tools/embedded/Qt/Qt.pro
Normal file
@@ -0,0 +1,27 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
TEMPLATE = app
|
||||
TARGET = Qt
|
||||
INCLUDEPATH += .
|
||||
|
||||
linux {
|
||||
INCLUDEPATH += /usr/include/python3.6
|
||||
LIBS += -lpython3.6m
|
||||
}
|
||||
|
||||
QT += widgets
|
||||
|
||||
# The following define makes your compiler warn you if you use any
|
||||
# feature of Qt which has been marked as deprecated (the exact warnings
|
||||
# depend on your compiler). Please consult the documentation of the
|
||||
# deprecated API in order to know how to port your code away from it.
|
||||
DEFINES += QT_DEPRECATED_WARNINGS
|
||||
|
||||
# You can also make your code fail to compile if you use deprecated APIs.
|
||||
# In order to do so, uncomment the following line.
|
||||
# You can also select to disable deprecated APIs only up to a certain version of Qt.
|
||||
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
|
||||
|
||||
# Input
|
||||
HEADERS += mainwindow.h
|
||||
SOURCES += main.cpp mainwindow.cpp
|
||||
114
src/Tools/embedded/Qt/cxx/CMakeLists.txt
Normal file
114
src/Tools/embedded/Qt/cxx/CMakeLists.txt
Normal file
@@ -0,0 +1,114 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
project(MyPlugin)
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
|
||||
# Qt5
|
||||
find_package(Qt5Widgets REQUIRED)
|
||||
find_package(Qt5Gui REQUIRED)
|
||||
|
||||
# Boost
|
||||
find_package(Boost COMPONENTS signals REQUIRED)
|
||||
|
||||
# Coin3d
|
||||
#find_package(Coin3D REQUIRED)
|
||||
|
||||
# Python
|
||||
find_package(PythonInterp REQUIRED)
|
||||
set(Python_ADDITIONAL_VERSIONS ${Python3_VERSION_MAJOR}.${Python3_VERSION_MINOR})
|
||||
IF (NOT DEFINED Python3_VERSION)
|
||||
find_package(PythonLibs REQUIRED)
|
||||
ELSE (NOT DEFINED Python3_VERSION)
|
||||
find_package(PythonLibs ${Python3_VERSION} EXACT)
|
||||
ENDIF(NOT DEFINED Python3_VERSION)
|
||||
|
||||
# FreeCAD
|
||||
set(FREECAD_SRC_DIR ${CMAKE_SOURCE_DIR}/../../../.. CACHE PATH "FreeCAD sources")
|
||||
set(FREECAD_BIN_DIR ${CMAKE_SOURCE_DIR}/../../../.. CACHE PATH "FreeCAD binaries")
|
||||
set(FREECAD_LIBPACK_DIR ${CMAKE_SOURCE_DIR} CACHE PATH "Directory of the FreeCAD LibPack")
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
add_definitions(-DBOOST_ALL_DYN_LINK)
|
||||
|
||||
include_directories(
|
||||
${FREECAD_SRC_DIR}
|
||||
)
|
||||
|
||||
include_directories(
|
||||
SYSTEM
|
||||
${FastSignals_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
#${COIN3D_INCLUDE_DIRS}
|
||||
${PYCXX_INCLUDE_DIR}
|
||||
${Python3_INCLUDE_DIRS}
|
||||
${Qt5Core_INCLUDE_DIRS}
|
||||
${Qt5Gui_INCLUDE_DIRS}
|
||||
${Qt5Widgets_INCLUDE_DIRS}
|
||||
"${FREECAD_LIBPACK_DIR}/include"
|
||||
)
|
||||
|
||||
link_directories(${FREECAD_LIBPACK_DIR}/lib)
|
||||
link_directories(${FREECAD_BIN_DIR})
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
set(MyPlugin_SRCS
|
||||
main.cpp
|
||||
)
|
||||
|
||||
set(MyPlugin_LIBS
|
||||
${Boost_LIBRARIES}
|
||||
#${COIN3D_LIBRARIES}
|
||||
${Python3_LIBRARIES}
|
||||
${Qt5Core_LIBRARIES}
|
||||
${Qt5Gui_LIBRARIES}
|
||||
${Qt5Widgets_LIBRARIES}
|
||||
)
|
||||
|
||||
add_executable(MyPlugin WIN32 ${MyPlugin_SRCS})
|
||||
target_link_libraries(MyPlugin ${MyPlugin_LIBS})
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
set(FreeCADPlugin_SRCS
|
||||
plugin.cpp
|
||||
)
|
||||
|
||||
set(FreeCADPlugin_LIBS
|
||||
${Boost_LIBRARIES}
|
||||
#${COIN3D_LIBRARIES}
|
||||
${Python3_LIBRARIES}
|
||||
${Qt5Core_LIBRARIES}
|
||||
${Qt5Gui_LIBRARIES}
|
||||
${Qt5Widgets_LIBRARIES}
|
||||
)
|
||||
|
||||
if (MSVC)
|
||||
set(FreeCADPlugin_LIBS
|
||||
${FreeCADPlugin_LIBS}
|
||||
debug FreeCADApp_d
|
||||
debug FreeCADBase_d
|
||||
debug FreeCADGui_d
|
||||
#debug Mesh_d
|
||||
optimized FreeCADApp
|
||||
optimized FreeCADBase
|
||||
optimized FreeCADGui
|
||||
#optimized Mesh
|
||||
)
|
||||
else()
|
||||
set(FreeCADPlugin_LIBS
|
||||
${FreeCADPlugin_LIBS}
|
||||
FreeCADApp
|
||||
FreeCADBase
|
||||
FreeCADGui
|
||||
#Mesh
|
||||
)
|
||||
endif()
|
||||
|
||||
add_library(FreeCADPlugin SHARED ${FreeCADPlugin_SRCS})
|
||||
target_link_libraries(FreeCADPlugin ${FreeCADPlugin_LIBS})
|
||||
|
||||
if (MSVC)
|
||||
target_compile_options(FreeCADPlugin PRIVATE /wd4251)
|
||||
endif()
|
||||
16
src/Tools/embedded/Qt/cxx/PreCompiled.h
Normal file
16
src/Tools/embedded/Qt/cxx/PreCompiled.h
Normal file
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#pragma once
|
||||
|
||||
#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
|
||||
#endif
|
||||
49
src/Tools/embedded/Qt/cxx/main.cpp
Normal file
49
src/Tools/embedded/Qt/cxx/main.cpp
Normal file
@@ -0,0 +1,49 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <QApplication>
|
||||
#include <QDialog>
|
||||
#include <QFileDialog>
|
||||
#include <QLibrary>
|
||||
#include <QPushButton>
|
||||
|
||||
QLibrary* freecadPlugin = nullptr;
|
||||
|
||||
void loadFreeCAD()
|
||||
{
|
||||
if (!freecadPlugin) {
|
||||
freecadPlugin = new QLibrary("FreeCADPlugin", qApp);
|
||||
}
|
||||
|
||||
if (!freecadPlugin->isLoaded()) {
|
||||
if (freecadPlugin->load()) {
|
||||
QFunctionPointer ptr = freecadPlugin->resolve("FreeCAD_init");
|
||||
if (ptr) {
|
||||
ptr();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Load a test file
|
||||
if (freecadPlugin->isLoaded()) {
|
||||
typedef void (*TestFunction)(const char*);
|
||||
TestFunction test = (TestFunction)freecadPlugin->resolve("FreeCAD_test");
|
||||
if (test) {
|
||||
QString file = QFileDialog::getOpenFileName();
|
||||
if (!file.isEmpty()) {
|
||||
test(file.toUtf8());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
QApplication app(argc, argv);
|
||||
QDialog dlg;
|
||||
QPushButton* button = new QPushButton(&dlg);
|
||||
button->setGeometry(QRect(140, 110, 90, 23));
|
||||
button->setText("Load FreeCAD");
|
||||
QObject::connect(button, &QPushButton::clicked, &loadFreeCAD);
|
||||
dlg.show();
|
||||
return app.exec();
|
||||
}
|
||||
51
src/Tools/embedded/Qt/cxx/plugin.cpp
Normal file
51
src/Tools/embedded/Qt/cxx/plugin.cpp
Normal file
@@ -0,0 +1,51 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <QApplication>
|
||||
#include <QMainWindow>
|
||||
#include <QMessageBox>
|
||||
#include <QVector>
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <Base/Factory.h>
|
||||
#include <Base/Interpreter.h>
|
||||
#include <Gui/Application.h>
|
||||
#include <Gui/MainWindow.h>
|
||||
|
||||
|
||||
PyMODINIT_FUNC FreeCAD_init()
|
||||
{
|
||||
static QVector<char*> argv;
|
||||
#if defined(_DEBUG)
|
||||
argv << "FreeCADApp_d.dll" << 0;
|
||||
#else
|
||||
argv << "FreeCADApp.dll" << 0;
|
||||
#endif
|
||||
|
||||
App::Application::Config()["RunMode"] = "Gui";
|
||||
App::Application::Config()["Console"] = "0";
|
||||
App::Application::Config()["ExeVendor"] = "FreeCAD";
|
||||
App::Application::Config()["SplashScreen"] = "freecadsplash";
|
||||
|
||||
App::Application::init(1, argv.data());
|
||||
Gui::Application::initApplication();
|
||||
Gui::Application* app = new Gui::Application(true);
|
||||
|
||||
Gui::MainWindow* mw = new Gui::MainWindow(qApp->activeWindow());
|
||||
mw->show();
|
||||
|
||||
app->initOpenInventor();
|
||||
app->runInitGuiScript();
|
||||
}
|
||||
|
||||
/* 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
|
||||
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) {
|
||||
QMessageBox::warning(0, "Exception", e.what());
|
||||
}
|
||||
}
|
||||
26
src/Tools/embedded/Qt/main.cpp
Normal file
26
src/Tools/embedded/Qt/main.cpp
Normal file
@@ -0,0 +1,26 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <Python.h>
|
||||
#include <QApplication>
|
||||
|
||||
#include "mainwindow.h"
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
const char* name = "Qt example";
|
||||
Py_SetProgramName(Py_DecodeLocale(name, NULL));
|
||||
Py_Initialize();
|
||||
|
||||
size_t size = argc;
|
||||
wchar_t** _argv = new wchar_t*[size];
|
||||
for (int i = 0; i < argc; i++) {
|
||||
_argv[i] = Py_DecodeLocale(argv[i], NULL);
|
||||
}
|
||||
PySys_SetArgv(argc, _argv);
|
||||
|
||||
QApplication app(argc, argv);
|
||||
MainWindow mainWin;
|
||||
mainWin.resize(600, 400);
|
||||
mainWin.show();
|
||||
return app.exec();
|
||||
}
|
||||
181
src/Tools/embedded/Qt/mainwindow.cpp
Normal file
181
src/Tools/embedded/Qt/mainwindow.cpp
Normal file
@@ -0,0 +1,181 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <Python.h>
|
||||
#include <QtGui>
|
||||
#include <QtWidgets>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#if defined(Q_WS_X11)
|
||||
# include <QX11EmbedContainer>
|
||||
#endif
|
||||
|
||||
#include "mainwindow.h"
|
||||
|
||||
MainWindow::MainWindow()
|
||||
{
|
||||
createActions();
|
||||
createMenus();
|
||||
#if defined(Q_WS_X11)
|
||||
setCentralWidget(new QX11EmbedContainer(this));
|
||||
#else
|
||||
setCentralWidget(new QWidget(this));
|
||||
#endif
|
||||
}
|
||||
|
||||
void MainWindow::createActions()
|
||||
{
|
||||
loadAct = new QAction(tr("&Load"), this);
|
||||
loadAct->setStatusTip(tr("Load FreeCAD module"));
|
||||
connect(loadAct, SIGNAL(triggered()), this, SLOT(loadFreeCAD()));
|
||||
|
||||
newAct = new QAction(tr("New document"), this);
|
||||
newAct->setStatusTip(tr("Create new document in the FreeCAD module"));
|
||||
connect(newAct, SIGNAL(triggered()), this, SLOT(newDocument()));
|
||||
newAct->setDisabled(true);
|
||||
|
||||
embedAct = new QAction(tr("Embed"), this);
|
||||
embedAct->setStatusTip(tr("Embed FreeCAD as child window"));
|
||||
connect(embedAct, SIGNAL(triggered()), this, SLOT(embedWindow()));
|
||||
embedAct->setDisabled(true);
|
||||
|
||||
exitAct = new QAction(tr("E&xit"), this);
|
||||
exitAct->setShortcut(tr("Ctrl+Q"));
|
||||
exitAct->setStatusTip(tr("Exit the application"));
|
||||
connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
|
||||
|
||||
aboutAct = new QAction(tr("&About"), this);
|
||||
aboutAct->setStatusTip(tr("Show the application's About box"));
|
||||
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
|
||||
}
|
||||
|
||||
void MainWindow::createMenus()
|
||||
{
|
||||
fileMenu = menuBar()->addMenu(tr("&File"));
|
||||
fileMenu->addAction(exitAct);
|
||||
|
||||
editMenu = menuBar()->addMenu(tr("Free&CAD"));
|
||||
editMenu->addAction(loadAct);
|
||||
editMenu->addAction(newAct);
|
||||
editMenu->addAction(embedAct);
|
||||
|
||||
menuBar()->addSeparator();
|
||||
|
||||
helpMenu = menuBar()->addMenu(tr("&Help"));
|
||||
helpMenu->addAction(aboutAct);
|
||||
}
|
||||
|
||||
void MainWindow::loadFreeCAD()
|
||||
{
|
||||
QString path = QFileDialog::getExistingDirectory(this, "FreeCAD module path");
|
||||
if (!path.isEmpty()) {
|
||||
path.replace('\\', '/');
|
||||
PyObject* main = PyImport_AddModule("__main__");
|
||||
PyObject* dict = PyModule_GetDict(main);
|
||||
std::stringstream cmd;
|
||||
cmd << "import sys,os\n"
|
||||
<< "sys.path.append(\"" << (const char*)path.toLatin1() << "\")\n"
|
||||
<< "os.chdir(\"" << (const char*)path.toLatin1() << "\")\n"
|
||||
<< "import FreeCADGui\n"
|
||||
<< "FreeCADGui.showMainWindow()\n";
|
||||
|
||||
PyObject* result = PyRun_String(cmd.str().c_str(), Py_file_input, dict, dict);
|
||||
if (result) {
|
||||
Py_DECREF(result);
|
||||
loadAct->setDisabled(true);
|
||||
newAct->setEnabled(true);
|
||||
embedAct->setEnabled(true);
|
||||
}
|
||||
else {
|
||||
PyObject *ptype, *pvalue, *ptrace;
|
||||
PyErr_Fetch(&ptype, &pvalue, &ptrace);
|
||||
PyObject* pystring = PyObject_Str(pvalue);
|
||||
const char* error = PyUnicode_AsUTF8(pystring);
|
||||
QMessageBox::warning(this, "Error", error);
|
||||
Py_DECREF(pystring);
|
||||
}
|
||||
Py_DECREF(dict);
|
||||
}
|
||||
}
|
||||
|
||||
void MainWindow::newDocument()
|
||||
{
|
||||
PyObject* main = PyImport_AddModule("__main__");
|
||||
PyObject* dict = PyModule_GetDict(main);
|
||||
const char* cmd = "FreeCAD.newDocument()\n";
|
||||
|
||||
PyObject* result = PyRun_String(cmd, Py_file_input, dict, dict);
|
||||
if (result) {
|
||||
Py_DECREF(result);
|
||||
}
|
||||
else {
|
||||
PyObject *ptype, *pvalue, *ptrace;
|
||||
PyErr_Fetch(&ptype, &pvalue, &ptrace);
|
||||
PyObject* pystring = PyObject_Str(pvalue);
|
||||
const char* error = PyUnicode_AsUTF8(pystring);
|
||||
QMessageBox::warning(this, "Error", error);
|
||||
Py_DECREF(pystring);
|
||||
}
|
||||
Py_DECREF(dict);
|
||||
}
|
||||
|
||||
void MainWindow::embedWindow()
|
||||
{
|
||||
PyObject* main = PyImport_AddModule("__main__");
|
||||
PyObject* dict = PyModule_GetDict(main);
|
||||
std::stringstream cmd;
|
||||
cmd << "class BlankWorkbench (Workbench):\n"
|
||||
<< " MenuText = \"Blank\"\n"
|
||||
<< " ToolTip = \"Blank workbench\"\n"
|
||||
<< "\n"
|
||||
<< " def Initialize(self):\n"
|
||||
<< " return\n"
|
||||
<< " def GetClassName(self):\n"
|
||||
<< " return \"Gui::BlankWorkbench\"\n"
|
||||
<< "\n"
|
||||
<< "FreeCADGui.addWorkbench(BlankWorkbench)\n"
|
||||
<< "FreeCADGui.activateWorkbench(\"BlankWorkbench\")\n"
|
||||
<< "\n";
|
||||
|
||||
#if defined(Q_WS_X11) || defined(Q_OS_WIN)
|
||||
WId hwnd = this->centralWidget()->winId();
|
||||
cmd << "FreeCADGui.embedToWindow(\"" << hwnd << "\")\n"
|
||||
<< "\n";
|
||||
#endif
|
||||
|
||||
PyObject* result = PyRun_String(cmd.str().c_str(), Py_file_input, dict, dict);
|
||||
if (result) {
|
||||
Py_DECREF(result);
|
||||
|
||||
#if !defined(Q_WS_X11)
|
||||
// This is a workaround for the lack of a replacement of QX11EmbedWidget with Qt5
|
||||
QWidget* mw = nullptr;
|
||||
for (auto it : qApp->topLevelWidgets()) {
|
||||
if (it->inherits("Gui::MainWindow")) {
|
||||
mw = it;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (mw) {
|
||||
QVBoxLayout* vb = new QVBoxLayout();
|
||||
centralWidget()->setLayout(vb);
|
||||
vb->addWidget(mw);
|
||||
}
|
||||
#endif
|
||||
|
||||
embedAct->setDisabled(true);
|
||||
}
|
||||
else {
|
||||
PyObject *ptype, *pvalue, *ptrace;
|
||||
PyErr_Fetch(&ptype, &pvalue, &ptrace);
|
||||
PyObject* pystring = PyObject_Str(pvalue);
|
||||
const char* error = PyUnicode_AsUTF8(pystring);
|
||||
QMessageBox::warning(this, "Error", error);
|
||||
Py_DECREF(pystring);
|
||||
}
|
||||
Py_DECREF(dict);
|
||||
}
|
||||
|
||||
void MainWindow::about()
|
||||
{
|
||||
QMessageBox::about(this, tr("About"), tr("Demonstrates remote control of FreeCAD"));
|
||||
}
|
||||
38
src/Tools/embedded/Qt/mainwindow.h
Normal file
38
src/Tools/embedded/Qt/mainwindow.h
Normal file
@@ -0,0 +1,38 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <QMainWindow>
|
||||
|
||||
QT_BEGIN_NAMESPACE
|
||||
class QAction;
|
||||
class QMenu;
|
||||
class QTextEdit;
|
||||
QT_END_NAMESPACE
|
||||
|
||||
class MainWindow: public QMainWindow
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
MainWindow();
|
||||
|
||||
private Q_SLOTS:
|
||||
void loadFreeCAD();
|
||||
void newDocument();
|
||||
void embedWindow();
|
||||
void about();
|
||||
|
||||
private:
|
||||
void createActions();
|
||||
void createMenus();
|
||||
|
||||
QMenu* fileMenu;
|
||||
QMenu* editMenu;
|
||||
QMenu* helpMenu;
|
||||
QAction* loadAct;
|
||||
QAction* newAct;
|
||||
QAction* embedAct;
|
||||
QAction* exitAct;
|
||||
QAction* aboutAct;
|
||||
};
|
||||
26
src/Tools/embedded/Win32/FreeCAD_widget.sln
Normal file
26
src/Tools/embedded/Win32/FreeCAD_widget.sln
Normal file
@@ -0,0 +1,26 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 10.00
|
||||
# Visual Studio 2008
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "FreeCAD_widget", "FreeCAD_widget\FreeCAD_widget.vcproj", "{FA497BF4-3A38-474A-8085-3035BE60F54A}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Win32 = Debug|Win32
|
||||
Debug|x64 = Debug|x64
|
||||
Release|Win32 = Release|Win32
|
||||
Release|x64 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{FA497BF4-3A38-474A-8085-3035BE60F54A}.Debug|Win32.ActiveCfg = Debug|Win32
|
||||
{FA497BF4-3A38-474A-8085-3035BE60F54A}.Debug|Win32.Build.0 = Debug|Win32
|
||||
{FA497BF4-3A38-474A-8085-3035BE60F54A}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{FA497BF4-3A38-474A-8085-3035BE60F54A}.Debug|x64.Build.0 = Debug|x64
|
||||
{FA497BF4-3A38-474A-8085-3035BE60F54A}.Release|Win32.ActiveCfg = Release|Win32
|
||||
{FA497BF4-3A38-474A-8085-3035BE60F54A}.Release|Win32.Build.0 = Release|Win32
|
||||
{FA497BF4-3A38-474A-8085-3035BE60F54A}.Release|x64.ActiveCfg = Release|x64
|
||||
{FA497BF4-3A38-474A-8085-3035BE60F54A}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
338
src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.cpp
Normal file
338
src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.cpp
Normal file
@@ -0,0 +1,338 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
// FreeCAD_widget.cpp : Defines the entry point for the application.
|
||||
//
|
||||
|
||||
#include "FreeCAD_widget.h"
|
||||
#include "stdafx.h"
|
||||
#include <Commdlg.h>
|
||||
#include <Shlobj.h>
|
||||
#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
|
||||
|
||||
// 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);
|
||||
|
||||
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
|
||||
{
|
||||
UNREFERENCED_PARAMETER(hPrevInstance);
|
||||
UNREFERENCED_PARAMETER(lpCmdLine);
|
||||
|
||||
// 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);
|
||||
|
||||
// Perform application initialization:
|
||||
if (!InitInstance(hInstance, nCmdShow)) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
return (int)msg.wParam;
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// FUNCTION: MyRegisterClass()
|
||||
//
|
||||
// PURPOSE: Registers the window class.
|
||||
//
|
||||
// COMMENTS:
|
||||
//
|
||||
// This function and its usage are only necessary if you want this code
|
||||
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
|
||||
// function that was added to Windows 95. It is important to call this function
|
||||
// so that the application will get 'well formed' small icons associated
|
||||
// with it.
|
||||
//
|
||||
ATOM MyRegisterClass(HINSTANCE hInstance)
|
||||
{
|
||||
WNDCLASSEX wcex;
|
||||
|
||||
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));
|
||||
|
||||
return RegisterClassEx(&wcex);
|
||||
}
|
||||
|
||||
//
|
||||
// FUNCTION: InitInstance(HINSTANCE, int)
|
||||
//
|
||||
// PURPOSE: Saves instance handle and creates main window
|
||||
//
|
||||
// COMMENTS:
|
||||
//
|
||||
// In this function, we save the instance handle in a global variable and
|
||||
// create and display the main program window.
|
||||
//
|
||||
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
|
||||
{
|
||||
HWND hWnd;
|
||||
|
||||
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
|
||||
);
|
||||
|
||||
if (!hWnd) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
ShowWindow(hWnd, nCmdShow);
|
||||
UpdateWindow(hWnd);
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
//
|
||||
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
|
||||
//
|
||||
// PURPOSE: Processes messages for the main window.
|
||||
//
|
||||
// WM_COMMAND - process the application menu
|
||||
// WM_PAINT - Paint the main window
|
||||
// WM_DESTROY - post a quit message and return
|
||||
//
|
||||
//
|
||||
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
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);
|
||||
break;
|
||||
case ID_FREECAD_NEWDOCUMENT:
|
||||
OnNewDocument(hWnd);
|
||||
break;
|
||||
case ID_FREECAD_EMBEDWINDOW:
|
||||
OnEmbedWidget(hWnd);
|
||||
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;
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
||||
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>
|
||||
|
||||
// See also https://www.freecad.org/wiki/Embedding_FreeCAD
|
||||
|
||||
std::string OnFileOpen(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
std::string path;
|
||||
BROWSEINFO bi;
|
||||
memset(&bi, 0, sizeof(BROWSEINFO));
|
||||
bi.hwndOwner = hWnd;
|
||||
bi.lpszTitle = "Select FreeCAD module directory";
|
||||
bi.ulFlags = BIF_RETURNONLYFSDIRS;
|
||||
|
||||
ITEMIDLIST* pList = SHBrowseForFolder(&bi);
|
||||
if (pList) {
|
||||
char szFolder[MAX_PATH + 1];
|
||||
SHGetPathFromIDList(pList, szFolder);
|
||||
path = szFolder;
|
||||
LPMALLOC pMalloc;
|
||||
if (S_OK == SHGetMalloc(&pMalloc)) {
|
||||
pMalloc->Free(pList);
|
||||
}
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
void OnLoadFreeCAD(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
if (!Py_IsInitialized()) {
|
||||
Py_SetProgramName(L"CEmbed_FreeCADDlg");
|
||||
Py_Initialize();
|
||||
static int argc = 1;
|
||||
static wchar_t* app = L"CEmbed_FreeCADDlg";
|
||||
static wchar_t* argv[2] = {app, 0};
|
||||
PySys_SetArgv(argc, argv);
|
||||
}
|
||||
|
||||
std::string path = OnFileOpen(hWnd, message, wParam, lParam);
|
||||
if (!path.empty()) {
|
||||
for (std::string::iterator it = path.begin(); it != path.end(); ++it) {
|
||||
if (*it == '\\') {
|
||||
*it = '/';
|
||||
}
|
||||
}
|
||||
PyObject* main = PyImport_AddModule("__main__");
|
||||
PyObject* dict = PyModule_GetDict(main);
|
||||
std::stringstream cmd;
|
||||
cmd << "import sys,os\n"
|
||||
<< "sys.path.append(\"" << path << "\")\n"
|
||||
<< "os.chdir(\"" << path << "\")\n"
|
||||
<< "import FreeCADGui\n"
|
||||
<< "FreeCADGui.showMainWindow()\n";
|
||||
|
||||
PyObject* result = PyRun_String(cmd.str().c_str(), Py_file_input, dict, dict);
|
||||
if (result) {
|
||||
Py_DECREF(result);
|
||||
HMENU hMenu = GetMenu(hWnd);
|
||||
EnableMenuItem(hMenu, ID_FREECAD_LOAD, MF_DISABLED);
|
||||
EnableMenuItem(hMenu, ID_FREECAD_NEWDOCUMENT, MF_ENABLED);
|
||||
EnableMenuItem(hMenu, ID_FREECAD_EMBEDWINDOW, MF_ENABLED);
|
||||
}
|
||||
else {
|
||||
PyObject *ptype, *pvalue, *ptrace;
|
||||
PyErr_Fetch(&ptype, &pvalue, &ptrace);
|
||||
PyObject* pystring = PyObject_Str(pvalue);
|
||||
const char* error = PyUnicode_AsUTF8(pystring);
|
||||
MessageBox(0, error, "Error", MB_OK);
|
||||
Py_DECREF(pystring);
|
||||
}
|
||||
Py_DECREF(dict);
|
||||
}
|
||||
}
|
||||
|
||||
void OnNewDocument(HWND hWnd)
|
||||
{
|
||||
PyObject* main = PyImport_AddModule("__main__");
|
||||
PyObject* dict = PyModule_GetDict(main);
|
||||
const char* cmd = "FreeCAD.newDocument()\n";
|
||||
|
||||
PyObject* result = PyRun_String(cmd, Py_file_input, dict, dict);
|
||||
if (result) {
|
||||
Py_DECREF(result);
|
||||
}
|
||||
else {
|
||||
PyObject *ptype, *pvalue, *ptrace;
|
||||
PyErr_Fetch(&ptype, &pvalue, &ptrace);
|
||||
PyObject* pystring = PyObject_Str(pvalue);
|
||||
const char* error = PyUnicode_AsUTF8(pystring);
|
||||
MessageBox(hWnd, error, "Error", MB_OK);
|
||||
Py_DECREF(pystring);
|
||||
}
|
||||
Py_DECREF(dict);
|
||||
}
|
||||
|
||||
void OnEmbedWidget(HWND hWnd)
|
||||
{
|
||||
PyObject* main = PyImport_AddModule("__main__");
|
||||
PyObject* dict = PyModule_GetDict(main);
|
||||
std::stringstream cmd;
|
||||
cmd << "class BlankWorkbench (Workbench):\n"
|
||||
<< " MenuText = \"Blank\"\n"
|
||||
<< " ToolTip = \"Blank workbench\"\n"
|
||||
<< "\n"
|
||||
<< " def Initialize(self):\n"
|
||||
<< " return\n"
|
||||
<< " def GetClassName(self):\n"
|
||||
<< " return \"Gui::BlankWorkbench\"\n"
|
||||
<< "\n"
|
||||
<< "FreeCADGui.addWorkbench(BlankWorkbench)\n"
|
||||
<< "FreeCADGui.activateWorkbench(\"BlankWorkbench\")\n"
|
||||
<< "FreeCADGui.embedToWindow(\"" << (void*)hWnd << "\")\n"
|
||||
<< "\n";
|
||||
PyObject* result = PyRun_String(cmd.str().c_str(), Py_file_input, dict, dict);
|
||||
if (result) {
|
||||
Py_DECREF(result);
|
||||
HMENU hMenu = GetMenu(hWnd);
|
||||
EnableMenuItem(hMenu, ID_FREECAD_EMBEDWINDOW, MF_DISABLED);
|
||||
}
|
||||
else {
|
||||
PyObject *ptype, *pvalue, *ptrace;
|
||||
PyErr_Fetch(&ptype, &pvalue, &ptrace);
|
||||
PyObject* pystring = PyObject_Str(pvalue);
|
||||
const char* error = PyUnicode_AsUTF8(pystring);
|
||||
MessageBox(hWnd, error, "Error", MB_OK);
|
||||
Py_DECREF(pystring);
|
||||
}
|
||||
Py_DECREF(dict);
|
||||
}
|
||||
5
src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.h
Normal file
5
src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.h
Normal file
@@ -0,0 +1,5 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "resource.h"
|
||||
BIN
src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.ico
Normal file
BIN
src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
166
src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.rc
Normal file
166
src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.rc
Normal file
@@ -0,0 +1,166 @@
|
||||
// Microsoft Visual C++ generated resource script.
|
||||
//
|
||||
#include "resource.h"
|
||||
|
||||
#define APSTUDIO_READONLY_SYMBOLS
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Generated from the TEXTINCLUDE 2 resource.
|
||||
//
|
||||
#ifndef APSTUDIO_INVOKED
|
||||
#include "targetver.h"
|
||||
#endif
|
||||
#define APSTUDIO_HIDDEN_SYMBOLS
|
||||
#include "windows.h"
|
||||
#undef APSTUDIO_HIDDEN_SYMBOLS
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
#undef APSTUDIO_READONLY_SYMBOLS
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// English (U.S.) resources
|
||||
|
||||
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
|
||||
#ifdef _WIN32
|
||||
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
|
||||
#pragma code_page(1252)
|
||||
#endif //_WIN32
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Icon
|
||||
//
|
||||
|
||||
// Icon with lowest ID value placed first to ensure application icon
|
||||
// remains consistent on all systems.
|
||||
IDI_FREECAD_WIDGET ICON "FreeCAD_widget.ico"
|
||||
IDI_SMALL ICON "small.ico"
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Menu
|
||||
//
|
||||
|
||||
IDC_FREECAD_WIDGET MENU
|
||||
BEGIN
|
||||
POPUP "&File"
|
||||
BEGIN
|
||||
MENUITEM "E&xit", IDM_EXIT
|
||||
END
|
||||
POPUP "FreeCAD"
|
||||
BEGIN
|
||||
MENUITEM "Load", ID_FREECAD_LOAD
|
||||
MENUITEM "New document", ID_FREECAD_NEWDOCUMENT, INACTIVE
|
||||
MENUITEM "Embed window", ID_FREECAD_EMBEDWINDOW, INACTIVE
|
||||
END
|
||||
POPUP "&Help"
|
||||
BEGIN
|
||||
MENUITEM "&About ...", IDM_ABOUT
|
||||
END
|
||||
END
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Accelerator
|
||||
//
|
||||
|
||||
IDC_FREECAD_WIDGET ACCELERATORS
|
||||
BEGIN
|
||||
"?", IDM_ABOUT, ASCII, ALT
|
||||
"/", IDM_ABOUT, ASCII, ALT
|
||||
END
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Dialog
|
||||
//
|
||||
|
||||
IDD_ABOUTBOX DIALOGEX 0, 0, 170, 62
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "About FreeCAD_widget"
|
||||
FONT 8, "MS Shell Dlg", 0, 0, 0x1
|
||||
BEGIN
|
||||
ICON 128,IDC_STATIC,14,14,21,20
|
||||
LTEXT "FreeCAD_widget, Version 1.0",IDC_STATIC,42,14,114,8,SS_NOPREFIX
|
||||
LTEXT "Copyright (C) 2011",IDC_STATIC,42,26,114,8
|
||||
DEFPUSHBUTTON "OK",IDOK,113,41,50,14,WS_GROUP
|
||||
END
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// DESIGNINFO
|
||||
//
|
||||
|
||||
#ifdef APSTUDIO_INVOKED
|
||||
GUIDELINES DESIGNINFO
|
||||
BEGIN
|
||||
IDD_ABOUTBOX, DIALOG
|
||||
BEGIN
|
||||
LEFTMARGIN, 7
|
||||
RIGHTMARGIN, 163
|
||||
TOPMARGIN, 7
|
||||
BOTTOMMARGIN, 55
|
||||
END
|
||||
END
|
||||
#endif // APSTUDIO_INVOKED
|
||||
|
||||
|
||||
#ifdef APSTUDIO_INVOKED
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// TEXTINCLUDE
|
||||
//
|
||||
|
||||
1 TEXTINCLUDE
|
||||
BEGIN
|
||||
"resource.h\0"
|
||||
END
|
||||
|
||||
2 TEXTINCLUDE
|
||||
BEGIN
|
||||
"#ifndef APSTUDIO_INVOKED\r\n"
|
||||
"#include ""targetver.h""\r\n"
|
||||
"#endif\r\n"
|
||||
"#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
|
||||
"#include ""windows.h""\r\n"
|
||||
"#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
|
||||
"\0"
|
||||
END
|
||||
|
||||
3 TEXTINCLUDE
|
||||
BEGIN
|
||||
"\r\n"
|
||||
"\0"
|
||||
END
|
||||
|
||||
#endif // APSTUDIO_INVOKED
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// String Table
|
||||
//
|
||||
|
||||
STRINGTABLE
|
||||
BEGIN
|
||||
IDS_APP_TITLE "FreeCAD_widget"
|
||||
IDC_FREECAD_WIDGET "FREECAD_WIDGET"
|
||||
END
|
||||
|
||||
#endif // English (U.S.) resources
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
#ifndef APSTUDIO_INVOKED
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Generated from the TEXTINCLUDE 3 resource.
|
||||
//
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
#endif // not APSTUDIO_INVOKED
|
||||
419
src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.vcproj
Normal file
419
src/Tools/embedded/Win32/FreeCAD_widget/FreeCAD_widget.vcproj
Normal file
@@ -0,0 +1,419 @@
|
||||
<?xml version="1.0" encoding="Windows-1252"?>
|
||||
<VisualStudioProject
|
||||
ProjectType="Visual C++"
|
||||
Version="9,00"
|
||||
Name="FreeCAD_widget"
|
||||
ProjectGUID="{FA497BF4-3A38-474A-8085-3035BE60F54A}"
|
||||
RootNamespace="FreeCAD_widget"
|
||||
Keyword="Win32Proj"
|
||||
TargetFrameworkVersion="196613"
|
||||
>
|
||||
<Platforms>
|
||||
<Platform
|
||||
Name="Win32"
|
||||
/>
|
||||
<Platform
|
||||
Name="x64"
|
||||
/>
|
||||
</Platforms>
|
||||
<ToolFiles>
|
||||
</ToolFiles>
|
||||
<Configurations>
|
||||
<Configuration
|
||||
Name="Debug|Win32"
|
||||
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
|
||||
IntermediateDirectory="$(ConfigurationName)"
|
||||
ConfigurationType="1"
|
||||
CharacterSet="0"
|
||||
>
|
||||
<Tool
|
||||
Name="VCPreBuildEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCustomBuildTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXMLDataGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCWebServiceProxyGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCMIDLTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
Optimization="0"
|
||||
AdditionalIncludeDirectories=""C:\Projects\LibPack\LibPack_win32\include\Python-2.6.4""
|
||||
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
|
||||
MinimalRebuild="true"
|
||||
BasicRuntimeChecks="3"
|
||||
RuntimeLibrary="3"
|
||||
UsePrecompiledHeader="2"
|
||||
WarningLevel="3"
|
||||
DebugInformationFormat="4"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManagedResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPreLinkEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCLinkerTool"
|
||||
LinkIncremental="2"
|
||||
AdditionalLibraryDirectories="C:\Projects\LibPack\LibPack_win32\lib"
|
||||
GenerateDebugInformation="true"
|
||||
SubSystem="2"
|
||||
TargetMachine="1"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCALinkTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManifestTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXDCMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCBscMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCFxCopTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCAppVerifierTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPostBuildEventTool"
|
||||
/>
|
||||
</Configuration>
|
||||
<Configuration
|
||||
Name="Debug|x64"
|
||||
OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
|
||||
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
|
||||
ConfigurationType="1"
|
||||
CharacterSet="0"
|
||||
>
|
||||
<Tool
|
||||
Name="VCPreBuildEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCustomBuildTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXMLDataGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCWebServiceProxyGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCMIDLTool"
|
||||
TargetEnvironment="3"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
Optimization="0"
|
||||
AdditionalIncludeDirectories=""C:\Projects\LibPack\LibPack_x64\include\Python-2.6.4""
|
||||
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"
|
||||
MinimalRebuild="true"
|
||||
BasicRuntimeChecks="3"
|
||||
RuntimeLibrary="3"
|
||||
UsePrecompiledHeader="2"
|
||||
WarningLevel="3"
|
||||
DebugInformationFormat="3"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManagedResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPreLinkEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCLinkerTool"
|
||||
LinkIncremental="2"
|
||||
AdditionalLibraryDirectories="C:\Projects\LibPack\LibPack_x64\lib"
|
||||
GenerateDebugInformation="true"
|
||||
SubSystem="2"
|
||||
TargetMachine="17"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCALinkTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManifestTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXDCMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCBscMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCFxCopTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCAppVerifierTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPostBuildEventTool"
|
||||
/>
|
||||
</Configuration>
|
||||
<Configuration
|
||||
Name="Release|Win32"
|
||||
OutputDirectory="$(SolutionDir)$(ConfigurationName)"
|
||||
IntermediateDirectory="$(ConfigurationName)"
|
||||
ConfigurationType="1"
|
||||
CharacterSet="0"
|
||||
WholeProgramOptimization="1"
|
||||
>
|
||||
<Tool
|
||||
Name="VCPreBuildEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCustomBuildTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXMLDataGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCWebServiceProxyGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCMIDLTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
Optimization="2"
|
||||
EnableIntrinsicFunctions="true"
|
||||
AdditionalIncludeDirectories=""C:\Projects\LibPack\LibPack_win32\include\Python-2.6.4""
|
||||
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
|
||||
RuntimeLibrary="2"
|
||||
EnableFunctionLevelLinking="true"
|
||||
UsePrecompiledHeader="2"
|
||||
WarningLevel="3"
|
||||
DebugInformationFormat="3"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManagedResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPreLinkEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCLinkerTool"
|
||||
LinkIncremental="1"
|
||||
AdditionalLibraryDirectories="C:\Projects\LibPack\LibPack_win32\lib"
|
||||
GenerateDebugInformation="true"
|
||||
SubSystem="2"
|
||||
OptimizeReferences="2"
|
||||
EnableCOMDATFolding="2"
|
||||
TargetMachine="1"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCALinkTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManifestTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXDCMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCBscMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCFxCopTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCAppVerifierTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPostBuildEventTool"
|
||||
/>
|
||||
</Configuration>
|
||||
<Configuration
|
||||
Name="Release|x64"
|
||||
OutputDirectory="$(SolutionDir)$(PlatformName)\$(ConfigurationName)"
|
||||
IntermediateDirectory="$(PlatformName)\$(ConfigurationName)"
|
||||
ConfigurationType="1"
|
||||
CharacterSet="0"
|
||||
WholeProgramOptimization="1"
|
||||
>
|
||||
<Tool
|
||||
Name="VCPreBuildEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCustomBuildTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXMLDataGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCWebServiceProxyGeneratorTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCMIDLTool"
|
||||
TargetEnvironment="3"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
Optimization="2"
|
||||
EnableIntrinsicFunctions="true"
|
||||
AdditionalIncludeDirectories=""C:\Projects\LibPack\LibPack_x64\include\Python-2.6.4""
|
||||
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"
|
||||
RuntimeLibrary="2"
|
||||
EnableFunctionLevelLinking="true"
|
||||
UsePrecompiledHeader="2"
|
||||
WarningLevel="3"
|
||||
DebugInformationFormat="3"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManagedResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCResourceCompilerTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPreLinkEventTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCLinkerTool"
|
||||
LinkIncremental="1"
|
||||
AdditionalLibraryDirectories="C:\Projects\LibPack\LibPack_x64\lib"
|
||||
GenerateDebugInformation="true"
|
||||
SubSystem="2"
|
||||
OptimizeReferences="2"
|
||||
EnableCOMDATFolding="2"
|
||||
TargetMachine="17"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCALinkTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCManifestTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCXDCMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCBscMakeTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCFxCopTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCAppVerifierTool"
|
||||
/>
|
||||
<Tool
|
||||
Name="VCPostBuildEventTool"
|
||||
/>
|
||||
</Configuration>
|
||||
</Configurations>
|
||||
<References>
|
||||
</References>
|
||||
<Files>
|
||||
<Filter
|
||||
Name="Source Files"
|
||||
Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
|
||||
UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
|
||||
>
|
||||
<File
|
||||
RelativePath=".\FreeCAD_widget.cpp"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\stdafx.cpp"
|
||||
>
|
||||
<FileConfiguration
|
||||
Name="Debug|Win32"
|
||||
>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
UsePrecompiledHeader="1"
|
||||
/>
|
||||
</FileConfiguration>
|
||||
<FileConfiguration
|
||||
Name="Debug|x64"
|
||||
>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
UsePrecompiledHeader="1"
|
||||
/>
|
||||
</FileConfiguration>
|
||||
<FileConfiguration
|
||||
Name="Release|Win32"
|
||||
>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
UsePrecompiledHeader="1"
|
||||
/>
|
||||
</FileConfiguration>
|
||||
<FileConfiguration
|
||||
Name="Release|x64"
|
||||
>
|
||||
<Tool
|
||||
Name="VCCLCompilerTool"
|
||||
UsePrecompiledHeader="1"
|
||||
/>
|
||||
</FileConfiguration>
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Header Files"
|
||||
Filter="h;hpp;hxx;hm;inl;inc;xsd"
|
||||
UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
|
||||
>
|
||||
<File
|
||||
RelativePath=".\FreeCAD_widget.h"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\Resource.h"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\stdafx.h"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\targetver.h"
|
||||
>
|
||||
</File>
|
||||
</Filter>
|
||||
<Filter
|
||||
Name="Resource Files"
|
||||
Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
|
||||
UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
|
||||
>
|
||||
<File
|
||||
RelativePath=".\FreeCAD_widget.ico"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\FreeCAD_widget.rc"
|
||||
>
|
||||
</File>
|
||||
<File
|
||||
RelativePath=".\small.ico"
|
||||
>
|
||||
</File>
|
||||
</Filter>
|
||||
<File
|
||||
RelativePath=".\ReadMe.txt"
|
||||
>
|
||||
</File>
|
||||
</Files>
|
||||
<Globals>
|
||||
</Globals>
|
||||
</VisualStudioProject>
|
||||
55
src/Tools/embedded/Win32/FreeCAD_widget/ReadMe.txt
Normal file
55
src/Tools/embedded/Win32/FreeCAD_widget/ReadMe.txt
Normal file
@@ -0,0 +1,55 @@
|
||||
========================================================================
|
||||
WIN32 APPLICATION : FreeCAD_widget Project Overview
|
||||
========================================================================
|
||||
|
||||
AppWizard has created this FreeCAD_widget application for you.
|
||||
|
||||
This file contains a summary of what you will find in each of the files that
|
||||
make up your FreeCAD_widget application.
|
||||
|
||||
|
||||
FreeCAD_widget.vcproj
|
||||
This is the main project file for VC++ projects generated using an Application Wizard.
|
||||
It contains information about the version of Visual C++ that generated the file, and
|
||||
information about the platforms, configurations, and project features selected with the
|
||||
Application Wizard.
|
||||
|
||||
FreeCAD_widget.cpp
|
||||
This is the main application source file.
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
AppWizard has created the following resources:
|
||||
|
||||
FreeCAD_widget.rc
|
||||
This is a listing of all of the Microsoft Windows resources that the
|
||||
program uses. It includes the icons, bitmaps, and cursors that are stored
|
||||
in the RES subdirectory. This file can be directly edited in Microsoft
|
||||
Visual C++.
|
||||
|
||||
Resource.h
|
||||
This is the standard header file, which defines new resource IDs.
|
||||
Microsoft Visual C++ reads and updates this file.
|
||||
|
||||
FreeCAD_widget.ico
|
||||
This is an icon file, which is used as the application's icon (32x32).
|
||||
This icon is included by the main resource file FreeCAD_widget.rc.
|
||||
|
||||
small.ico
|
||||
This is an icon file, which contains a smaller version (16x16)
|
||||
of the application's icon. This icon is included by the main resource
|
||||
file FreeCAD_widget.rc.
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
Other standard files:
|
||||
|
||||
StdAfx.h, StdAfx.cpp
|
||||
These files are used to build a precompiled header (PCH) file
|
||||
named FreeCAD_widget.pch and a precompiled types file named StdAfx.obj.
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
Other notes:
|
||||
|
||||
AppWizard uses "TODO:" comments to indicate parts of the source code you
|
||||
should add to or customize.
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
32
src/Tools/embedded/Win32/FreeCAD_widget/resource.h
Normal file
32
src/Tools/embedded/Win32/FreeCAD_widget/resource.h
Normal file
@@ -0,0 +1,32 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
//{{NO_DEPENDENCIES}}
|
||||
// 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
|
||||
|
||||
// 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
|
||||
# endif
|
||||
#endif
|
||||
BIN
src/Tools/embedded/Win32/FreeCAD_widget/small.ico
Normal file
BIN
src/Tools/embedded/Win32/FreeCAD_widget/small.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
10
src/Tools/embedded/Win32/FreeCAD_widget/stdafx.cpp
Normal file
10
src/Tools/embedded/Win32/FreeCAD_widget/stdafx.cpp
Normal file
@@ -0,0 +1,10 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
// stdafx.cpp : source file that includes just the standard includes
|
||||
// FreeCAD_widget.pch will be the pre-compiled header
|
||||
// stdafx.obj will contain the pre-compiled type information
|
||||
|
||||
#include "stdafx.h"
|
||||
|
||||
// TODO: reference any additional headers you need in STDAFX.H
|
||||
// and not in this file
|
||||
23
src/Tools/embedded/Win32/FreeCAD_widget/stdafx.h
Normal file
23
src/Tools/embedded/Win32/FreeCAD_widget/stdafx.h
Normal file
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
// stdafx.h : include file for standard system include files,
|
||||
// or project specific include files that are used frequently, but
|
||||
// are changed infrequently
|
||||
//
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "targetver.h"
|
||||
|
||||
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
|
||||
// Windows Header Files:
|
||||
#include <windows.h>
|
||||
|
||||
// C RunTime Header Files
|
||||
#include <malloc.h>
|
||||
#include <memory.h>
|
||||
#include <stdlib.h>
|
||||
#include <tchar.h>
|
||||
|
||||
|
||||
// TODO: reference additional headers your program requires here
|
||||
28
src/Tools/embedded/Win32/FreeCAD_widget/targetver.h
Normal file
28
src/Tools/embedded/Win32/FreeCAD_widget/targetver.h
Normal file
@@ -0,0 +1,28 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#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.
|
||||
|
||||
// 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.
|
||||
#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.
|
||||
#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.
|
||||
#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.
|
||||
#endif
|
||||
59
src/Tools/embedded/glib/glib.cbp
Normal file
59
src/Tools/embedded/glib/glib.cbp
Normal file
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
|
||||
<CodeBlocks_project_file>
|
||||
<FileVersion major="1" minor="6" />
|
||||
<Project>
|
||||
<Option title="glib" />
|
||||
<Option pch_mode="2" />
|
||||
<Option compiler="gcc" />
|
||||
<Build>
|
||||
<Target title="Debug">
|
||||
<Option output="bin/Debug/glib" prefix_auto="1" extension_auto="1" />
|
||||
<Option object_output="obj/Debug/" />
|
||||
<Option type="1" />
|
||||
<Option compiler="gcc" />
|
||||
<Compiler>
|
||||
<Add option="-g" />
|
||||
<Add directory="/usr/include/python3.6m" />
|
||||
<Add directory="/usr/include/gtk-3.0/" />
|
||||
<Add directory="/usr/include/glib-2.0" />
|
||||
<Add directory="/usr/lib/x86_64-linux-gnu/glib-2.0/include" />
|
||||
<Add directory="/usr/include/cairo/" />
|
||||
<Add directory="/usr/include/pango-1.0/" />
|
||||
<Add directory="/usr/include/gdk-pixbuf-2.0/" />
|
||||
<Add directory="/usr/include/atk-1.0/" />
|
||||
</Compiler>
|
||||
</Target>
|
||||
<Target title="Release">
|
||||
<Option output="bin/Release/glib" prefix_auto="1" extension_auto="1" />
|
||||
<Option object_output="obj/Release/" />
|
||||
<Option type="0" />
|
||||
<Option compiler="gcc" />
|
||||
<Compiler>
|
||||
<Add option="-O2" />
|
||||
</Compiler>
|
||||
<Linker>
|
||||
<Add option="-s" />
|
||||
</Linker>
|
||||
</Target>
|
||||
</Build>
|
||||
<Compiler>
|
||||
<Add option="-Wall" />
|
||||
<Add option="`pkg-config gtk+-3.0 --cflags`" />
|
||||
<Add directory="/usr/include/gtk-3.0" />
|
||||
</Compiler>
|
||||
<Linker>
|
||||
<Add option="`pkg-config gtk+-3.0 --libs`" />
|
||||
<Add library="python3.6m" />
|
||||
<Add library="glib-2.0" />
|
||||
<Add library="gobject-2.0" />
|
||||
<Add directory="/usr/lib/x86_64-linux-gnu/" />
|
||||
</Linker>
|
||||
<Unit filename="main.c">
|
||||
<Option compilerVar="CC" />
|
||||
</Unit>
|
||||
<Extensions>
|
||||
<code_completion />
|
||||
<debugger />
|
||||
</Extensions>
|
||||
</Project>
|
||||
</CodeBlocks_project_file>
|
||||
106
src/Tools/embedded/glib/main.c
Normal file
106
src/Tools/embedded/glib/main.c
Normal file
@@ -0,0 +1,106 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <Python.h>
|
||||
#include <gtk/gtk.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
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
|
||||
);
|
||||
PyObject* result = PyRun_String(
|
||||
"import FreeCADGui\n"
|
||||
"FreeCADGui.showMainWindow()",
|
||||
Py_file_input,
|
||||
dict,
|
||||
dict
|
||||
);
|
||||
if (result) {
|
||||
Py_DECREF(result);
|
||||
}
|
||||
else {
|
||||
PyObject *ptype, *pvalue, *ptrace;
|
||||
PyErr_Fetch(&ptype, &pvalue, &ptrace);
|
||||
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);
|
||||
|
||||
Py_DECREF(pystring);
|
||||
}
|
||||
Py_DECREF(dict);
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[])
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
/* 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 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("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;
|
||||
}
|
||||
8
src/Tools/entitlements.plist
Normal file
8
src/Tools/entitlements.plist
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
68
src/Tools/examplePy2wiki.py
Normal file
68
src/Tools/examplePy2wiki.py
Normal file
@@ -0,0 +1,68 @@
|
||||
#! python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# (c) 2009 Juergen Riegel GPL
|
||||
|
||||
Usage = """examplePy2wiki - generating a wiki text out of a python example
|
||||
|
||||
Usage:
|
||||
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
|
||||
show up us code in the wiki.
|
||||
|
||||
|
||||
Author:
|
||||
(c) 2009 Juergen Riegel
|
||||
juergen.riegel@web.de
|
||||
Licence: GPL V2
|
||||
|
||||
Version:
|
||||
0.1
|
||||
"""
|
||||
|
||||
import os, sys, string, getopt
|
||||
|
||||
|
||||
def Process(line):
|
||||
if line[0:2] == "# ":
|
||||
return line[2:]
|
||||
else:
|
||||
return " " + line
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
try:
|
||||
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)
|
||||
sys.exit(2)
|
||||
|
||||
# checking on the options
|
||||
for o, a in opts:
|
||||
if o in ("-h", "--help"):
|
||||
sys.stderr.write(Usage)
|
||||
sys.exit()
|
||||
if o in ("-o", "--out-file"):
|
||||
outfile = open(a, "w")
|
||||
if o in ("-i", "--in-file"):
|
||||
infile = open(a, "r")
|
||||
|
||||
lines = infile.readlines()
|
||||
for l in lines:
|
||||
outfile.write(Process(l))
|
||||
# print l
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
62
src/Tools/fcbt.py
Normal file
62
src/Tools/fcbt.py
Normal file
@@ -0,0 +1,62 @@
|
||||
#!python
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# FreeCAD Build Tool
|
||||
# (c) 2004 Juergen Riegel
|
||||
|
||||
|
||||
import sys
|
||||
|
||||
help1 = """
|
||||
FreeCAD Build Tool
|
||||
Usage:
|
||||
fcbt <command name> [command parameter]
|
||||
possible commands are:
|
||||
- DistSrc (DS) Build a source Distr. of the current source tree
|
||||
- DistBin (DB) Build a binary Distr. of the current source tree
|
||||
- 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
|
||||
- CreateModule (CM) Insert a new FreeCAD Module in the module directory
|
||||
- CreatePyModule (CP) Insert a new FreeCAD Python Module in the module directory
|
||||
|
||||
For help on the modules type:
|
||||
fcbt <command name> ?
|
||||
|
||||
"""
|
||||
|
||||
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":
|
||||
import fcbt.DistSrc
|
||||
elif Cmd == "distbin" or Cmd == "db":
|
||||
import fcbt.DistBin
|
||||
elif Cmd == "distsetup" or Cmd == "di":
|
||||
import fcbt.DistSetup
|
||||
elif Cmd == "distsetup" or Cmd == "dui":
|
||||
import fcbt.DistUserSetup
|
||||
elif Cmd == "distall" or Cmd == "da":
|
||||
import fcbt.DistSrc
|
||||
import fcbt.DistBin
|
||||
import fcbt.DistSetup
|
||||
elif Cmd == "nextbuildnumber" or Cmd == "nbn":
|
||||
import fcbt.NextBuildNumber
|
||||
elif Cmd == "createmodule" or Cmd == "cm":
|
||||
import fcbt.CreateModule
|
||||
elif Cmd == "createpymodule" or Cmd == "cp":
|
||||
import fcbt.CreatePyModule
|
||||
elif Cmd == "?" or Cmd == "help" or Cmd == "/h" or Cmd == "/?" or Cmd == "-h" or Cmd == "-help":
|
||||
sys.stdout.write(help1)
|
||||
else:
|
||||
print(CmdRaw + " is an unknown command!\n")
|
||||
sys.exit(1)
|
||||
157
src/Tools/fcbt/BuildDoc.py
Normal file
157
src/Tools/fcbt/BuildDoc.py
Normal file
@@ -0,0 +1,157 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# shell and operating system
|
||||
import os, sys, FileTools
|
||||
|
||||
# sys.path.append( "..\Tools" )
|
||||
|
||||
# import FileTools
|
||||
|
||||
# line separator
|
||||
ls = os.linesep
|
||||
# path separator
|
||||
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")
|
||||
if not os.path.isdir("../../doc"):
|
||||
os.mkdir("../../doc")
|
||||
# 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")
|
||||
|
||||
# ====================================================================
|
||||
sys.stdout.write("Running source documentation ...")
|
||||
# running doxygen with the parameters from the config file
|
||||
param = "doxygen fcbt" + ds + "BuildDocDoxy.cfg"
|
||||
LogFile.write(param)
|
||||
print(param)
|
||||
text = os.popen(param).read()
|
||||
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 DVI ...')
|
||||
os.chdir("latex")
|
||||
text = os.popen("latex refman.tex").read()
|
||||
LogFile.write(text)
|
||||
text = os.popen("makeindex refman.idx").read()
|
||||
LogFile.write(text)
|
||||
text = os.popen("latex refman.tex").read()
|
||||
text = os.popen("latex refman.tex").read()
|
||||
text = os.popen("latex refman.tex").read()
|
||||
FileTools.cpfile("refman.dvi","../../../doc/FrameWork/FrameWork.dvi")
|
||||
|
||||
#====================================================================
|
||||
sys.stdout.write (' done\n Generate PS ...')
|
||||
text = os.popen("dvips refman.dvi").read()
|
||||
LogFile.write(text)
|
||||
FileTools.cpfile("refman.ps","../../../doc/FrameWork/FrameWork.ps")
|
||||
|
||||
#====================================================================
|
||||
sys.stdout.write (' done\n Generate PDF ...')
|
||||
text = os.popen("pdflatex refman.tex").read()
|
||||
LogFile.write(text)
|
||||
FileTools.cpfile("refman.pdf","../../../doc/FrameWork/FrameWork.pdf")
|
||||
os.chdir("..")
|
||||
|
||||
#====================================================================
|
||||
sys.stdout.write (' done\n Clean up temporary files ...')
|
||||
FileTools.rmall("html")
|
||||
FileTools.rmall("latex")
|
||||
|
||||
#====================================================================
|
||||
sys.stdout.write (' done\nCreating manuals\n')
|
||||
if not os.path.isdir("../../Doc/Manuals"):
|
||||
os.mkdir("../../Doc/Manuals")
|
||||
os.chdir("Manuals")
|
||||
|
||||
#====================================================================
|
||||
sys.stdout.write(' Generate DVI ...')
|
||||
text = os.popen("latex Design_Specification.tex").read()
|
||||
LogFile.write(text)
|
||||
text = os.popen("makeindex Design_Specification.idx").read()
|
||||
LogFile.write(text)
|
||||
text = os.popen("latex Design_Specification.tex").read()
|
||||
text = os.popen("latex Design_Specification.tex").read()
|
||||
text = os.popen("latex Design_Specification.tex").read()
|
||||
FileTools.cpfile("Design_Specification.dvi","../../../doc/Manuals/Design_Specification.dvi")
|
||||
|
||||
text = os.popen("latex Manual.tex").read()
|
||||
LogFile.write(text)
|
||||
text = os.popen("makeindex Manual.idx").read()
|
||||
LogFile.write(text)
|
||||
text = os.popen("latex Manual.tex").read()
|
||||
text = os.popen("latex Manual.tex").read()
|
||||
text = os.popen("latex Manual.tex").read()
|
||||
FileTools.cpfile("Manual.dvi","../../../doc/Manuals/Manual.dvi")
|
||||
|
||||
#====================================================================
|
||||
sys.stdout.write (' done\n Generate PS ...')
|
||||
text = os.popen("dvips Design_Specification.dvi").read()
|
||||
LogFile.write(text)
|
||||
FileTools.cpfile("Design_Specification.ps","../../../doc/Manuals/Design_Specification.ps")
|
||||
text = os.popen("dvips Manual.dvi").read()
|
||||
LogFile.write(text)
|
||||
FileTools.cpfile("Manual.ps","../../../doc/Manuals/Manual.ps")
|
||||
|
||||
#====================================================================
|
||||
sys.stdout.write (' done\n Generate PDF ...')
|
||||
text = os.popen("pdflatex Design_Specification.tex").read()
|
||||
LogFile.write(text)
|
||||
FileTools.cpfile("Design_Specification.pdf","../../../doc/Manuals/Design_Specification.pdf")
|
||||
text = os.popen("pdflatex Manual.tex").read()
|
||||
LogFile.write(text)
|
||||
FileTools.cpfile("Manual.pdf","../../../doc/Manuals/Manual.pdf")
|
||||
|
||||
#====================================================================
|
||||
#== run latex2html now NOTE: current directory MUST NOT contain any spaces !!!
|
||||
sys.stdout.write (' done\n Generate HTML ...')
|
||||
if not os.path.isdir("../../../doc/Manuals/Design_Specification"):
|
||||
os.mkdir("../../../doc/Manuals/Design_Specification")
|
||||
text = os.popen("latex2html Design_Specification.tex").read()
|
||||
LogFile.write(text)
|
||||
# if latex2html failed this directory doesn't exist
|
||||
if os.path.isdir("Design_Specification"):
|
||||
FileTools.cpall("Design_Specification","../../../doc/Manuals/Design_Specification")
|
||||
else:
|
||||
sys.stderr.write("latex2html failed!\n")
|
||||
|
||||
if not os.path.isdir("../../../doc/Manuals/Manual"):
|
||||
os.mkdir("../../../doc/Manuals/Manual")
|
||||
text = os.popen("latex2html Manual.tex").read()
|
||||
LogFile.write(text)
|
||||
# if latex2html failed this directory doesn't exist
|
||||
if os.path.isdir("Manual"):
|
||||
FileTools.cpall("Manual","../../../doc/Manuals/Manual")
|
||||
|
||||
#====================================================================
|
||||
os.chdir("..")
|
||||
sys.stdout.write (' done\n copy online help ...')
|
||||
if not os.path.isdir("../../Doc/Online"):
|
||||
os.mkdir("../../Doc/Online")
|
||||
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")
|
||||
|
||||
|
||||
# print text
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user