Not much, but a start:
Code: Select all
"""test_library.py
This code was written as an sample code
for "FreeCAD Scripting Guide"
Author: Carlo Dormeletti
Copyright: 2021
Licence: CC BY-NC-ND 4.0 IT
"""
import os
import os.path
import glob
import json
import FreeCAD
from FreeCAD import Base, Rotation, Vector
import PathScripts.PathLog as PathLog
import PathScripts.PathPreferences as PathPreferences
import PathScripts.PathToolBit as PathToolBit
DOC_NAME = "Pippo"
DOC = FreeCAD.activeDocument()
def clear_doc():
"""
Clear the active document deleting all the objects
"""
for obj in DOC.Objects:
DOC.removeObject(obj.Name)
if DOC is None:
FreeCAD.newDocument(DOC_NAME)
FreeCAD.setActiveDocument(DOC_NAME)
DOC = FreeCAD.activeDocument()
VIEW = FreeCAD.Gui.ActiveDocument.ActiveView
else:
clear_doc()
VIEW = FreeCAD.Gui.ActiveDocument.ActiveView
def setview():
"""Rearrange View"""
DOC.recompute()
VIEW.viewAxometric()
VIEW.setAxisCross(True)
VIEW.fitAll()
EPS = 0.10
EPS_C = EPS * -0.5
VZOR = Vector(0,0,0)
RZO = Rotation(0, 0, 0)
def checkWorkingDir():
# Check existence of a working directory.
# and check that working directory is writable
PathLog.track()
workingdir = os.path.dirname(PathPreferences.lastPathToolLibrary())
defaultdir = os.path.dirname(PathPreferences.pathDefaultToolsPath())
msg = 'workingdir: {} defaultdir: {}'.format(workingdir, defaultdir)
PathLog.debug(msg)
print(msg)
dirOK = lambda : workingdir != defaultdir and (os.access(workingdir, os.W_OK))
if dirOK():
return True
else:
return False
class ToolLibrary(object):
'''Helper class to access and manage ToolLibraries.'''
def __init__(self, path=None):
PathLog.track()
self.path = ""
# self.currentLib = ""
def __libraryLoad(self, path, datamodel):
PathLog.track(path)
PathPreferences.setLastFileToolLibrary(path)
# self.currenLib = path
with open(path) as fp:
library = json.load(fp)
for toolBit in library['tools']:
try:
nr = toolBit['nr']
bit = PathToolBit.findToolBit(toolBit['path'], path)
if bit:
PathLog.track(bit)
tool = PathToolBit.Declaration(bit)
datamodel.append((nr, tool, bit))
else:
PathLog.error("Could not find tool #{}: {}".format(nr, toolBit['path']))
except Exception as e:
msg = "Error loading tool: {} : {}".format(toolBit['path'], e)
FreeCAD.Console.PrintError(msg)
def _toolAdd(self, nr, tool, path):
strShape = os.path.splitext(os.path.basename(tool['shape']))[0]
# strDiam = tool['parameter']['Diameter']
tooltip = "{}".format(strShape)
return [toolNr, toolName, toolShape]
def newTool(self, datamodel, path):
"""Add a toolbit item to a library.
"""
PathLog.track()
try:
nr = 0
tool = PathToolBit.Declaration(path)
except Exception as e:
PathLog.error(e)
def findLibraries(self):
"""Find all the fctl files in a location.
Return a list of filenames with path
"""
libfiles = []
PathLog.track()
path = PathPreferences.lastPathToolLibrary()
if os.path.isdir(path):
libFiles = [f for f in glob.glob(path + os.path.sep + '*.fctl')]
libFiles.sort()
for libFile in libFiles:
libfiles.append(libFile)
PathLog.debug('model rows: {}'.format(len(libfiles)))
return libfiles
def libraryOpen(self, lib=""):
'''
opens the tools in library
'''
model = []
PathLog.track(lib)
if lib == "":
lib = PathPreferences.lastFileToolLibrary()
if lib == "" or lib is None:
return model
print("lib: {}".format(lib))
if os.path.isfile(lib): # An individual library is wanted
self.__libraryLoad(lib, model)
PathLog.debug('model rows: {}'.format(len(model)))
return model
def libraryDump(self, lib=""):
tools = self.libraryOpen(lib)
for idx, tool in enumerate(tools):
msg = ["Index: {}".format(idx)]
msg.append("ToolNumber: {}".format(tool[0]))
for mk, mv in tool[1].items():
if mk not in ('parameter', 'attribute'):
msg.append("{}: {}".format(mk, mv))
else:
msg.append("{}:".format(mk))
for pk, pv in mv.items():
msg.append("-- {}: {}".format(pk, pv))
out_msg = "\n".join(msg)
out_msg += "\n-----------------------\n\n"
FreeCAD.Console.PrintMessage(out_msg)
# CODE start here
workingdir = os.path.dirname(PathPreferences.lastPathToolLibrary())
checkWorkingDir()
libraries = []
tools = []
library = ToolLibrary()
libraries = library.findLibraries()
print("Libraries: {}".format(libraries))
library.libraryDump(libraries[1])
print("--- done ---")
As suggested by @sliptonic I've done some work, copying and modifying some methods from /Path/PathScripts/PathToolBitLibraryGui.py as found in 0.20.26202 sources that I have on my hd.
it is more a test code to see how thing works, but just in case someone will find it useful, I put here.
Most of the code is simply the original code copied and slightly modified so maintaining will be more plain as original methods names are nearly identical.
Some description, it nedds a custom Tool Library in the User directory, like one of those created with the Gui ToolLibrary.
For now only libraryDump is added the code will output some data printing them in the Report Window, as a FreeCAD.Console.Message.
some little explanation:
in the user directory a
Tools directory is created by the Gui Tool, there are three sub directories
- Bit where the ToolBit definition reside
- Library where are the Library files (Tool Collections)
- Shape if you don't use custom shapes this is empty in current implementation
a "Tool Collection" file is a json file ending with
.fctl that simply contains the toll number and a reference to the corresponding Bit file
Code: Select all
{
"tools": [
{
"nr": 1,
"path": "5mm_Endmill.fctb"
},
{
"nr": 2,
"path": "5mm_Drill.fctb"
},
{
"nr": 3,
"path": "6mm_Ball_End.fctb"
},
{
"nr": 4,
"path": "6mm_Bullnose.fctb"
},
{
"nr": 5,
"path": "60degree_Vbit.fctb"
}
],
"version": 1
}
This is the content of the Bit file:
Code: Select all
{
"version": 2,
"name": "5mm Endmill",
"shape": "endmill.fcstd",
"parameter": {
"CuttingEdgeHeight": "30.0000 mm",
"Diameter": "5.0000 mm",
"Length": "50.0000 mm",
"ShankDiameter": "3.0000 mm"
},
"attribute": {}
}
So now it all to write some helpers methods that create appropriate files under
Bit subdir and add the appropriate stanza to the "Tool Collection"
Regards
Carlo D.