Drawing: Apply clang format

This commit is contained in:
wmayer
2023-09-10 12:33:49 +02:00
committed by wwmayer
parent ebcd846d09
commit 789912d745
52 changed files with 2650 additions and 2106 deletions

View File

@@ -26,7 +26,8 @@
#include "PageGroup.h"
namespace Drawing {
namespace Drawing
{
extern PyObject* initModule();
}
@@ -36,9 +37,9 @@ PyMOD_INIT_FUNC(Drawing)
// load dependent module
try {
Base::Interpreter().loadModule("Part");
//Base::Interpreter().loadModule("Mesh");
// Base::Interpreter().loadModule("Mesh");
}
catch(const Base::Exception& e) {
catch (const Base::Exception& e) {
PyErr_SetString(PyExc_ImportError, e.what());
PyMOD_Return(nullptr);
}
@@ -49,7 +50,7 @@ PyMOD_INIT_FUNC(Drawing)
// NOTE: To finish the initialization of our own type objects we must
// call PyType_Ready, otherwise we run into a segmentation fault, later on.
// This function is responsible for adding inherited slots from a type's base class.
// clang-format off
Drawing::FeaturePage ::init();
Drawing::FeatureView ::init();
Drawing::FeatureViewPart ::init();
@@ -61,6 +62,6 @@ PyMOD_INIT_FUNC(Drawing)
Drawing::FeatureViewSymbol ::init();
Drawing::FeatureClip ::init();
Drawing::FeatureViewSpreadsheet ::init();
// clang-format on
PyMOD_Return(mod);
}

View File

@@ -22,7 +22,7 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <boost/regex.hpp>
#include <boost/regex.hpp>
#endif
#include <Base/Console.h>
@@ -36,85 +36,97 @@
using namespace std;
using Part::TopoShapePy;
using Part::TopoShape;
using Part::TopoShapePy;
namespace Drawing {
namespace Drawing
{
/** Copies a Python dictionary of Python strings to a C++ container.
*
* After the function call, the key-value pairs of the Python
* dictionary are copied into the target buffer as C++ pairs
* (pair<string, string>).
*
* @param sourceRange is a Python dictionary (Py::Dict). Both, the
* keys and the values must be Python strings.
*
* @param targetIt refers to where the data should be inserted. Must
* be of concept output iterator.
*/
template<typename OutputIt>
void copy(Py::Dict sourceRange, OutputIt targetIt)
{
/** Copies a Python dictionary of Python strings to a C++ container.
*
* After the function call, the key-value pairs of the Python
* dictionary are copied into the target buffer as C++ pairs
* (pair<string, string>).
*
* @param sourceRange is a Python dictionary (Py::Dict). Both, the
* keys and the values must be Python strings.
*
* @param targetIt refers to where the data should be inserted. Must
* be of concept output iterator.
*/
template<typename OutputIt>
void copy(Py::Dict sourceRange, OutputIt targetIt)
{
string key;
string value;
for (const auto& keyPy : sourceRange.keys()) {
key = Py::String(keyPy);
value = Py::String(sourceRange[keyPy]);
*targetIt = {key, value};
++targetIt;
key = Py::String(keyPy);
value = Py::String(sourceRange[keyPy]);
*targetIt = {key, value};
++targetIt;
}
}
}
class Module : public Py::ExtensionModule<Module>
class Module: public Py::ExtensionModule<Module>
{
public:
Module() : Py::ExtensionModule<Module>("Drawing")
Module()
: Py::ExtensionModule<Module>("Drawing")
{
add_varargs_method("project",&Module::project,
"[visiblyG0,visiblyG1,hiddenG0,hiddenG1] = project(TopoShape[,App.Vector Direction, string type])\n"
" -- Project a shape and return the visible/invisible parts of it."
);
add_varargs_method("projectEx",&Module::projectEx,
"[V,V1,VN,VO,VI,H,H1,HN,HO,HI] = projectEx(TopoShape[,App.Vector Direction, string type])\n"
" -- Project a shape and return the all parts of it."
);
add_keyword_method("projectToSVG",&Module::projectToSVG,
"string = projectToSVG(TopoShape[, App.Vector direction, string type, float tolerance, dict vStyle, dict v0Style, dict v1Style, dict hStyle, dict h0Style, dict h1Style])\n"
" -- Project a shape and return the SVG representation as string."
);
add_varargs_method("projectToDXF",&Module::projectToDXF,
"string = projectToDXF(TopoShape[,App.Vector Direction, string type])\n"
" -- Project a shape and return the DXF representation as string."
);
add_varargs_method("removeSvgTags",&Module::removeSvgTags,
add_varargs_method("project",
&Module::project,
"[visiblyG0,visiblyG1,hiddenG0,hiddenG1] = "
"project(TopoShape[,App.Vector Direction, string type])\n"
" -- Project a shape and return the visible/invisible parts of it.");
add_varargs_method("projectEx",
&Module::projectEx,
"[V,V1,VN,VO,VI,H,H1,HN,HO,HI] = projectEx(TopoShape[,App.Vector "
"Direction, string type])\n"
" -- Project a shape and return the all parts of it.");
add_keyword_method(
"projectToSVG",
&Module::projectToSVG,
"string = projectToSVG(TopoShape[, App.Vector direction, string type, float tolerance, "
"dict vStyle, dict v0Style, dict v1Style, dict hStyle, dict h0Style, dict h1Style])\n"
" -- Project a shape and return the SVG representation as string.");
add_varargs_method("projectToDXF",
&Module::projectToDXF,
"string = projectToDXF(TopoShape[,App.Vector Direction, string type])\n"
" -- Project a shape and return the DXF representation as string.");
add_varargs_method(
"removeSvgTags",
&Module::removeSvgTags,
"string = removeSvgTags(string) -- Removes the opening and closing svg tags\n"
"and other metatags from a svg code, making it embeddable"
);
initialize("This module is the Drawing module."); // register with Python
"and other metatags from a svg code, making it embeddable");
initialize("This module is the Drawing module.");// register with Python
}
virtual ~Module() {}
virtual ~Module()
{}
private:
virtual Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args)
virtual Py::Object invoke_method_varargs(void* method_def, const Py::Tuple& args)
{
try {
return Py::ExtensionModule<Module>::invoke_method_varargs(method_def, args);
}
catch (const Standard_Failure &e) {
catch (const Standard_Failure& e) {
std::string str;
Standard_CString msg = e.GetMessageString();
str += typeid(e).name();
str += " ";
if (msg) {str += msg;}
else {str += "No OCCT Exception Message";}
if (msg) {
str += msg;
}
else {
str += "No OCCT Exception Message";
}
Base::Console().Error("%s\n", str.c_str());
throw Py::Exception(Part::PartExceptionOCCError, str);
}
catch (const Base::Exception &e) {
catch (const Base::Exception& e) {
std::string str;
str += "FreeCAD exception thrown (";
str += e.what();
@@ -122,7 +134,7 @@ private:
e.ReportException();
throw Py::RuntimeError(str);
}
catch (const std::exception &e) {
catch (const std::exception& e) {
std::string str;
str += "C++ exception thrown (";
str += e.what();
@@ -133,53 +145,63 @@ private:
}
Py::Object project(const Py::Tuple& args)
{
PyObject *pcObjShape;
PyObject *pcObjDir=nullptr;
PyObject* pcObjShape;
PyObject* pcObjDir = nullptr;
if (!PyArg_ParseTuple(args.ptr(), "O!|O!",
&(Part::TopoShapePy::Type), &pcObjShape,
&(Base::VectorPy::Type), &pcObjDir))
if (!PyArg_ParseTuple(args.ptr(),
"O!|O!",
&(Part::TopoShapePy::Type),
&pcObjShape,
&(Base::VectorPy::Type),
&pcObjDir)) {
throw Py::Exception();
}
Part::TopoShapePy* pShape = static_cast<Part::TopoShapePy*>(pcObjShape);
Base::Vector3d Vector(0,0,1);
if (pcObjDir)
Base::Vector3d Vector(0, 0, 1);
if (pcObjDir) {
Vector = *static_cast<Base::VectorPy*>(pcObjDir)->getVectorPtr();
}
ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(),Vector);
ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(), Vector);
Py::List list;
list.append(Py::Object(new Part::TopoShapePy(new Part::TopoShape(Alg.V)) , true));
list.append(Py::Object(new Part::TopoShapePy(new Part::TopoShape(Alg.V)), true));
list.append(Py::Object(new Part::TopoShapePy(new Part::TopoShape(Alg.V1)), true));
list.append(Py::Object(new Part::TopoShapePy(new Part::TopoShape(Alg.H)) , true));
list.append(Py::Object(new Part::TopoShapePy(new Part::TopoShape(Alg.H)), true));
list.append(Py::Object(new Part::TopoShapePy(new Part::TopoShape(Alg.H1)), true));
return list;
}
Py::Object projectEx(const Py::Tuple& args)
{
PyObject *pcObjShape;
PyObject *pcObjDir=nullptr;
PyObject* pcObjShape;
PyObject* pcObjDir = nullptr;
if (!PyArg_ParseTuple(args.ptr(), "O!|O!",
&(TopoShapePy::Type), &pcObjShape,
&(Base::VectorPy::Type), &pcObjDir))
if (!PyArg_ParseTuple(args.ptr(),
"O!|O!",
&(TopoShapePy::Type),
&pcObjShape,
&(Base::VectorPy::Type),
&pcObjDir)) {
throw Py::Exception();
}
TopoShapePy* pShape = static_cast<TopoShapePy*>(pcObjShape);
Base::Vector3d Vector(0,0,1);
if (pcObjDir)
Base::Vector3d Vector(0, 0, 1);
if (pcObjDir) {
Vector = *static_cast<Base::VectorPy*>(pcObjDir)->getVectorPtr();
}
ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(),Vector);
ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(), Vector);
Py::List list;
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.V)) , true));
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.V)), true));
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.V1)), true));
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.VN)), true));
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.VO)), true));
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.VI)), true));
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.H)) , true));
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.H)), true));
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.H1)), true));
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.HN)), true));
list.append(Py::Object(new TopoShapePy(new TopoShape(Alg.HO)), true));
@@ -189,140 +211,165 @@ private:
}
Py::Object projectToSVG(const Py::Tuple& args, const Py::Dict& keys)
{
static const std::array<const char *, 11> argNames {"topoShape",
"direction",
"type",
"tolerance",
"vStyle",
"v0Style",
"v1Style",
"hStyle",
"h0Style",
"h1Style",
nullptr};
PyObject *pcObjShape = nullptr;
PyObject *pcObjDir = nullptr;
const char *extractionTypePy = nullptr;
ProjectionAlgos::ExtractionType extractionType = ProjectionAlgos::Plain;
const float tol = 0.1f;
PyObject* vStylePy = nullptr;
ProjectionAlgos::XmlAttributes vStyle;
PyObject* v0StylePy = nullptr;
ProjectionAlgos::XmlAttributes v0Style;
PyObject* v1StylePy = nullptr;
ProjectionAlgos::XmlAttributes v1Style;
PyObject* hStylePy = nullptr;
ProjectionAlgos::XmlAttributes hStyle;
PyObject* h0StylePy = nullptr;
ProjectionAlgos::XmlAttributes h0Style;
PyObject* h1StylePy = nullptr;
ProjectionAlgos::XmlAttributes h1Style;
// Get the arguments
{
static const std::array<const char*, 11> argNames {"topoShape",
"direction",
"type",
"tolerance",
"vStyle",
"v0Style",
"v1Style",
"hStyle",
"h0Style",
"h1Style",
nullptr};
PyObject* pcObjShape = nullptr;
PyObject* pcObjDir = nullptr;
const char* extractionTypePy = nullptr;
ProjectionAlgos::ExtractionType extractionType = ProjectionAlgos::Plain;
const float tol = 0.1f;
PyObject* vStylePy = nullptr;
ProjectionAlgos::XmlAttributes vStyle;
PyObject* v0StylePy = nullptr;
ProjectionAlgos::XmlAttributes v0Style;
PyObject* v1StylePy = nullptr;
ProjectionAlgos::XmlAttributes v1Style;
PyObject* hStylePy = nullptr;
ProjectionAlgos::XmlAttributes hStyle;
PyObject* h0StylePy = nullptr;
ProjectionAlgos::XmlAttributes h0Style;
PyObject* h1StylePy = nullptr;
ProjectionAlgos::XmlAttributes h1Style;
if (!Base::Wrapped_ParseTupleAndKeywords(
args.ptr(), keys.ptr(),
"O!|O!sfOOOOOO",
argNames,
&(TopoShapePy::Type), &pcObjShape,
&(Base::VectorPy::Type), &pcObjDir,
&extractionTypePy, &tol,
&vStylePy, &v0StylePy, &v1StylePy,
&hStylePy, &h0StylePy, &h1StylePy))
throw Py::Exception();
// Get the arguments
// Convert all arguments into the right format
if (!Base::Wrapped_ParseTupleAndKeywords(args.ptr(),
keys.ptr(),
"O!|O!sfOOOOOO",
argNames,
&(TopoShapePy::Type),
&pcObjShape,
&(Base::VectorPy::Type),
&pcObjDir,
&extractionTypePy,
&tol,
&vStylePy,
&v0StylePy,
&v1StylePy,
&hStylePy,
&h0StylePy,
&h1StylePy)) {
TopoShapePy* pShape = static_cast<TopoShapePy*>(pcObjShape);
Base::Vector3d directionVector(0,0,1);
if (pcObjDir)
directionVector = static_cast<Base::VectorPy*>(pcObjDir)->value();
if (extractionTypePy && string(extractionTypePy) == "ShowHiddenLines")
extractionType = ProjectionAlgos::WithHidden;
if (vStylePy)
copy(Py::Dict(vStylePy), inserter(vStyle, vStyle.begin()));
if (v0StylePy)
copy(Py::Dict(v0StylePy), inserter(v0Style, v0Style.begin()));
if (v1StylePy)
copy(Py::Dict(v1StylePy), inserter(v1Style, v1Style.begin()));
if (hStylePy)
copy(Py::Dict(hStylePy), inserter(hStyle, hStyle.begin()));
if (h0StylePy)
copy(Py::Dict(h0StylePy), inserter(h0Style, h0Style.begin()));
if (h1StylePy)
copy(Py::Dict(h1StylePy), inserter(h1Style, h1Style.begin()));
// Execute the SVG generation
ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(),
directionVector);
Py::String result(Alg.getSVG(extractionType, tol,
vStyle, v0Style, v1Style,
hStyle, h0Style, h1Style));
return result;
throw Py::Exception();
}
// Convert all arguments into the right format
TopoShapePy* pShape = static_cast<TopoShapePy*>(pcObjShape);
Base::Vector3d directionVector(0, 0, 1);
if (pcObjDir) {
directionVector = static_cast<Base::VectorPy*>(pcObjDir)->value();
}
if (extractionTypePy && string(extractionTypePy) == "ShowHiddenLines") {
extractionType = ProjectionAlgos::WithHidden;
}
if (vStylePy) {
copy(Py::Dict(vStylePy), inserter(vStyle, vStyle.begin()));
}
if (v0StylePy) {
copy(Py::Dict(v0StylePy), inserter(v0Style, v0Style.begin()));
}
if (v1StylePy) {
copy(Py::Dict(v1StylePy), inserter(v1Style, v1Style.begin()));
}
if (hStylePy) {
copy(Py::Dict(hStylePy), inserter(hStyle, hStyle.begin()));
}
if (h0StylePy) {
copy(Py::Dict(h0StylePy), inserter(h0Style, h0Style.begin()));
}
if (h1StylePy) {
copy(Py::Dict(h1StylePy), inserter(h1Style, h1Style.begin()));
}
// Execute the SVG generation
ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(), directionVector);
Py::String result(
Alg.getSVG(extractionType, tol, vStyle, v0Style, v1Style, hStyle, h0Style, h1Style));
return result;
}
Py::Object projectToDXF(const Py::Tuple& args)
{
PyObject *pcObjShape;
PyObject *pcObjDir=nullptr;
const char *type=nullptr;
float scale=1.0f;
float tol=0.1f;
PyObject* pcObjShape;
PyObject* pcObjDir = nullptr;
const char* type = nullptr;
float scale = 1.0f;
float tol = 0.1f;
if (!PyArg_ParseTuple(args.ptr(), "O!|O!sff",
&(TopoShapePy::Type), &pcObjShape,
&(Base::VectorPy::Type), &pcObjDir, &type, &scale, &tol))
if (!PyArg_ParseTuple(args.ptr(),
"O!|O!sff",
&(TopoShapePy::Type),
&pcObjShape,
&(Base::VectorPy::Type),
&pcObjDir,
&type,
&scale,
&tol)) {
throw Py::Exception();
}
TopoShapePy* pShape = static_cast<TopoShapePy*>(pcObjShape);
Base::Vector3d Vector(0,0,1);
if (pcObjDir)
Base::Vector3d Vector(0, 0, 1);
if (pcObjDir) {
Vector = static_cast<Base::VectorPy*>(pcObjDir)->value();
ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(),Vector);
}
ProjectionAlgos Alg(pShape->getTopoShapePtr()->getShape(), Vector);
bool hidden = false;
if (type && std::string(type) == "ShowHiddenLines")
if (type && std::string(type) == "ShowHiddenLines") {
hidden = true;
}
Py::String result(Alg.getDXF(hidden?ProjectionAlgos::WithHidden:ProjectionAlgos::Plain, scale, tol));
Py::String result(
Alg.getDXF(hidden ? ProjectionAlgos::WithHidden : ProjectionAlgos::Plain, scale, tol));
return result;
}
Py::Object removeSvgTags(const Py::Tuple& args)
{
const char* svgcode;
if (!PyArg_ParseTuple(args.ptr(), "s",&svgcode))
if (!PyArg_ParseTuple(args.ptr(), "s", &svgcode)) {
throw Py::Exception();
}
std::string svg(svgcode);
std::string empty = "";
std::string endline = "--endOfLine--";
std::string linebreak = "\\n";
// removing linebreaks for regex to work
boost::regex e1 ("\\n");
boost::regex e1("\\n");
svg = boost::regex_replace(svg, e1, endline);
// removing starting xml definition
boost::regex e2 ("<\\?xml.*?\\?>");
boost::regex e2("<\\?xml.*?\\?>");
svg = boost::regex_replace(svg, e2, empty);
// removing starting svg tag
boost::regex e3 ("<svg.*?>");
boost::regex e3("<svg.*?>");
svg = boost::regex_replace(svg, e3, empty);
// removing sodipodi tags -- DANGEROUS, some sodipodi tags are single, better leave it
//boost::regex e4 ("<sodipodi.*?>");
//svg = boost::regex_replace(svg, e4, empty);
// boost::regex e4 ("<sodipodi.*?>");
// svg = boost::regex_replace(svg, e4, empty);
// removing metadata tags
boost::regex e5 ("<metadata.*?</metadata>");
boost::regex e5("<metadata.*?</metadata>");
svg = boost::regex_replace(svg, e5, empty);
// removing closing svg tags
boost::regex e6 ("</svg>");
boost::regex e6("</svg>");
svg = boost::regex_replace(svg, e6, empty);
// restoring linebreaks
boost::regex e7 ("--endOfLine--");
boost::regex e7("--endOfLine--");
svg = boost::regex_replace(svg, e7, linebreak);
Py::String result(svg);
return result;
@@ -334,4 +381,4 @@ PyObject* initModule()
return Base::Interpreter().addModule(new Module);
}
} // namespace Drawing
}// namespace Drawing

View File

@@ -22,34 +22,34 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <cmath>
# include <sstream>
#include <cmath>
#include <sstream>
# include <Approx_Curve3d.hxx>
# include <BRep_Tool.hxx>
# include <BRepAdaptor_Curve.hxx>
# include <BRepBuilderAPI_MakeEdge.hxx>
# include <BRepLProp_CLProps.hxx>
# include <Geom_BezierCurve.hxx>
# include <Geom_BSplineCurve.hxx>
# include <GeomConvert_BSplineCurveKnotSplitting.hxx>
# include <GeomConvert_BSplineCurveToBezierCurve.hxx>
# include <gp_Circ.hxx>
# include <gp_Dir.hxx>
# include <gp_Elips.hxx>
# include <gp_Pnt.hxx>
# include <gp_Vec.hxx>
# include <Poly_Polygon3D.hxx>
# include <Standard_Failure.hxx>
# include <Standard_Version.hxx>
# include <TColStd_Array1OfReal.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS.hxx>
# include <TopoDS_Edge.hxx>
# include <TopoDS_Shape.hxx>
# if OCC_VERSION_HEX < 0x070600
# include <BRepAdaptor_HCurve.hxx>
# endif
#include <Approx_Curve3d.hxx>
#include <BRepAdaptor_Curve.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepLProp_CLProps.hxx>
#include <BRep_Tool.hxx>
#include <GeomConvert_BSplineCurveKnotSplitting.hxx>
#include <GeomConvert_BSplineCurveToBezierCurve.hxx>
#include <Geom_BSplineCurve.hxx>
#include <Geom_BezierCurve.hxx>
#include <Poly_Polygon3D.hxx>
#include <Standard_Failure.hxx>
#include <Standard_Version.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <TopExp_Explorer.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Shape.hxx>
#include <gp_Circ.hxx>
#include <gp_Dir.hxx>
#include <gp_Elips.hxx>
#include <gp_Pnt.hxx>
#include <gp_Vec.hxx>
#if OCC_VERSION_HEX < 0x070600
#include <BRepAdaptor_HCurve.hxx>
#endif
#endif
#include <Base/Tools.h>
@@ -67,17 +67,17 @@ using namespace std;
TopoDS_Edge DrawingOutput::asCircle(const BRepAdaptor_Curve& c) const
{
double curv=0;
double curv = 0;
gp_Pnt pnt, center;
try {
// approximate the circle center from three positions
BRepLProp_CLProps prop(c,c.FirstParameter(),2,Precision::Confusion());
BRepLProp_CLProps prop(c, c.FirstParameter(), 2, Precision::Confusion());
curv += prop.Curvature();
prop.CentreOfCurvature(pnt);
center.ChangeCoord().Add(pnt.Coord());
prop.SetParameter(0.5*(c.FirstParameter()+c.LastParameter()));
prop.SetParameter(0.5 * (c.FirstParameter() + c.LastParameter()));
curv += prop.Curvature();
prop.CentreOfCurvature(pnt);
center.ChangeCoord().Add(pnt.Coord());
@@ -106,8 +106,9 @@ TopoDS_Edge DrawingOutput::asCircle(const BRepAdaptor_Curve& c) const
for (int i = nodes.Lower(); i <= nodes.Upper(); i++) {
gp_Pnt p = nodes(i);
double dist = p.Distance(center);
if (std::abs(dist - radius) > 0.001)
if (std::abs(dist - radius) > 0.001) {
return TopoDS_Edge();
}
}
gp_Circ circ;
@@ -142,7 +143,7 @@ TopoDS_Edge DrawingOutput::asBSpline(const BRepAdaptor_Curve& c, int maxDegree)
Standard_Integer maxSegment = 50;
Handle(BRepAdaptor_HCurve) hCurve = new BRepAdaptor_HCurve(c);
// approximate the curve using a tolerance
Approx_Curve3d approx(hCurve,tol3D,GeomAbs_C0,maxSegment,maxDegree);
Approx_Curve3d approx(hCurve, tol3D, GeomAbs_C0, maxSegment, maxDegree);
if (approx.IsDone() && approx.HasResult()) {
// have the result
Handle(Geom_BSplineCurve) spline = approx.Curve();
@@ -154,15 +155,14 @@ TopoDS_Edge DrawingOutput::asBSpline(const BRepAdaptor_Curve& c, int maxDegree)
}
SVGOutput::SVGOutput()
{
}
{}
std::string SVGOutput::exportEdges(const TopoDS_Shape& input)
{
std::stringstream result;
TopExp_Explorer edges(input, TopAbs_EDGE);
for (int i = 1 ; edges.More(); edges.Next(),i++) {
for (int i = 1; edges.More(); edges.Next(), i++) {
const TopoDS_Edge& edge = TopoDS::Edge(edges.Current());
BRepAdaptor_Curve adapt(edge);
if (adapt.GetType() == GeomAbs_Circle) {
@@ -172,14 +172,14 @@ std::string SVGOutput::exportEdges(const TopoDS_Shape& input)
printEllipse(adapt, i, result);
}
else if (adapt.GetType() == GeomAbs_BSplineCurve) {
// TopoDS_Edge circle = asCircle(adapt);
// if (circle.IsNull()) {
printBSpline(adapt, i, result);
// }
// else {
// BRepAdaptor_Curve adapt_circle(circle);
// printCircle(adapt_circle, result);
// }
// TopoDS_Edge circle = asCircle(adapt);
// if (circle.IsNull()) {
printBSpline(adapt, i, result);
// }
// else {
// BRepAdaptor_Curve adapt_circle(circle);
// printCircle(adapt_circle, result);
// }
}
else if (adapt.GetType() == GeomAbs_BezierCurve) {
printBezier(adapt, i, result);
@@ -196,81 +196,77 @@ std::string SVGOutput::exportEdges(const TopoDS_Shape& input)
void SVGOutput::printCircle(const BRepAdaptor_Curve& c, std::ostream& out)
{
gp_Circ circ = c.Circle();
const gp_Pnt& p= circ.Location();
const gp_Pnt& p = circ.Location();
double r = circ.Radius();
double f = c.FirstParameter();
double l = c.LastParameter();
gp_Pnt s = c.Value(f);
gp_Pnt m = c.Value((l+f)/2.0);
gp_Pnt m = c.Value((l + f) / 2.0);
gp_Pnt e = c.Value(l);
gp_Vec v1(m,s);
gp_Vec v2(m,e);
gp_Vec v3(0,0,1);
double a = v3.DotCross(v1,v2);
gp_Vec v1(m, s);
gp_Vec v2(m, e);
gp_Vec v3(0, 0, 1);
double a = v3.DotCross(v1, v2);
// a full circle
if (fabs(l-f) > 1.0 && s.SquareDistance(e) < 0.001) {
out << "<circle cx =\"" << p.X() << "\" cy =\""
<< p.Y() << "\" r =\"" << r << "\" />";
if (fabs(l - f) > 1.0 && s.SquareDistance(e) < 0.001) {
out << "<circle cx =\"" << p.X() << "\" cy =\"" << p.Y() << "\" r =\"" << r << "\" />";
}
// arc of circle
else {
// See also https://developer.mozilla.org/en/SVG/Tutorial/Paths
char xar = '0'; // x-axis-rotation
char las = (l-f > D_PI) ? '1' : '0'; // large-arc-flag
char swp = (a < 0) ? '1' : '0'; // sweep-flag, i.e. clockwise (0) or counter-clockwise (1)
out << "<path d=\"M" << s.X() << " " << s.Y()
<< " A" << r << " " << r << " "
<< xar << " " << las << " " << swp << " "
<< e.X() << " " << e.Y() << "\" />";
char xar = '0'; // x-axis-rotation
char las = (l - f > D_PI) ? '1' : '0';// large-arc-flag
char swp = (a < 0) ? '1' : '0';// sweep-flag, i.e. clockwise (0) or counter-clockwise (1)
out << "<path d=\"M" << s.X() << " " << s.Y() << " A" << r << " " << r << " " << xar << " "
<< las << " " << swp << " " << e.X() << " " << e.Y() << "\" />";
}
}
void SVGOutput::printEllipse(const BRepAdaptor_Curve& c, int id, std::ostream& out)
{
gp_Elips ellp = c.Ellipse();
const gp_Pnt& p= ellp.Location();
const gp_Pnt& p = ellp.Location();
double r1 = ellp.MajorRadius();
double r2 = ellp.MinorRadius();
double f = c.FirstParameter();
double l = c.LastParameter();
gp_Pnt s = c.Value(f);
gp_Pnt m = c.Value((l+f)/2.0);
gp_Pnt m = c.Value((l + f) / 2.0);
gp_Pnt e = c.Value(l);
// If the minor radius is very small compared to the major radius
// the geometry actually degenerates to a line
double ratio = std::min(r1,r2)/std::max(r1,r2);
double ratio = std::min(r1, r2) / std::max(r1, r2);
if (ratio < 0.001) {
printGeneric(c, id, out);
return;
}
gp_Vec v1(m,s);
gp_Vec v2(m,e);
gp_Vec v3(0,0,1);
double a = v3.DotCross(v1,v2);
gp_Vec v1(m, s);
gp_Vec v2(m, e);
gp_Vec v3(0, 0, 1);
double a = v3.DotCross(v1, v2);
// a full ellipse
// See also https://developer.mozilla.org/en/SVG/Tutorial/Paths
gp_Dir xaxis = ellp.XAxis().Direction();
Standard_Real angle = xaxis.AngleWithRef(gp_Dir(1,0,0),gp_Dir(0,0,-1));
Standard_Real angle = xaxis.AngleWithRef(gp_Dir(1, 0, 0), gp_Dir(0, 0, -1));
angle = Base::toDegrees<double>(angle);
if (fabs(l-f) > 1.0 && s.SquareDistance(e) < 0.001) {
out << "<g transform = \"rotate(" << angle << "," << p.X() << "," << p.Y() << ")\">" << std::endl;
out << "<ellipse cx =\"" << p.X() << "\" cy =\""
<< p.Y() << "\" rx =\"" << r1 << "\" ry =\"" << r2 << "\"/>" << std::endl;
if (fabs(l - f) > 1.0 && s.SquareDistance(e) < 0.001) {
out << "<g transform = \"rotate(" << angle << "," << p.X() << "," << p.Y() << ")\">"
<< std::endl;
out << "<ellipse cx =\"" << p.X() << "\" cy =\"" << p.Y() << "\" rx =\"" << r1
<< "\" ry =\"" << r2 << "\"/>" << std::endl;
out << "</g>" << std::endl;
}
// arc of ellipse
else {
char las = (l-f > D_PI) ? '1' : '0'; // large-arc-flag
char swp = (a < 0) ? '1' : '0'; // sweep-flag, i.e. clockwise (0) or counter-clockwise (1)
out << "<path d=\"M" << s.X() << " " << s.Y()
<< " A" << r1 << " " << r2 << " "
<< angle << " " << las << " " << swp << " "
<< e.X() << " " << e.Y() << "\" />" << std::endl;
char las = (l - f > D_PI) ? '1' : '0';// large-arc-flag
char swp = (a < 0) ? '1' : '0';// sweep-flag, i.e. clockwise (0) or counter-clockwise (1)
out << "<path d=\"M" << s.X() << " " << s.Y() << " A" << r1 << " " << r2 << " " << angle
<< " " << las << " " << swp << " " << e.X() << " " << e.Y() << "\" />" << std::endl;
}
}
@@ -301,28 +297,27 @@ void SVGOutput::printBezier(const BRepAdaptor_Curve& c, int id, std::ostream& ou
gp_Pnt p1 = bezier->Pole(1);
str << p1.X() << "," << p1.Y();
if (bezier->Degree() == 3) {
if (poles != 4)
if (poles != 4) {
Standard_Failure::Raise("do it the generic way");
}
gp_Pnt p2 = bezier->Pole(2);
gp_Pnt p3 = bezier->Pole(3);
gp_Pnt p4 = bezier->Pole(4);
str << " C"
<< p2.X() << "," << p2.Y() << " "
<< p3.X() << "," << p3.Y() << " "
str << " C" << p2.X() << "," << p2.Y() << " " << p3.X() << "," << p3.Y() << " "
<< p4.X() << "," << p4.Y() << " ";
}
else if (bezier->Degree() == 2) {
if (poles != 3)
if (poles != 3) {
Standard_Failure::Raise("do it the generic way");
}
gp_Pnt p2 = bezier->Pole(2);
gp_Pnt p3 = bezier->Pole(3);
str << " Q"
<< p2.X() << "," << p2.Y() << " "
<< p3.X() << "," << p3.Y() << " ";
str << " Q" << p2.X() << "," << p2.Y() << " " << p3.X() << "," << p3.Y() << " ";
}
else if (bezier->Degree() == 1) {
if (poles != 2)
if (poles != 2) {
Standard_Failure::Raise("do it the generic way");
}
gp_Pnt p2 = bezier->Pole(2);
str << " L" << p2.X() << "," << p2.Y() << " ";
}
@@ -347,11 +342,12 @@ void SVGOutput::printBSpline(const BRepAdaptor_Curve& c, int id, std::ostream& o
Standard_Integer maxDegree = 3, maxSegment = 100;
Handle(BRepAdaptor_HCurve) hCurve = new BRepAdaptor_HCurve(c);
// approximate the curve using a tolerance
Approx_Curve3d approx(hCurve,tol3D,GeomAbs_C0,maxSegment,maxDegree);
Approx_Curve3d approx(hCurve, tol3D, GeomAbs_C0, maxSegment, maxDegree);
if (approx.IsDone() && approx.HasResult()) {
// have the result
spline = approx.Curve();
} else {
}
else {
printGeneric(c, id, out);
return;
}
@@ -359,7 +355,7 @@ void SVGOutput::printBSpline(const BRepAdaptor_Curve& c, int id, std::ostream& o
GeomConvert_BSplineCurveToBezierCurve crt(spline);
Standard_Integer arcs = crt.NbArcs();
str << "<path d=\"M";
for (Standard_Integer i=1; i<=arcs; i++) {
for (Standard_Integer i = 1; i <= arcs; i++) {
Handle(Geom_BezierCurve) bezier = crt.Arc(i);
Standard_Integer poles = bezier->NbPoles();
if (i == 1) {
@@ -367,28 +363,27 @@ void SVGOutput::printBSpline(const BRepAdaptor_Curve& c, int id, std::ostream& o
str << p1.X() << "," << p1.Y();
}
if (bezier->Degree() == 3) {
if (poles != 4)
if (poles != 4) {
Standard_Failure::Raise("do it the generic way");
}
gp_Pnt p2 = bezier->Pole(2);
gp_Pnt p3 = bezier->Pole(3);
gp_Pnt p4 = bezier->Pole(4);
str << " C"
<< p2.X() << "," << p2.Y() << " "
<< p3.X() << "," << p3.Y() << " "
str << " C" << p2.X() << "," << p2.Y() << " " << p3.X() << "," << p3.Y() << " "
<< p4.X() << "," << p4.Y() << " ";
}
else if (bezier->Degree() == 2) {
if (poles != 3)
if (poles != 3) {
Standard_Failure::Raise("do it the generic way");
}
gp_Pnt p2 = bezier->Pole(2);
gp_Pnt p3 = bezier->Pole(3);
str << " Q"
<< p2.X() << "," << p2.Y() << " "
<< p3.X() << "," << p3.Y() << " ";
str << " Q" << p2.X() << "," << p2.Y() << " " << p3.X() << "," << p3.Y() << " ";
}
else if (bezier->Degree() == 1) {
if (poles != 2)
if (poles != 2) {
Standard_Failure::Raise("do it the generic way");
}
gp_Pnt p2 = bezier->Pole(2);
str << " L" << p2.X() << "," << p2.Y() << " ";
}
@@ -412,24 +407,25 @@ void SVGOutput::printGeneric(const BRepAdaptor_Curve& bac, int id, std::ostream&
if (!polygon.IsNull()) {
const TColgp_Array1OfPnt& nodes = polygon->Nodes();
char c = 'M';
out << "<path id= \"" /*<< ViewName*/ << id << "\" d=\" ";
for (int i = nodes.Lower(); i <= nodes.Upper(); i++){
out << c << " " << nodes(i).X() << " " << nodes(i).Y()<< " " ;
out << "<path id= \"" /*<< ViewName*/ << id << "\" d=\" ";
for (int i = nodes.Lower(); i <= nodes.Upper(); i++) {
out << c << " " << nodes(i).X() << " " << nodes(i).Y() << " ";
c = 'L';
}
out << "\" />" << endl;
} else if (bac.GetType() == GeomAbs_Line) {
//BRep_Tool::Polygon3D assumes the edge has polygon representation - ie already been "tessellated"
//this is not true for all edges, especially "floating edges"
}
else if (bac.GetType() == GeomAbs_Line) {
// BRep_Tool::Polygon3D assumes the edge has polygon representation - ie already been
// "tessellated" this is not true for all edges, especially "floating edges"
double f = bac.FirstParameter();
double l = bac.LastParameter();
gp_Pnt s = bac.Value(f);
gp_Pnt e = bac.Value(l);
char c = 'M';
out << "<path id= \"" /*<< ViewName*/ << id << "\" d=\" ";
out << c << " " << s.X() << " " << s.Y()<< " " ;
out << "<path id= \"" /*<< ViewName*/ << id << "\" d=\" ";
out << c << " " << s.X() << " " << s.Y() << " ";
c = 'L';
out << c << " " << e.X() << " " << e.Y()<< " " ;
out << c << " " << e.X() << " " << e.Y() << " ";
out << "\" />" << endl;
}
}
@@ -437,15 +433,14 @@ void SVGOutput::printGeneric(const BRepAdaptor_Curve& bac, int id, std::ostream&
// ----------------------------------------------------------------------------
DXFOutput::DXFOutput()
{
}
{}
std::string DXFOutput::exportEdges(const TopoDS_Shape& input)
{
std::stringstream result;
TopExp_Explorer edges(input, TopAbs_EDGE);
for (int i = 1 ; edges.More(); edges.Next(),i++) {
for (int i = 1; edges.More(); edges.Next(), i++) {
const TopoDS_Edge& edge = TopoDS::Edge(edges.Current());
BRepAdaptor_Curve adapt(edge);
if (adapt.GetType() == GeomAbs_Circle) {
@@ -466,53 +461,52 @@ std::string DXFOutput::exportEdges(const TopoDS_Shape& input)
return result.str();
}
void DXFOutput::printHeader( std::ostream& out)
void DXFOutput::printHeader(std::ostream& out)
{
out << 0 << endl;
out << "SECTION" << endl;
out << 2 << endl;
out << "ENTITIES" << endl;
out << 0 << endl;
out << "SECTION" << endl;
out << 2 << endl;
out << "ENTITIES" << endl;
}
void DXFOutput::printCircle(const BRepAdaptor_Curve& c, std::ostream& out)
{
gp_Circ circ = c.Circle();
//const gp_Ax1& axis = c->Axis();
const gp_Pnt& p= circ.Location();
// const gp_Ax1& axis = c->Axis();
const gp_Pnt& p = circ.Location();
double r = circ.Radius();
double f = c.FirstParameter();
double l = c.LastParameter();
gp_Pnt s = c.Value(f);
gp_Pnt m = c.Value((l+f)/2.0);
gp_Pnt m = c.Value((l + f) / 2.0);
gp_Pnt e = c.Value(l);
gp_Vec v1(m,s);
gp_Vec v2(m,e);
gp_Vec v3(0,0,1);
double a = v3.DotCross(v1,v2);
gp_Vec v1(m, s);
gp_Vec v2(m, e);
gp_Vec v3(0, 0, 1);
double a = v3.DotCross(v1, v2);
// a full circle
if (s.SquareDistance(e) < 0.001) {
//out << "<circle cx =\"" << p.X() << "\" cy =\""
//<< p.Y() << "\" r =\"" << r << "\" />";
out << 0 << endl;
out << "CIRCLE" << endl;
out << 8 << endl; // Group code for layer name
out << "sheet_layer" << endl; // Layer number
out << "100" << endl;
// out << "<circle cx =\"" << p.X() << "\" cy =\""
//<< p.Y() << "\" r =\"" << r << "\" />";
out << 0 << endl;
out << "CIRCLE" << endl;
out << 8 << endl; // Group code for layer name
out << "sheet_layer" << endl;// Layer number
out << "100" << endl;
out << "AcDbEntity" << endl;
out << "100" << endl;
out << "AcDbCircle" << endl;
out << 10 << endl; // Centre X
out << p.X() << endl; // X in WCS coordinates
out << 20 << endl;
out << p.Y() << endl; // Y in WCS coordinates
out << 30 << endl;
out << 0 << endl; // Z in WCS coordinates-leaving flat
out << 40 << endl; //
out << r << endl; // Radius
}
out << "100" << endl;
out << "AcDbCircle" << endl;
out << 10 << endl; // Centre X
out << p.X() << endl;// X in WCS coordinates
out << 20 << endl;
out << p.Y() << endl;// Y in WCS coordinates
out << 30 << endl;
out << 0 << endl; // Z in WCS coordinates-leaving flat
out << 40 << endl;//
out << r << endl; // Radius
}
// arc of circle
@@ -525,121 +519,122 @@ void DXFOutput::printCircle(const BRepAdaptor_Curve& c, std::ostream& out)
<< " A" << r << " " << r << " "
<< xar << " " << las << " " << swp << " "
<< e.X() << " " << e.Y() << "\" />";*/
double ax = s.X() - p.X();
double ay = s.Y() - p.Y();
double bx = e.X() - p.X();
double by = e.Y() - p.Y();
double start_angle = atan2(ay, ax) * 180/D_PI;
double end_angle = atan2(by, bx) * 180/D_PI;
if(a > 0){
double temp = start_angle;
start_angle = end_angle;
end_angle = temp;}
out << 0 << endl;
out << "ARC" << endl;
out << 8 << endl; // Group code for layer name
out << "sheet_layer" << endl; // Layer number
out << "100" << endl;
out << "AcDbEntity" << endl;
out << "100" << endl;
out << "AcDbCircle" << endl;
out << 10 << endl; // Centre X
out << p.X() << endl; // X in WCS coordinates
out << 20 << endl;
out << p.Y() << endl; // Y in WCS coordinates
out << 30 << endl;
out << 0 << endl; // Z in WCS coordinates
out << 40 << endl; //
out << r << endl; // Radius
out << "100" << endl;
out << "AcDbArc" << endl;
out << 50 << endl;
out << start_angle << endl; // Start angle
out << 51 << endl;
out << end_angle << endl; // End angle
double ax = s.X() - p.X();
double ay = s.Y() - p.Y();
double bx = e.X() - p.X();
double by = e.Y() - p.Y();
double start_angle = atan2(ay, ax) * 180 / D_PI;
double end_angle = atan2(by, bx) * 180 / D_PI;
if (a > 0) {
double temp = start_angle;
start_angle = end_angle;
end_angle = temp;
}
out << 0 << endl;
out << "ARC" << endl;
out << 8 << endl; // Group code for layer name
out << "sheet_layer" << endl;// Layer number
out << "100" << endl;
out << "AcDbEntity" << endl;
out << "100" << endl;
out << "AcDbCircle" << endl;
out << 10 << endl; // Centre X
out << p.X() << endl;// X in WCS coordinates
out << 20 << endl;
out << p.Y() << endl;// Y in WCS coordinates
out << 30 << endl;
out << 0 << endl; // Z in WCS coordinates
out << 40 << endl;//
out << r << endl; // Radius
out << "100" << endl;
out << "AcDbArc" << endl;
out << 50 << endl;
out << start_angle << endl;// Start angle
out << 51 << endl;
out << end_angle << endl;// End angle
}
}
void DXFOutput::printEllipse(const BRepAdaptor_Curve& c, int /*id*/, std::ostream& out)
{
gp_Elips ellp = c.Ellipse();
const gp_Pnt& p= ellp.Location();
const gp_Pnt& p = ellp.Location();
double r1 = ellp.MajorRadius();
double r2 = ellp.MinorRadius();
double dp = ellp.Axis().Direction().Dot(gp_Vec(0,0,1));
double dp = ellp.Axis().Direction().Dot(gp_Vec(0, 0, 1));
// a full ellipse
/* if (s.SquareDistance(e) < 0.001) {
out << "<ellipse cx =\"" << p.X() << "\" cy =\""
<< p.Y() << "\" rx =\"" << r1 << "\" ry =\"" << r2 << "\"/>";
/* if (s.SquareDistance(e) < 0.001) {
out << "<ellipse cx =\"" << p.X() << "\" cy =\""
<< p.Y() << "\" rx =\"" << r1 << "\" ry =\"" << r2 << "\"/>";
}
// arc of ellipse
else {
// See also https://developer.mozilla.org/en/SVG/Tutorial/Paths
gp_Dir xaxis = ellp.XAxis().Direction();
Standard_Real angle = xaxis.Angle(gp_Dir(1,0,0));
angle = Base::toDegrees<double>(angle);
char las = (l-f > D_PI) ? '1' : '0'; // large-arc-flag
char swp = (a < 0) ? '1' : '0'; // sweep-flag, i.e. clockwise (0) or counter-clockwise (1)
out << "<path d=\"M" << s.X() << " " << s.Y()
<< " A" << r1 << " " << r2 << " "
<< angle << " " << las << " " << swp << " "
<< e.X() << " " << e.Y() << "\" />";
}*/
gp_Dir xaxis = ellp.XAxis().Direction();
double angle = xaxis.AngleWithRef(gp_Dir(1, 0, 0), gp_Dir(0, 0, -1));
// double rotation = Base::toDegrees<double>(angle);
double start_angle = c.FirstParameter();
double end_angle = c.LastParameter();
double major_x;
double major_y;
major_x = r1 * cos(angle);
major_y = r1 * sin(angle);
double ratio = r2 / r1;
if (dp < 0) {
double temp = start_angle;
start_angle = end_angle;
end_angle = temp;
}
// arc of ellipse
else {
// See also https://developer.mozilla.org/en/SVG/Tutorial/Paths
gp_Dir xaxis = ellp.XAxis().Direction();
Standard_Real angle = xaxis.Angle(gp_Dir(1,0,0));
angle = Base::toDegrees<double>(angle);
char las = (l-f > D_PI) ? '1' : '0'; // large-arc-flag
char swp = (a < 0) ? '1' : '0'; // sweep-flag, i.e. clockwise (0) or counter-clockwise (1)
out << "<path d=\"M" << s.X() << " " << s.Y()
<< " A" << r1 << " " << r2 << " "
<< angle << " " << las << " " << swp << " "
<< e.X() << " " << e.Y() << "\" />";
}*/
gp_Dir xaxis = ellp.XAxis().Direction();
double angle = xaxis.AngleWithRef(gp_Dir(1,0,0),gp_Dir(0,0,-1));
//double rotation = Base::toDegrees<double>(angle);
double start_angle = c.FirstParameter();
double end_angle = c.LastParameter();
double major_x;double major_y;
major_x = r1 * cos(angle);
major_y = r1 * sin(angle);
double ratio = r2/r1;
if(dp < 0){
double temp = start_angle;
start_angle = end_angle;
end_angle = temp;
}
out << 0 << endl;
out << "ELLIPSE" << endl;
out << 8 << endl; // Group code for layer name
out << "sheet_layer" << endl; // Layer number
out << "100" << endl;
out << 0 << endl;
out << "ELLIPSE" << endl;
out << 8 << endl; // Group code for layer name
out << "sheet_layer" << endl;// Layer number
out << "100" << endl;
out << "AcDbEntity" << endl;
out << "100" << endl;
out << "AcDbEllipse" << endl;
out << 10 << endl; // Centre X
out << p.X() << endl; // X in WCS coordinates
out << 20 << endl;
out << p.Y() << endl; // Y in WCS coordinates
out << 30 << endl;
out << 0 << endl; // Z in WCS coordinates
out << 11 << endl; //
out << major_x << endl; // Major X
out << 21 << endl;
out << major_y << endl; // Major Y
out << 31 << endl;
out << 0 << endl; // Major Z
out << 40 << endl; //
out << ratio << endl; // Ratio
out << 41 << endl;
out << start_angle << endl; // Start angle
out << 42 << endl;
out << end_angle << endl; // End angle
out << "100" << endl;
out << "AcDbEllipse" << endl;
out << 10 << endl; // Centre X
out << p.X() << endl;// X in WCS coordinates
out << 20 << endl;
out << p.Y() << endl;// Y in WCS coordinates
out << 30 << endl;
out << 0 << endl; // Z in WCS coordinates
out << 11 << endl; //
out << major_x << endl;// Major X
out << 21 << endl;
out << major_y << endl;// Major Y
out << 31 << endl;
out << 0 << endl; // Major Z
out << 40 << endl; //
out << ratio << endl;// Ratio
out << 41 << endl;
out << start_angle << endl;// Start angle
out << 42 << endl;
out << end_angle << endl;// End angle
}
void DXFOutput::printBSpline(const BRepAdaptor_Curve& c, int id, std::ostream& out) //Not even close yet- DF
void DXFOutput::printBSpline(const BRepAdaptor_Curve& c,
int id,
std::ostream& out)// Not even close yet- DF
{
try {
std::stringstream str;
@@ -648,62 +643,71 @@ void DXFOutput::printBSpline(const BRepAdaptor_Curve& c, int id, std::ostream& o
Standard_Integer maxDegree = 3, maxSegment = 50;
Handle(BRepAdaptor_HCurve) hCurve = new BRepAdaptor_HCurve(c);
// approximate the curve using a tolerance
Approx_Curve3d approx(hCurve,tol3D,GeomAbs_C0,maxSegment,maxDegree);
Approx_Curve3d approx(hCurve, tol3D, GeomAbs_C0, maxSegment, maxDegree);
if (approx.IsDone() && approx.HasResult()) {
// have the result
spline = approx.Curve();
} else {
}
else {
printGeneric(c, id, out);
return;
}
//GeomConvert_BSplineCurveToBezierCurve crt(spline);
//GeomConvert_BSplineCurveKnotSplitting crt(spline,0);
//Standard_Integer arcs = crt.NbArcs();
//Standard_Integer arcs = crt.NbSplits()-1;
// GeomConvert_BSplineCurveToBezierCurve crt(spline);
// GeomConvert_BSplineCurveKnotSplitting crt(spline,0);
// Standard_Integer arcs = crt.NbArcs();
// Standard_Integer arcs = crt.NbSplits()-1;
Standard_Integer m = 0;
if (spline->IsPeriodic()) {
m = spline->NbPoles() + 2*spline->Degree() - spline->Multiplicity(1) + 2;
m = spline->NbPoles() + 2 * spline->Degree() - spline->Multiplicity(1) + 2;
}
else {
for (int i=1; i<= spline->NbKnots(); i++)
for (int i = 1; i <= spline->NbKnots(); i++) {
m += spline->Multiplicity(i);
}
}
TColStd_Array1OfReal knotsequence(1,m);
TColStd_Array1OfReal knotsequence(1, m);
spline->KnotSequence(knotsequence);
TColgp_Array1OfPnt poles(1,spline->NbPoles());
TColgp_Array1OfPnt poles(1, spline->NbPoles());
spline->Poles(poles);
str << 0 << endl
<< "SPLINE" << endl
<< 8 << endl // Group code for layer name
<< "sheet_layer" << endl // Layer name
<< "100" << endl
<< 8 << endl // Group code for layer name
<< "sheet_layer" << endl// Layer name
<< "100" << endl
<< "AcDbEntity" << endl
<< "100" << endl
<< "AcDbSpline" << endl
<< "100" << endl
<< "AcDbSpline" << endl
<< 70 << endl
<< spline->IsRational()*4 << endl //flags
<< 71 << endl << spline->Degree() << endl
<< 72 << endl << knotsequence.Length() << endl
<< 73 << endl << poles.Length() << endl
<< 74 << endl << 0 << endl; //fitpoints
<< spline->IsRational() * 4 << endl// flags
<< 71 << endl
<< spline->Degree() << endl
<< 72 << endl
<< knotsequence.Length() << endl
<< 73 << endl
<< poles.Length() << endl
<< 74 << endl
<< 0 << endl;// fitpoints
for (int i = knotsequence.Lower() ; i <= knotsequence.Upper(); i++) {
for (int i = knotsequence.Lower(); i <= knotsequence.Upper(); i++) {
str << 40 << endl << knotsequence(i) << endl;
}
for (int i = poles.Lower(); i <= poles.Upper(); i++) {
gp_Pnt pole = poles(i);
str << 10 << endl << pole.X() << endl
<< 20 << endl << pole.Y() << endl
<< 30 << endl << pole.Z() << endl;
str << 10 << endl
<< pole.X() << endl
<< 20 << endl
<< pole.Y() << endl
<< 30 << endl
<< pole.Z() << endl;
if (spline->IsRational()) {
str << 41 << endl << spline->Weight(i) << endl;
}
}
//str << "\" />";
// str << "\" />";
out << str.str();
}
catch (Standard_Failure&) {
@@ -723,24 +727,24 @@ void DXFOutput::printGeneric(const BRepAdaptor_Curve& c, int /*id*/, std::ostrea
gp_Vec VE;
c.D1(uEnd, PE, VE);
out << "0" << endl;
out << "LINE" << endl;
out << "8" << endl; // Group code for layer name
out << "sheet_layer" << endl; // Layer name
out << "100" << endl;
out << "0" << endl;
out << "LINE" << endl;
out << "8" << endl; // Group code for layer name
out << "sheet_layer" << endl;// Layer name
out << "100" << endl;
out << "AcDbEntity" << endl;
out << "100" << endl;
out << "AcDbLine" << endl;
out << "10" << endl; // Start point of line
out << PS.X() << endl; // X in WCS coordinates
out << "20" << endl;
out << PS.Y() << endl; // Y in WCS coordinates
out << "30" << endl;
out << "0" << endl; // Z in WCS coordinates
out << "11" << endl; // End point of line
out << PE.X() << endl; // X in WCS coordinates
out << "21" << endl;
out << PE.Y() << endl; // Y in WCS coordinates
out << "31" << endl;
out << "0" << endl; // Z in WCS coordinates
out << "100" << endl;
out << "AcDbLine" << endl;
out << "10" << endl; // Start point of line
out << PS.X() << endl;// X in WCS coordinates
out << "20" << endl;
out << PS.Y() << endl;// Y in WCS coordinates
out << "30" << endl;
out << "0" << endl; // Z in WCS coordinates
out << "11" << endl; // End point of line
out << PE.X() << endl;// X in WCS coordinates
out << "21" << endl;
out << PE.Y() << endl;// Y in WCS coordinates
out << "31" << endl;
out << "0" << endl;// Z in WCS coordinates
}

View File

@@ -23,9 +23,9 @@
#ifndef DRAWING_EXPORT_H
#define DRAWING_EXPORT_H
#include <string>
#include <TopoDS_Edge.hxx>
#include <Mod/Drawing/DrawingGlobal.h>
#include <TopoDS_Edge.hxx>
#include <string>
class TopoDS_Shape;
@@ -43,7 +43,7 @@ public:
TopoDS_Edge asBSpline(const BRepAdaptor_Curve&, int maxDegree) const;
};
class DrawingExport SVGOutput : public DrawingOutput
class DrawingExport SVGOutput: public DrawingOutput
{
public:
SVGOutput();
@@ -58,7 +58,7 @@ private:
};
/* dxf output section - Dan Falck 2011/09/25 */
class DrawingExport DXFOutput : public DrawingOutput
class DrawingExport DXFOutput: public DrawingOutput
{
public:
DXFOutput();
@@ -72,6 +72,6 @@ private:
void printGeneric(const BRepAdaptor_Curve&, int id, std::ostream&);
};
} //namespace Drawing
}// namespace Drawing
#endif // DRAWING_EXPORT_H
#endif// DRAWING_EXPORT_H

View File

@@ -22,8 +22,8 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <iostream>
# include <sstream>
#include <iostream>
#include <sstream>
#endif
#include "FeatureClip.h"
@@ -39,25 +39,50 @@ using namespace std;
PROPERTY_SOURCE(Drawing::FeatureClip, App::DocumentObjectGroup)
FeatureClip::FeatureClip(void)
FeatureClip::FeatureClip(void)
{
static const char *group = "Drawing view";
static const char* group = "Drawing view";
App::PropertyType hidden = (App::PropertyType)(App::Prop_Hidden);
ADD_PROPERTY_TYPE(ViewResult ,(""),group,hidden,"Resulting SVG view of this clip");
ADD_PROPERTY_TYPE(X ,(10),group,App::Prop_None ,"The left margin of the view area of this clip");
ADD_PROPERTY_TYPE(Y ,(10),group,App::Prop_None ,"The top margin of the view area of this clip");
ADD_PROPERTY_TYPE(Height ,(10),group,App::Prop_None ,"The height of the view area of this clip");
ADD_PROPERTY_TYPE(Width ,(10),group,App::Prop_None ,"The width of the view area of this clip");
ADD_PROPERTY_TYPE(ShowFrame ,(0),group,App::Prop_None,"Specifies if the clip frame appears on the page or not");
// The 'Visible' property is handled by the view provider exclusively. It has the 'Output' flag set to
// avoid to call the execute() method. The view provider touches the page object, instead.
App::PropertyType propType = static_cast<App::PropertyType>(App::Prop_Hidden|App::Prop_Output);
ADD_PROPERTY_TYPE(Visible, (true),group,propType,"Control whether frame is visible in page object");
ADD_PROPERTY_TYPE(ViewResult, (""), group, hidden, "Resulting SVG view of this clip");
ADD_PROPERTY_TYPE(X,
(10),
group,
App::Prop_None,
"The left margin of the view area of this clip");
ADD_PROPERTY_TYPE(Y,
(10),
group,
App::Prop_None,
"The top margin of the view area of this clip");
ADD_PROPERTY_TYPE(Height,
(10),
group,
App::Prop_None,
"The height of the view area of this clip");
ADD_PROPERTY_TYPE(Width,
(10),
group,
App::Prop_None,
"The width of the view area of this clip");
ADD_PROPERTY_TYPE(ShowFrame,
(0),
group,
App::Prop_None,
"Specifies if the clip frame appears on the page or not");
// The 'Visible' property is handled by the view provider exclusively. It has the 'Output' flag
// set to avoid to call the execute() method. The view provider touches the page object,
// instead.
App::PropertyType propType =
static_cast<App::PropertyType>(App::Prop_Hidden | App::Prop_Output);
ADD_PROPERTY_TYPE(Visible,
(true),
group,
propType,
"Control whether frame is visible in page object");
}
FeatureClip::~FeatureClip()
{
}
{}
/// get called by the container when a Property was changed
void FeatureClip::onChanged(const App::Property* prop)
@@ -65,7 +90,7 @@ void FeatureClip::onChanged(const App::Property* prop)
App::DocumentObjectGroup::onChanged(prop);
}
App::DocumentObjectExecReturn *FeatureClip::execute(void)
App::DocumentObjectExecReturn* FeatureClip::execute(void)
{
ostringstream svg;
@@ -79,7 +104,7 @@ App::DocumentObjectExecReturn *FeatureClip::execute(void)
// show clip frame on the page if needed
if (ShowFrame.getValue()) {
svg << "<rect fill=\"None\" stroke=\"#ff0000\" stroke-width=\"1px\""
svg << "<rect fill=\"None\" stroke=\"#ff0000\" stroke-width=\"1px\""
<< " x=\"" << X.getValue() << "\""
<< " y=\"" << Y.getValue() << "\""
<< " width=\"" << Width.getValue() << "\""
@@ -90,10 +115,10 @@ App::DocumentObjectExecReturn *FeatureClip::execute(void)
svg << "<g clip-path=\"url(#" << Label.getValue() << ")\">" << endl;
// get through the children and collect all the views
const vector<App::DocumentObject*> &Grp = Group.getValues();
for (vector<App::DocumentObject*>::const_iterator It= Grp.begin();It!=Grp.end();++It) {
const vector<App::DocumentObject*>& Grp = Group.getValues();
for (vector<App::DocumentObject*>::const_iterator It = Grp.begin(); It != Grp.end(); ++It) {
if ((*It)->getTypeId().isDerivedFrom(Drawing::FeatureView::getClassTypeId())) {
Drawing::FeatureView *View = static_cast<Drawing::FeatureView *>(*It);
Drawing::FeatureView* View = static_cast<Drawing::FeatureView*>(*It);
svg << View->ViewResult.getValue() << endl;
}
}

View File

@@ -53,11 +53,12 @@ public:
/** @name methods override Feature */
//@{
/// recalculate the Feature
virtual App::DocumentObjectExecReturn *execute(void);
virtual App::DocumentObjectExecReturn* execute(void);
//@}
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
virtual const char* getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingClip";
}
@@ -66,7 +67,7 @@ protected:
};
} //namespace Drawing
}// namespace Drawing
#endif

View File

@@ -22,20 +22,20 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <fstream>
# include <iostream>
# include <iterator>
# include <sstream>
#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
# include <boost/regex.hpp>
#include <boost/regex.hpp>
#endif
#include <App/Application.h>
#include <Base/Console.h>
#include <Base/FileInfo.h>
#include "FeaturePage.h"
#include "FeatureClip.h"
#include "FeaturePage.h"
#include "FeatureView.h"
@@ -48,18 +48,26 @@ using namespace std;
PROPERTY_SOURCE(Drawing::FeaturePage, App::DocumentObjectGroup)
FeaturePage::FeaturePage(void) : numChildren(0)
FeaturePage::FeaturePage(void)
: numChildren(0)
{
static const char *group = "Drawing view";
static const char* group = "Drawing view";
ADD_PROPERTY_TYPE(PageResult, (nullptr), group, App::Prop_Output, "Resulting SVG document of that page");
ADD_PROPERTY_TYPE(PageResult,
(nullptr),
group,
App::Prop_Output,
"Resulting SVG document of that page");
ADD_PROPERTY_TYPE(Template, (""), group, App::Prop_None, "Template for the page");
ADD_PROPERTY_TYPE(EditableTexts, (""), group, App::Prop_None, "Substitution values for the editable strings in the template");
ADD_PROPERTY_TYPE(EditableTexts,
(""),
group,
App::Prop_None,
"Substitution values for the editable strings in the template");
}
FeaturePage::~FeaturePage()
{
}
{}
void FeaturePage::onBeforeChange(const App::Property* prop)
{
@@ -78,19 +86,23 @@ void FeaturePage::onChanged(const App::Property* prop)
// When loading a document the included file
// doesn't need to exist at this point.
Base::FileInfo fi(PageResult.getValue());
if (!fi.exists())
if (!fi.exists()) {
return;
}
}
} else if (prop == &EditableTexts) {
}
else if (prop == &EditableTexts) {
if (!this->isRestoring()) {
this->execute();
return;
}
} else if (prop == &Template) {
}
else if (prop == &Template) {
if (!this->isRestoring()) {
EditableTexts.setValues(getEditableTextsFromTemplate());
}
} else if (prop == &Group) {
}
else if (prop == &Group) {
if (Group.getSize() != numChildren) {
numChildren = Group.getSize();
touch();
@@ -103,29 +115,33 @@ void FeaturePage::onChanged(const App::Property* prop)
void FeaturePage::onDocumentRestored()
{
// Needs to be tmp. set because otherwise the custom text gets overridden (#0002064)
this->StatusBits.set(App::Restore); // the 'Restore' flag
this->StatusBits.set(App::Restore);// the 'Restore' flag
Base::FileInfo templateInfo(Template.getValue());
if (!templateInfo.exists()) {
Base::FileInfo fi(Template.getValue());
if (fi.fileName().empty())
if (fi.fileName().empty()) {
fi.setFile(PageResult.getValue());
std::string path = App::Application::getResourceDir() + "Mod/Drawing/Templates/" + fi.fileName();
}
std::string path =
App::Application::getResourceDir() + "Mod/Drawing/Templates/" + fi.fileName();
// try to find the template in user dir/Templates first
Base::FileInfo tempfi(App::Application::getUserAppDataDir() + "Templates/" + fi.fileName());
if (tempfi.exists())
if (tempfi.exists()) {
path = tempfi.filePath();
}
Template.setValue(path);
}
this->StatusBits.reset(App::Restore); // the 'Restore' flag
this->StatusBits.reset(App::Restore);// the 'Restore' flag
}
App::DocumentObjectExecReturn *FeaturePage::execute(void)
App::DocumentObjectExecReturn* FeaturePage::execute(void)
{
std::string temp = Template.getValue();
if (temp.empty())
if (temp.empty()) {
return App::DocumentObject::StdReturn;
}
Base::FileInfo fi(temp);
if (!fi.isReadable()) {
@@ -133,54 +149,64 @@ App::DocumentObjectExecReturn *FeaturePage::execute(void)
fi.setFile(App::Application::getResourceDir() + "Mod/Drawing/Templates/" + fi.fileName());
// try the redirect
if (!fi.isReadable()) {
Base::Console().Log("FeaturePage::execute() not able to open %s!\n",Template.getValue());
Base::Console().Log("FeaturePage::execute() not able to open %s!\n",
Template.getValue());
std::string error = std::string("Cannot open file ") + Template.getValue();
return new App::DocumentObjectExecReturn(error);
}
}
if (std::string(PageResult.getValue()).empty())
if (std::string(PageResult.getValue()).empty()) {
PageResult.setValue(fi.filePath().c_str());
}
// open Template file
string line;
ifstream file (fi.filePath().c_str());
ifstream file(fi.filePath().c_str());
// make a temp file for FileIncluded Property
string tempName = PageResult.getExchangeTempFile();
ostringstream ofile;
string tempendl = "--endOfLine--";
while (getline (file,line))
{
while (getline(file, line)) {
// check if the marker in the template is found
if(line.find("<!-- DrawingContent -->") == string::npos)
if (line.find("<!-- DrawingContent -->") == string::npos) {
// if not - write through
ofile << line << tempendl;
else
{
}
else {
// get through the children and collect all the views
const std::vector<App::DocumentObject*> &Grp = Group.getValues();
for (std::vector<App::DocumentObject*>::const_iterator It= Grp.begin();It!=Grp.end();++It) {
if ( (*It)->getTypeId().isDerivedFrom(Drawing::FeatureView::getClassTypeId()) ) {
Drawing::FeatureView *View = static_cast<Drawing::FeatureView *>(*It);
const std::vector<App::DocumentObject*>& Grp = Group.getValues();
for (std::vector<App::DocumentObject*>::const_iterator It = Grp.begin();
It != Grp.end();
++It) {
if ((*It)->getTypeId().isDerivedFrom(Drawing::FeatureView::getClassTypeId())) {
Drawing::FeatureView* View = static_cast<Drawing::FeatureView*>(*It);
if (View->Visible.getValue()) {
ofile << View->ViewResult.getValue();
ofile << tempendl << tempendl << tempendl;
}
} else if ( (*It)->getTypeId().isDerivedFrom(Drawing::FeatureClip::getClassTypeId()) ) {
Drawing::FeatureClip *Clip = static_cast<Drawing::FeatureClip *>(*It);
}
else if ((*It)->getTypeId().isDerivedFrom(Drawing::FeatureClip::getClassTypeId())) {
Drawing::FeatureClip* Clip = static_cast<Drawing::FeatureClip*>(*It);
if (Clip->Visible.getValue()) {
ofile << Clip->ViewResult.getValue();
ofile << tempendl << tempendl << tempendl;
}
} else if ( (*It)->getTypeId().isDerivedFrom(App::DocumentObjectGroup::getClassTypeId()) ) {
}
else if ((*It)->getTypeId().isDerivedFrom(
App::DocumentObjectGroup::getClassTypeId())) {
// getting children inside subgroups too
App::DocumentObjectGroup *SubGroup = static_cast<App::DocumentObjectGroup *>(*It);
const std::vector<App::DocumentObject*> &SubGrp = SubGroup->Group.getValues();
for (std::vector<App::DocumentObject*>::const_iterator Grit= SubGrp.begin();Grit!=SubGrp.end();++Grit) {
if ( (*Grit)->getTypeId().isDerivedFrom(Drawing::FeatureView::getClassTypeId()) ) {
Drawing::FeatureView *SView = static_cast<Drawing::FeatureView *>(*Grit);
App::DocumentObjectGroup* SubGroup =
static_cast<App::DocumentObjectGroup*>(*It);
const std::vector<App::DocumentObject*>& SubGrp = SubGroup->Group.getValues();
for (std::vector<App::DocumentObject*>::const_iterator Grit = SubGrp.begin();
Grit != SubGrp.end();
++Grit) {
if ((*Grit)->getTypeId().isDerivedFrom(
Drawing::FeatureView::getClassTypeId())) {
Drawing::FeatureView* SView = static_cast<Drawing::FeatureView*>(*Grit);
if (SView->Visible.getValue()) {
ofile << SView->ViewResult.getValue();
ofile << tempendl << tempendl << tempendl;
@@ -198,7 +224,7 @@ App::DocumentObjectExecReturn *FeaturePage::execute(void)
string outfragment(ofile.str());
const std::vector<std::string>& editText = EditableTexts.getValues();
if (!editText.empty()) {
boost::regex e1 ("<text.*?freecad:editable=\"(.*?)\".*?<tspan.*?>(.*?)</tspan>");
boost::regex e1("<text.*?freecad:editable=\"(.*?)\".*?<tspan.*?>(.*?)</tspan>");
string::const_iterator begin, end;
begin = outfragment.begin();
end = outfragment.end();
@@ -210,9 +236,14 @@ App::DocumentObjectExecReturn *FeaturePage::execute(void)
while (boost::regex_search(begin, end, what, e1)) {
if (count < editText.size()) {
// change values of editable texts
boost::regex e2 ("(<text.*?freecad:editable=\""+what[1].str()+"\".*?<tspan.*?)>(.*?)(</tspan>)");
boost::regex e2("(<text.*?freecad:editable=\"" + what[1].str()
+ "\".*?<tspan.*?)>(.*?)(</tspan>)");
std::back_insert_iterator<std::string> out(newfragment);
boost::regex_replace(out, begin, what[0].second, e2, "$1>"+editText[count]+"$3");
boost::regex_replace(out,
begin,
what[0].second,
e2,
"$1>" + editText[count] + "$3");
}
count++;
begin = what[0].second;
@@ -224,7 +255,7 @@ App::DocumentObjectExecReturn *FeaturePage::execute(void)
}
// restoring linebreaks and saving the file
boost::regex e3 ("--endOfLine--");
boost::regex e3("--endOfLine--");
string fmt = "\\n";
outfragment = boost::regex_replace(outfragment, e3, fmt);
ofstream outfinal(tempName.c_str());
@@ -236,8 +267,9 @@ App::DocumentObjectExecReturn *FeaturePage::execute(void)
return App::DocumentObject::StdReturn;
}
std::vector<std::string> FeaturePage::getEditableTextsFromTemplate(void) const {
//getting editable texts from "freecad:editable" attributes in SVG template
std::vector<std::string> FeaturePage::getEditableTextsFromTemplate(void) const
{
// getting editable texts from "freecad:editable" attributes in SVG template
std::vector<string> eds;
@@ -246,20 +278,21 @@ std::vector<std::string> FeaturePage::getEditableTextsFromTemplate(void) const {
Base::FileInfo tfi(temp);
if (!tfi.isReadable()) {
// if there is a old absolute template file set use a redirect
tfi.setFile(App::Application::getResourceDir() + "Mod/Drawing/Templates/" + tfi.fileName());
tfi.setFile(App::Application::getResourceDir() + "Mod/Drawing/Templates/"
+ tfi.fileName());
// try the redirect
if (!tfi.isReadable()) {
return eds;
}
}
string tline, tfrag;
ifstream tfile (tfi.filePath().c_str());
while (getline (tfile,tline)) {
ifstream tfile(tfi.filePath().c_str());
while (getline(tfile, tline)) {
tfrag += tline;
tfrag += "--endOfLine--";
}
tfile.close();
boost::regex e ("<text.*?freecad:editable=\"(.*?)\".*?<tspan.*?>(.*?)</tspan>");
boost::regex e("<text.*?freecad:editable=\"(.*?)\".*?<tspan.*?>(.*?)</tspan>");
string::const_iterator tbegin, tend;
tbegin = tfrag.begin();
tend = tfrag.end();

View File

@@ -49,11 +49,12 @@ public:
/** @name methods override Feature */
//@{
/// recalculate the Feature
virtual App::DocumentObjectExecReturn *execute(void);
virtual App::DocumentObjectExecReturn* execute(void);
//@}
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
virtual const char* getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingPage";
}
virtual std::vector<std::string> getEditableTextsFromTemplate(void) const;
@@ -69,7 +70,7 @@ private:
};
} //namespace Drawing
}// namespace Drawing
#endif

View File

@@ -22,11 +22,11 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#include <sstream>
# include <BRep_Builder.hxx>
# include <Standard_Failure.hxx>
# include <TopoDS_Compound.hxx>
#include <BRep_Builder.hxx>
#include <Standard_Failure.hxx>
#include <TopoDS_Compound.hxx>
#endif
#include "FeatureProjection.h"
@@ -37,38 +37,43 @@ using namespace Drawing;
PROPERTY_SOURCE(Drawing::FeatureProjection, Part::Feature)
FeatureProjection::FeatureProjection()
FeatureProjection::FeatureProjection()
{
static const char *group = "Projection";
ADD_PROPERTY_TYPE(Source ,(nullptr),group,App::Prop_None,"Shape to project");
ADD_PROPERTY_TYPE(Direction, (Base::Vector3d(0, 0, 1)), group, App::Prop_None,
static const char* group = "Projection";
ADD_PROPERTY_TYPE(Source, (nullptr), group, App::Prop_None, "Shape to project");
ADD_PROPERTY_TYPE(Direction,
(Base::Vector3d(0, 0, 1)),
group,
App::Prop_None,
"Projection direction");
ADD_PROPERTY_TYPE(VCompound ,(true),group,App::Prop_None,"Projection parameter");
ADD_PROPERTY_TYPE(Rg1LineVCompound ,(true),group,App::Prop_None,"Projection parameter");
ADD_PROPERTY_TYPE(RgNLineVCompound ,(true),group,App::Prop_None,"Projection parameter");
ADD_PROPERTY_TYPE(OutLineVCompound ,(true),group,App::Prop_None,"Projection parameter");
ADD_PROPERTY_TYPE(IsoLineVCompound ,(true),group,App::Prop_None,"Projection parameter");
ADD_PROPERTY_TYPE(HCompound ,(true),group,App::Prop_None,"Projection parameter");
ADD_PROPERTY_TYPE(Rg1LineHCompound ,(true),group,App::Prop_None,"Projection parameter");
ADD_PROPERTY_TYPE(RgNLineHCompound ,(true),group,App::Prop_None,"Projection parameter");
ADD_PROPERTY_TYPE(OutLineHCompound ,(true),group,App::Prop_None,"Projection parameter");
ADD_PROPERTY_TYPE(IsoLineHCompound ,(true),group,App::Prop_None,"Projection parameter");
ADD_PROPERTY_TYPE(VCompound, (true), group, App::Prop_None, "Projection parameter");
ADD_PROPERTY_TYPE(Rg1LineVCompound, (true), group, App::Prop_None, "Projection parameter");
ADD_PROPERTY_TYPE(RgNLineVCompound, (true), group, App::Prop_None, "Projection parameter");
ADD_PROPERTY_TYPE(OutLineVCompound, (true), group, App::Prop_None, "Projection parameter");
ADD_PROPERTY_TYPE(IsoLineVCompound, (true), group, App::Prop_None, "Projection parameter");
ADD_PROPERTY_TYPE(HCompound, (true), group, App::Prop_None, "Projection parameter");
ADD_PROPERTY_TYPE(Rg1LineHCompound, (true), group, App::Prop_None, "Projection parameter");
ADD_PROPERTY_TYPE(RgNLineHCompound, (true), group, App::Prop_None, "Projection parameter");
ADD_PROPERTY_TYPE(OutLineHCompound, (true), group, App::Prop_None, "Projection parameter");
ADD_PROPERTY_TYPE(IsoLineHCompound, (true), group, App::Prop_None, "Projection parameter");
}
FeatureProjection::~FeatureProjection()
{
}
{}
App::DocumentObjectExecReturn *FeatureProjection::execute(void)
App::DocumentObjectExecReturn* FeatureProjection::execute(void)
{
App::DocumentObject* link = Source.getValue();
if (!link)
if (!link) {
return new App::DocumentObjectExecReturn("No object linked");
if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
}
if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
return new App::DocumentObjectExecReturn("Linked object is not a Part object");
}
const TopoDS_Shape& shape = static_cast<Part::Feature*>(link)->Shape.getShape().getShape();
if (shape.IsNull())
if (shape.IsNull()) {
return new App::DocumentObjectExecReturn("Linked shape object is empty");
}
try {
const Base::Vector3d& dir = Direction.getValue();
@@ -77,26 +82,36 @@ App::DocumentObjectExecReturn *FeatureProjection::execute(void)
TopoDS_Compound comp;
BRep_Builder builder;
builder.MakeCompound(comp);
if (!alg.V.IsNull() && VCompound.getValue())
if (!alg.V.IsNull() && VCompound.getValue()) {
builder.Add(comp, alg.V);
if (!alg.V1.IsNull() && Rg1LineVCompound.getValue())
}
if (!alg.V1.IsNull() && Rg1LineVCompound.getValue()) {
builder.Add(comp, alg.V1);
if (!alg.VN.IsNull() && RgNLineVCompound.getValue())
}
if (!alg.VN.IsNull() && RgNLineVCompound.getValue()) {
builder.Add(comp, alg.VN);
if (!alg.VO.IsNull() && OutLineVCompound.getValue())
}
if (!alg.VO.IsNull() && OutLineVCompound.getValue()) {
builder.Add(comp, alg.VO);
if (!alg.VI.IsNull() && IsoLineVCompound.getValue())
}
if (!alg.VI.IsNull() && IsoLineVCompound.getValue()) {
builder.Add(comp, alg.VI);
if (!alg.H.IsNull() && HCompound.getValue())
}
if (!alg.H.IsNull() && HCompound.getValue()) {
builder.Add(comp, alg.H);
if (!alg.H1.IsNull() && Rg1LineHCompound.getValue())
}
if (!alg.H1.IsNull() && Rg1LineHCompound.getValue()) {
builder.Add(comp, alg.H1);
if (!alg.HN.IsNull() && RgNLineHCompound.getValue())
}
if (!alg.HN.IsNull() && RgNLineHCompound.getValue()) {
builder.Add(comp, alg.HN);
if (!alg.HO.IsNull() && OutLineHCompound.getValue())
}
if (!alg.HO.IsNull() && OutLineHCompound.getValue()) {
builder.Add(comp, alg.HO);
if (!alg.HI.IsNull() && IsoLineHCompound.getValue())
}
if (!alg.HI.IsNull() && IsoLineHCompound.getValue()) {
builder.Add(comp, alg.HI);
}
Shape.setValue(comp);
return App::DocumentObject::StdReturn;

View File

@@ -34,7 +34,7 @@ namespace Drawing
/** Base class of all View Features in the drawing module
*/
class DrawingExport FeatureProjection : public Part::Feature
class DrawingExport FeatureProjection: public Part::Feature
{
PROPERTY_HEADER(Drawing::FeatureProjection);
@@ -43,28 +43,27 @@ public:
FeatureProjection();
virtual ~FeatureProjection();
App::PropertyLink Source;
App::PropertyLink Source;
App::PropertyVector Direction;
App::PropertyBool VCompound;
App::PropertyBool Rg1LineVCompound;
App::PropertyBool RgNLineVCompound;
App::PropertyBool OutLineVCompound;
App::PropertyBool IsoLineVCompound;
App::PropertyBool HCompound;
App::PropertyBool Rg1LineHCompound;
App::PropertyBool RgNLineHCompound;
App::PropertyBool OutLineHCompound;
App::PropertyBool IsoLineHCompound;
App::PropertyBool VCompound;
App::PropertyBool Rg1LineVCompound;
App::PropertyBool RgNLineVCompound;
App::PropertyBool OutLineVCompound;
App::PropertyBool IsoLineVCompound;
App::PropertyBool HCompound;
App::PropertyBool Rg1LineHCompound;
App::PropertyBool RgNLineHCompound;
App::PropertyBool OutLineHCompound;
App::PropertyBool IsoLineHCompound;
/** @name methods override feature */
//@{
/// recalculate the Feature
virtual App::DocumentObjectExecReturn *execute(void);
virtual App::DocumentObjectExecReturn* execute(void);
//@}
};
} //namespace Drawing
}// namespace Drawing
#endif // DRAWING_FEATUREPROJECTION
#endif// DRAWING_FEATUREPROJECTION

View File

@@ -22,8 +22,8 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
# include <Standard_Failure.hxx>
#include <Standard_Failure.hxx>
#include <sstream>
#endif
#include <Base/Exception.h>
@@ -40,21 +40,34 @@ using namespace Drawing;
PROPERTY_SOURCE(Drawing::FeatureView, App::DocumentObject)
FeatureView::FeatureView(void)
FeatureView::FeatureView(void)
{
static const char* group = "Drawing view";
ADD_PROPERTY_TYPE(X, (0), group, App::Prop_None,
ADD_PROPERTY_TYPE(X,
(0),
group,
App::Prop_None,
"X position of the view on the drawing in modelling units (mm)");
ADD_PROPERTY_TYPE(Y, (0), group, App::Prop_None,
ADD_PROPERTY_TYPE(Y,
(0),
group,
App::Prop_None,
"Y position of the view on the drawing in modelling units (mm)");
ADD_PROPERTY_TYPE(Scale, (1.0), group, App::Prop_None, "Scale factor of the view");
ADD_PROPERTY_TYPE(Rotation, (0), group, App::Prop_None,
ADD_PROPERTY_TYPE(Rotation,
(0),
group,
App::Prop_None,
"Rotation of the view in degrees counterclockwise");
// The 'Visible' property is handled by the view provider exclusively. It has the 'Output' flag set to
// avoid to call the execute() method. The view provider touches the page object, instead.
// The 'Visible' property is handled by the view provider exclusively. It has the 'Output' flag
// set to avoid to call the execute() method. The view provider touches the page object,
// instead.
App::PropertyType propType =
static_cast<App::PropertyType>(App::Prop_Hidden | App::Prop_Output);
ADD_PROPERTY_TYPE(Visible, (true), group, propType,
ADD_PROPERTY_TYPE(Visible,
(true),
group,
propType,
"Control whether view is visible in page object");
App::PropertyType type = (App::PropertyType)(App::Prop_Hidden);
@@ -62,10 +75,9 @@ FeatureView::FeatureView(void)
}
FeatureView::~FeatureView()
{
}
{}
App::DocumentObjectExecReturn *FeatureView::recompute(void)
App::DocumentObjectExecReturn* FeatureView::recompute(void)
{
try {
return App::DocumentObject::recompute();
@@ -73,12 +85,14 @@ App::DocumentObjectExecReturn *FeatureView::recompute(void)
catch (Standard_Failure& e) {
App::DocumentObjectExecReturn* ret =
new App::DocumentObjectExecReturn(e.GetMessageString());
if (ret->Why.empty()) ret->Why = "Unknown OCC exception";
if (ret->Why.empty()) {
ret->Why = "Unknown OCC exception";
}
return ret;
}
}
App::DocumentObjectExecReturn *FeatureView::execute(void)
App::DocumentObjectExecReturn* FeatureView::execute(void)
{
return App::DocumentObject::StdReturn;
}
@@ -86,14 +100,17 @@ App::DocumentObjectExecReturn *FeatureView::execute(void)
// Python Drawing feature ---------------------------------------------------------
namespace App {
namespace App
{
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Drawing::FeatureViewPython, Drawing::FeatureView)
template<> const char* Drawing::FeatureViewPython::getViewProviderName(void) const {
template<>
const char* Drawing::FeatureViewPython::getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingViewPython";
}
/// @endcond
// explicit template instantiation
template class DrawingExport FeaturePythonT<Drawing::FeatureView>;
}
}// namespace App

View File

@@ -34,7 +34,7 @@ namespace Drawing
/** Base class of all View Features in the drawing module
*/
class DrawingExport FeatureView : public App::DocumentObject
class DrawingExport FeatureView: public App::DocumentObject
{
PROPERTY_HEADER(Drawing::FeatureView);
@@ -43,12 +43,13 @@ public:
FeatureView(void);
virtual ~FeatureView();
App::PropertyFloat X,Y,Scale,Rotation;
App::PropertyFloat X, Y, Scale, Rotation;
App::PropertyString ViewResult;
App::PropertyBool Visible;
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
virtual const char* getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingView";
}
@@ -56,15 +57,14 @@ protected:
/** @name methods override Feature */
//@{
/// recalculate the Feature
virtual App::DocumentObjectExecReturn *recompute(void);
virtual App::DocumentObjectExecReturn *execute(void);
virtual App::DocumentObjectExecReturn* recompute(void);
virtual App::DocumentObjectExecReturn* execute(void);
//@}
};
using FeatureViewPython = App::FeaturePythonT<FeatureView>;
} //namespace Drawing
}// namespace Drawing
#endif

View File

@@ -22,8 +22,8 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <iomanip>
# include <sstream>
#include <iomanip>
#include <sstream>
#endif
#include "FeatureViewAnnotation.h"
@@ -39,36 +39,39 @@ using namespace std;
PROPERTY_SOURCE(Drawing::FeatureViewAnnotation, Drawing::FeatureView)
FeatureViewAnnotation::FeatureViewAnnotation(void)
FeatureViewAnnotation::FeatureViewAnnotation(void)
{
static const char *vgroup = "Drawing view";
static const char* vgroup = "Drawing view";
ADD_PROPERTY_TYPE(Text ,(""),vgroup,App::Prop_None,"The text to be displayed");
ADD_PROPERTY_TYPE(Font ,("Sans"),vgroup,App::Prop_None,"The name of the font to use");
ADD_PROPERTY_TYPE(TextColor, (0.0f, 0.0f, 0.0f), vgroup, App::Prop_None,
ADD_PROPERTY_TYPE(Text, (""), vgroup, App::Prop_None, "The text to be displayed");
ADD_PROPERTY_TYPE(Font, ("Sans"), vgroup, App::Prop_None, "The name of the font to use");
ADD_PROPERTY_TYPE(TextColor,
(0.0f, 0.0f, 0.0f),
vgroup,
App::Prop_None,
"The color of the text");
}
FeatureViewAnnotation::~FeatureViewAnnotation()
{
}
{}
App::DocumentObjectExecReturn *FeatureViewAnnotation::execute(void)
App::DocumentObjectExecReturn* FeatureViewAnnotation::execute(void)
{
stringstream result,hr,hg,hb;
stringstream result, hr, hg, hb;
const App::Color& c = TextColor.getValue();
hr << hex << setfill('0') << setw(2) << (int)(255.0*c.r);
hg << hex << setfill('0') << setw(2) << (int)(255.0*c.g);
hb << hex << setfill('0') << setw(2) << (int)(255.0*c.b);
hr << hex << setfill('0') << setw(2) << (int)(255.0 * c.r);
hg << hex << setfill('0') << setw(2) << (int)(255.0 * c.g);
hb << hex << setfill('0') << setw(2) << (int)(255.0 * c.b);
result << "<g transform=\"translate(" << X.getValue() << "," << Y.getValue() << ")"
<< " rotate(" << Rotation.getValue() << ")\">" << endl
<< "<text id=\"" << Label.getValue() << "\"" << endl
<< " font-family=\"" << Font.getValue() << "\"" << endl
<< " font-size=\"" << Scale.getValue() << "\"" << endl
<< " fill=\"#" << hr.str() << hg.str() << hb.str() << "\">" << endl;
result << "<g transform=\"translate(" << X.getValue() << "," << Y.getValue() << ")"
<< " rotate(" << Rotation.getValue() << ")\">" << endl
<< "<text id=\"" << Label.getValue() << "\"" << endl
<< " font-family=\"" << Font.getValue() << "\"" << endl
<< " font-size=\"" << Scale.getValue() << "\"" << endl
<< " fill=\"#" << hr.str() << hg.str() << hb.str() << "\">" << endl;
for (vector<string>::const_iterator it = Text.getValues().begin(); it != Text.getValues().end(); ++it) {
for (vector<string>::const_iterator it = Text.getValues().begin(); it != Text.getValues().end();
++it) {
result << "<tspan x=\"0\" dy=\"1em\">" << it->c_str() << "</tspan>" << endl;
}
@@ -82,14 +85,17 @@ App::DocumentObjectExecReturn *FeatureViewAnnotation::execute(void)
// Python Drawing feature ---------------------------------------------------------
namespace App {
namespace App
{
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Drawing::FeatureViewAnnotationPython, Drawing::FeatureViewAnnotation)
template<> const char* Drawing::FeatureViewAnnotationPython::getViewProviderName(void) const {
template<>
const char* Drawing::FeatureViewAnnotationPython::getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingView";
}
/// @endcond
// explicit template instantiation
template class DrawingExport FeaturePythonT<Drawing::FeatureViewAnnotation>;
}
}// namespace App

View File

@@ -35,7 +35,7 @@ namespace Drawing
/** Base class of all View Features in the drawing module
*/
class DrawingExport FeatureViewAnnotation : public FeatureView
class DrawingExport FeatureViewAnnotation: public FeatureView
{
PROPERTY_HEADER(Drawing::FeatureView);
@@ -44,18 +44,19 @@ public:
FeatureViewAnnotation(void);
virtual ~FeatureViewAnnotation();
App::PropertyStringList Text;
App::PropertyString Font;
App::PropertyColor TextColor;
App::PropertyStringList Text;
App::PropertyString Font;
App::PropertyColor TextColor;
/** @name methods override Feature */
//@{
/// recalculate the Feature
virtual App::DocumentObjectExecReturn *execute(void);
virtual App::DocumentObjectExecReturn* execute(void);
//@}
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
virtual const char* getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingView";
}
};
@@ -63,7 +64,7 @@ public:
using FeatureViewAnnotationPython = App::FeaturePythonT<FeatureViewAnnotation>;
} //namespace Drawing
}// namespace Drawing
#endif

View File

@@ -22,8 +22,8 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
# include <TopoDS_Shape.hxx>
#include <TopoDS_Shape.hxx>
#include <sstream>
#endif
#include <Mod/Part/App/PartFeature.h>
@@ -44,59 +44,88 @@ App::PropertyFloatConstraint::Constraints FeatureViewPart::floatRange = {0.01, 5
PROPERTY_SOURCE(Drawing::FeatureViewPart, Drawing::FeatureView)
FeatureViewPart::FeatureViewPart(void)
FeatureViewPart::FeatureViewPart(void)
{
static const char *group = "Shape view";
static const char *vgroup = "Drawing view";
static const char* group = "Shape view";
static const char* vgroup = "Drawing view";
ADD_PROPERTY_TYPE(Direction ,(0,0,1.0),group,App::Prop_None,"Projection direction");
ADD_PROPERTY_TYPE(Source ,(nullptr),group,App::Prop_None,"Shape to view");
ADD_PROPERTY_TYPE(ShowHiddenLines ,(false),group,App::Prop_None,"Control the appearance of the dashed hidden lines");
ADD_PROPERTY_TYPE(ShowSmoothLines ,(false),group,App::Prop_None,"Control the appearance of the smooth lines");
ADD_PROPERTY_TYPE(LineWidth,(0.35),vgroup,App::Prop_None,"The thickness of the viewed lines");
ADD_PROPERTY_TYPE(HiddenWidth,(0.15),vgroup,App::Prop_None,"The thickness of the hidden lines, if enabled");
ADD_PROPERTY_TYPE(Tolerance,(0.05),vgroup,App::Prop_None,"The tessellation tolerance");
ADD_PROPERTY_TYPE(Direction, (0, 0, 1.0), group, App::Prop_None, "Projection direction");
ADD_PROPERTY_TYPE(Source, (nullptr), group, App::Prop_None, "Shape to view");
ADD_PROPERTY_TYPE(ShowHiddenLines,
(false),
group,
App::Prop_None,
"Control the appearance of the dashed hidden lines");
ADD_PROPERTY_TYPE(ShowSmoothLines,
(false),
group,
App::Prop_None,
"Control the appearance of the smooth lines");
ADD_PROPERTY_TYPE(LineWidth,
(0.35),
vgroup,
App::Prop_None,
"The thickness of the viewed lines");
ADD_PROPERTY_TYPE(HiddenWidth,
(0.15),
vgroup,
App::Prop_None,
"The thickness of the hidden lines, if enabled");
ADD_PROPERTY_TYPE(Tolerance, (0.05), vgroup, App::Prop_None, "The tessellation tolerance");
Tolerance.setConstraints(&floatRange);
}
FeatureViewPart::~FeatureViewPart()
{
}
{}
App::DocumentObjectExecReturn *FeatureViewPart::execute(void)
App::DocumentObjectExecReturn* FeatureViewPart::execute(void)
{
std::stringstream result;
std::string ViewName = Label.getValue();
App::DocumentObject* link = Source.getValue();
if (!link)
if (!link) {
return new App::DocumentObjectExecReturn("No object linked");
if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()))
}
if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
return new App::DocumentObjectExecReturn("Linked object is not a Part object");
}
TopoDS_Shape shape = static_cast<Part::Feature*>(link)->Shape.getShape().getShape();
if (shape.IsNull())
if (shape.IsNull()) {
return new App::DocumentObjectExecReturn("Linked shape object is empty");
}
Base::Vector3d Dir = Direction.getValue();
bool hidden = ShowHiddenLines.getValue();
bool smooth = ShowSmoothLines.getValue();
try {
ProjectionAlgos Alg(shape,Dir);
result << "<g"
<< " id=\"" << ViewName << "\"" << endl
<< " transform=\"rotate("<< Rotation.getValue() << ","<< X.getValue()<<","<<Y.getValue()<<") translate("<< X.getValue()<<","<<Y.getValue()<<") scale("<< Scale.getValue()<<","<<Scale.getValue()<<")\"" << endl
<< " >" << endl;
ProjectionAlgos Alg(shape, Dir);
result << "<g"
<< " id=\"" << ViewName << "\"" << endl
<< " transform=\"rotate(" << Rotation.getValue() << "," << X.getValue() << ","
<< Y.getValue() << ") translate(" << X.getValue() << "," << Y.getValue()
<< ") scale(" << Scale.getValue() << "," << Scale.getValue() << ")\"" << endl
<< " >" << endl;
ProjectionAlgos::ExtractionType type = ProjectionAlgos::Plain;
if (hidden) type = (ProjectionAlgos::ExtractionType)(type|ProjectionAlgos::WithHidden);
if (smooth) type = (ProjectionAlgos::ExtractionType)(type|ProjectionAlgos::WithSmooth);
if (hidden) {
type = (ProjectionAlgos::ExtractionType)(type | ProjectionAlgos::WithHidden);
}
if (smooth) {
type = (ProjectionAlgos::ExtractionType)(type | ProjectionAlgos::WithSmooth);
}
ProjectionAlgos::XmlAttributes visible_style = {
{"stroke-width", to_string(this->LineWidth.getValue() / this->Scale.getValue())}
};
{"stroke-width", to_string(this->LineWidth.getValue() / this->Scale.getValue())}};
ProjectionAlgos::XmlAttributes hidden_style = {
{"stroke-width", to_string(this->HiddenWidth.getValue() / this->Scale.getValue()) }
};
result << Alg.getSVG(type, this->Tolerance.getValue(), visible_style, visible_style, visible_style, hidden_style, hidden_style, hidden_style);
{"stroke-width", to_string(this->HiddenWidth.getValue() / this->Scale.getValue())}};
result << Alg.getSVG(type,
this->Tolerance.getValue(),
visible_style,
visible_style,
visible_style,
hidden_style,
hidden_style,
hidden_style);
result << "</g>" << endl;
@@ -111,17 +140,19 @@ App::DocumentObjectExecReturn *FeatureViewPart::execute(void)
}
// Python Drawing feature ---------------------------------------------------------
namespace App {
namespace App
{
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Drawing::FeatureViewPartPython, Drawing::FeatureViewPart)
template<> const char* Drawing::FeatureViewPartPython::getViewProviderName(void) const {
template<>
const char* Drawing::FeatureViewPartPython::getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingView";
}
/// @endcond
// explicit template instantiation
template class DrawingExport FeaturePythonT<Drawing::FeatureViewPart>;
}
}// namespace App

View File

@@ -35,7 +35,7 @@ namespace Drawing
/** Base class of all View Features in the drawing module
*/
class DrawingExport FeatureViewPart : public FeatureView
class DrawingExport FeatureViewPart: public FeatureView
{
PROPERTY_HEADER(Part::FeatureViewPart);
@@ -44,23 +44,24 @@ public:
FeatureViewPart(void);
virtual ~FeatureViewPart();
App::PropertyLink Source;
App::PropertyLink Source;
App::PropertyVector Direction;
App::PropertyBool ShowHiddenLines;
App::PropertyBool ShowSmoothLines;
App::PropertyFloat LineWidth;
App::PropertyFloat HiddenWidth;
App::PropertyFloatConstraint Tolerance;
App::PropertyBool ShowHiddenLines;
App::PropertyBool ShowSmoothLines;
App::PropertyFloat LineWidth;
App::PropertyFloat HiddenWidth;
App::PropertyFloatConstraint Tolerance;
/** @name methods override Feature */
//@{
/// recalculate the Feature
virtual App::DocumentObjectExecReturn *execute(void);
virtual App::DocumentObjectExecReturn* execute(void);
//@}
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
virtual const char* getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingView";
}
@@ -71,7 +72,7 @@ private:
using FeatureViewPartPython = App::FeaturePythonT<FeatureViewPart>;
} //namespace Drawing
}// namespace Drawing
#endif

View File

@@ -22,8 +22,8 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <iomanip>
# include <sstream>
#include <iomanip>
#include <sstream>
#endif
#include <App/PropertyUnits.h>
@@ -43,53 +43,67 @@ using namespace Drawing;
PROPERTY_SOURCE(Drawing::FeatureViewSpreadsheet, Drawing::FeatureView)
FeatureViewSpreadsheet::FeatureViewSpreadsheet(void)
FeatureViewSpreadsheet::FeatureViewSpreadsheet(void)
{
static const char *vgroup = "Drawing view";
static const char* vgroup = "Drawing view";
ADD_PROPERTY_TYPE(CellStart ,("A1"),vgroup,App::Prop_None,"The top left cell of the range to display");
ADD_PROPERTY_TYPE(CellEnd ,("B2"),vgroup,App::Prop_None,"The bottom right cell of the range to display");
ADD_PROPERTY_TYPE(Font ,("Sans"),vgroup,App::Prop_None,"The name of the font to use");
ADD_PROPERTY_TYPE(Color,(0.0f,0.0f,0.0f),vgroup,App::Prop_None,"The default color of the text and lines");
ADD_PROPERTY_TYPE(Source ,(nullptr),vgroup,App::Prop_None,"Spreadsheet to view");
ADD_PROPERTY_TYPE(LineWidth,(0.35),vgroup,App::Prop_None,"The thickness of the cell lines");
ADD_PROPERTY_TYPE(FontSize,(12.0),vgroup,App::Prop_None,"The size of the text");
ADD_PROPERTY_TYPE(CellStart,
("A1"),
vgroup,
App::Prop_None,
"The top left cell of the range to display");
ADD_PROPERTY_TYPE(CellEnd,
("B2"),
vgroup,
App::Prop_None,
"The bottom right cell of the range to display");
ADD_PROPERTY_TYPE(Font, ("Sans"), vgroup, App::Prop_None, "The name of the font to use");
ADD_PROPERTY_TYPE(Color,
(0.0f, 0.0f, 0.0f),
vgroup,
App::Prop_None,
"The default color of the text and lines");
ADD_PROPERTY_TYPE(Source, (nullptr), vgroup, App::Prop_None, "Spreadsheet to view");
ADD_PROPERTY_TYPE(LineWidth, (0.35), vgroup, App::Prop_None, "The thickness of the cell lines");
ADD_PROPERTY_TYPE(FontSize, (12.0), vgroup, App::Prop_None, "The size of the text");
}
FeatureViewSpreadsheet::~FeatureViewSpreadsheet()
{
}
{}
App::DocumentObjectExecReturn *FeatureViewSpreadsheet::execute(void)
App::DocumentObjectExecReturn* FeatureViewSpreadsheet::execute(void)
{
// quick tests
App::DocumentObject* link = Source.getValue();
std::string scellstart = CellStart.getValue();
std::string scellend = CellEnd.getValue();
if (!link)
if (!link) {
return new App::DocumentObjectExecReturn("No spreadsheet linked");
if (!link->getTypeId().isDerivedFrom(Spreadsheet::Sheet::getClassTypeId()))
}
if (!link->getTypeId().isDerivedFrom(Spreadsheet::Sheet::getClassTypeId())) {
return new App::DocumentObjectExecReturn("The linked object is not a spreadsheet");
if ( (scellstart.empty()) || (scellend.empty()) )
}
if ((scellstart.empty()) || (scellend.empty())) {
return new App::DocumentObjectExecReturn("Empty cell value");
}
// build a list of available columns: A, B, C, ... AA, AB, ... ZY, ZZ.
std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::vector<std::string> availcolumns;
for (int i=0; i<26; ++i) {
for (int i = 0; i < 26; ++i) {
std::stringstream s;
s << alphabet[i];
availcolumns.push_back(s.str());
}
for (int i=0; i<26; ++i) {
for (int j=0; i<26; ++i) {
for (int i = 0; i < 26; ++i) {
for (int j = 0; i < 26; ++i) {
std::stringstream s;
s << alphabet[i] << alphabet[j];
availcolumns.push_back(s.str());
}
}
// build rows range and columns range
std::vector<std::string> columns;
std::vector<int> rows;
@@ -106,7 +120,8 @@ App::DocumentObjectExecReturn *FeatureViewSpreadsheet::execute(void)
std::string endcol = scellend.substr(0, i);
bool valid = false;
for (std::vector<std::string>::const_iterator j = availcolumns.begin();
j != availcolumns.end(); ++j) {
j != availcolumns.end();
++j) {
if ((*j) == startcol) {
if ((*j) != endcol) {
valid = true;
@@ -130,13 +145,14 @@ App::DocumentObjectExecReturn *FeatureViewSpreadsheet::execute(void)
}
}
}
} catch (std::exception&) {
}
catch (std::exception&) {
return new App::DocumentObjectExecReturn("Invalid cell range");
}
// create the containing group
std::string ViewName = Label.getValue();
std::stringstream result,hr,hg,hb;
std::stringstream result, hr, hg, hb;
const App::Color& c = Color.getValue();
hr << std::hex << std::setfill('0') << std::setw(2) << (int)(255.0 * c.r);
hg << std::hex << std::setfill('0') << std::setw(2) << (int)(255.0 * c.g);
@@ -152,8 +168,8 @@ App::DocumentObjectExecReturn *FeatureViewSpreadsheet::execute(void)
float cellheight = 100;
float cellwidth = 100;
std::string celltext;
Spreadsheet::Sheet* sheet = static_cast<Spreadsheet::Sheet*>(link);
std::vector<std::string> skiplist;
Spreadsheet::Sheet* sheet = static_cast<Spreadsheet::Sheet*>(link);
std::vector<std::string> skiplist;
for (std::vector<std::string>::const_iterator col = columns.begin(); col != columns.end();
++col) {
// create a group for each column
@@ -170,14 +186,18 @@ App::DocumentObjectExecReturn *FeatureViewSpreadsheet::execute(void)
App::Property* prop = sheet->getPropertyByName(address.toString().c_str());
std::stringstream field;
if (prop) {
if (prop->isDerivedFrom((App::PropertyQuantity::getClassTypeId())))
if (prop->isDerivedFrom((App::PropertyQuantity::getClassTypeId()))) {
field << static_cast<App::PropertyQuantity*>(prop)->getValue();
else if (prop->isDerivedFrom((App::PropertyFloat::getClassTypeId())))
}
else if (prop->isDerivedFrom((App::PropertyFloat::getClassTypeId()))) {
field << static_cast<App::PropertyFloat*>(prop)->getValue();
else if (prop->isDerivedFrom((App::PropertyString::getClassTypeId())))
}
else if (prop->isDerivedFrom((App::PropertyString::getClassTypeId()))) {
field << static_cast<App::PropertyString*>(prop)->getValue();
else
}
else {
assert(0);
}
celltext = field.str();
}
// get colors, style, alignment and span
@@ -206,24 +226,30 @@ App::DocumentObjectExecReturn *FeatureViewSpreadsheet::execute(void)
}
if (cell->getStyle(st)) {
for (std::set<std::string>::const_iterator i = st.begin(); i != st.end(); ++i) {
if ((*i) == "bold")
if ((*i) == "bold") {
textstyle = textstyle + "font-weight: bold; ";
else if ((*i) == "italic")
}
else if ((*i) == "italic") {
textstyle = textstyle + "font-style: italic; ";
else if ((*i) == "underline")
}
else if ((*i) == "underline") {
textstyle = textstyle + "text-decoration: underline; ";
}
}
}
if (cell->getSpans(rowspan, colspan)) {
for (int i = 0; i < colspan; ++i) {
for (int j = 0; j < rowspan; ++j) {
App::CellAddress nextcell(address.row() + j, address.col() + i);
if (i > 0)
if (i > 0) {
cellwidth = cellwidth + sheet->getColumnWidth(nextcell.col());
if (j > 0)
}
if (j > 0) {
cellheight = cellheight + sheet->getRowHeight(nextcell.row());
if ((i > 0) || (j > 0))
}
if ((i > 0) || (j > 0)) {
skiplist.push_back(nextcell.toString());
}
}
}
}
@@ -235,18 +261,21 @@ App::DocumentObjectExecReturn *FeatureViewSpreadsheet::execute(void)
<< cellwidth << "\" height=\"" << cellheight << "\" style=\"fill:" << bcolor
<< ";stroke-width:" << LineWidth.getValue() / Scale.getValue() << ";stroke:#"
<< hr.str() << hg.str() << hb.str() << ";\" />" << std::endl;
if (alignment & Spreadsheet::Cell::ALIGNMENT_LEFT)
if (alignment & Spreadsheet::Cell::ALIGNMENT_LEFT) {
result << " <text style=\"" << textstyle << "\" x=\""
<< coloffset + FontSize.getValue() / 2 << "\" y=\""
<< rowoffset + 0.75 * cellheight << "\" font-family=\"";
if (alignment & Spreadsheet::Cell::ALIGNMENT_HCENTER)
}
if (alignment & Spreadsheet::Cell::ALIGNMENT_HCENTER) {
result << " <text text-anchor=\"middle\" style=\"" << textstyle << "\" x=\""
<< coloffset + cellwidth / 2 << "\" y=\""
<< rowoffset + 0.75 * cellheight << "\" font-family=\"";
if (alignment & Spreadsheet::Cell::ALIGNMENT_RIGHT)
}
if (alignment & Spreadsheet::Cell::ALIGNMENT_RIGHT) {
result << " <text text-anchor=\"end\" style=\"" << textstyle << "\" x=\""
<< coloffset + (cellwidth - FontSize.getValue() / 2) << "\" y=\""
<< rowoffset + 0.75 * cellheight << "\" font-family=\"";
}
result << Font.getValue() << "\""
<< " font-size=\"" << FontSize.getValue() << "\""
<< " fill=\"" << fcolor << "\">" << celltext << "</text>" << std::endl;

View File

@@ -34,7 +34,7 @@ namespace Drawing
/** Base class of all View Features in the drawing module
*/
class DrawingExport FeatureViewSpreadsheet : public FeatureView
class DrawingExport FeatureViewSpreadsheet: public FeatureView
{
PROPERTY_HEADER(Drawing::FeatureView);
@@ -42,27 +42,28 @@ public:
/// Constructor
FeatureViewSpreadsheet(void);
virtual ~FeatureViewSpreadsheet();
App::PropertyLink Source;
App::PropertyString CellStart;
App::PropertyString CellEnd;
App::PropertyString Font;
App::PropertyColor Color;
App::PropertyFloat LineWidth;
App::PropertyFloat FontSize;
App::PropertyLink Source;
App::PropertyString CellStart;
App::PropertyString CellEnd;
App::PropertyString Font;
App::PropertyColor Color;
App::PropertyFloat LineWidth;
App::PropertyFloat FontSize;
/** @name methods override Feature */
//@{
/// recalculate the Feature
virtual App::DocumentObjectExecReturn *execute(void);
virtual App::DocumentObjectExecReturn* execute(void);
//@}
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
virtual const char* getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingView";
}
};
} //namespace Drawing
}// namespace Drawing
#endif

View File

@@ -22,11 +22,11 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <iomanip>
# include <iterator>
# include <sstream>
#include <iomanip>
#include <iterator>
#include <sstream>
# include <boost/regex.hpp>
#include <boost/regex.hpp>
#endif
#include "FeatureViewSymbol.h"
@@ -42,18 +42,20 @@ using namespace std;
PROPERTY_SOURCE(Drawing::FeatureViewSymbol, Drawing::FeatureView)
FeatureViewSymbol::FeatureViewSymbol(void)
FeatureViewSymbol::FeatureViewSymbol(void)
{
static const char *vgroup = "Drawing view";
ADD_PROPERTY_TYPE(Symbol,(""),vgroup,App::Prop_Hidden,"The SVG code defining this symbol");
ADD_PROPERTY_TYPE(EditableTexts,(""),vgroup,App::Prop_None,"Substitution values for the editable strings in this symbol");
static const char* vgroup = "Drawing view";
ADD_PROPERTY_TYPE(Symbol, (""), vgroup, App::Prop_Hidden, "The SVG code defining this symbol");
ADD_PROPERTY_TYPE(EditableTexts,
(""),
vgroup,
App::Prop_None,
"Substitution values for the editable strings in this symbol");
}
FeatureViewSymbol::~FeatureViewSymbol()
{
}
{}
/// get called by the container when a Property was changed
void FeatureViewSymbol::onChanged(const App::Property* prop)
@@ -63,7 +65,7 @@ void FeatureViewSymbol::onChanged(const App::Property* prop)
std::vector<string> eds;
std::string svg = Symbol.getValue();
if (!svg.empty()) {
boost::regex e ("<text.*?freecad:editable=\"(.*?)\".*?<tspan.*?>(.*?)</tspan>");
boost::regex e("<text.*?freecad:editable=\"(.*?)\".*?<tspan.*?>(.*?)</tspan>");
std::string::const_iterator tbegin, tend;
tbegin = svg.begin();
tend = svg.end();
@@ -79,13 +81,13 @@ void FeatureViewSymbol::onChanged(const App::Property* prop)
Drawing::FeatureView::onChanged(prop);
}
App::DocumentObjectExecReturn *FeatureViewSymbol::execute(void)
App::DocumentObjectExecReturn* FeatureViewSymbol::execute(void)
{
std::string svg = Symbol.getValue();
const std::vector<std::string>& editText = EditableTexts.getValues();
if (!editText.empty()) {
boost::regex e1 ("<text.*?freecad:editable=\"(.*?)\".*?<tspan.*?>(.*?)</tspan>");
boost::regex e1("<text.*?freecad:editable=\"(.*?)\".*?<tspan.*?>(.*?)</tspan>");
string::const_iterator begin, end;
begin = svg.begin();
end = svg.end();
@@ -98,9 +100,14 @@ App::DocumentObjectExecReturn *FeatureViewSymbol::execute(void)
if (count < editText.size()) {
// change values of editable texts. Also strip the "freecad:editable"
// attribute so it isn't detected by the page
boost::regex e2 ("(<text.*?)(freecad:editable=\""+what[1].str()+"\")(.*?<tspan.*?)>(.*?)(</tspan>)");
boost::regex e2("(<text.*?)(freecad:editable=\"" + what[1].str()
+ "\")(.*?<tspan.*?)>(.*?)(</tspan>)");
std::back_insert_iterator<std::string> out(newsvg);
boost::regex_replace(out, begin, what[0].second, e2, "$1$3>"+editText[count]+"$5");
boost::regex_replace(out,
begin,
what[0].second,
e2,
"$1$3>" + editText[count] + "$5");
}
count++;
begin = what[0].second;
@@ -110,13 +117,13 @@ App::DocumentObjectExecReturn *FeatureViewSymbol::execute(void)
newsvg.insert(newsvg.end(), begin, end);
svg = newsvg;
}
std::stringstream result;
result << "<g transform=\"translate(" << X.getValue() << "," << Y.getValue() << ")"
<< " rotate(" << Rotation.getValue() << ")"
<< " scale(" << Scale.getValue() << ")\">" << endl
<< svg << endl
<< "</g>" << endl;
result << "<g transform=\"translate(" << X.getValue() << "," << Y.getValue() << ")"
<< " rotate(" << Rotation.getValue() << ")"
<< " scale(" << Scale.getValue() << ")\">" << endl
<< svg << endl
<< "</g>" << endl;
// Apply the resulting fragment
ViewResult.setValue(result.str().c_str());
@@ -126,14 +133,17 @@ App::DocumentObjectExecReturn *FeatureViewSymbol::execute(void)
// Python Drawing feature ---------------------------------------------------------
namespace App {
namespace App
{
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(Drawing::FeatureViewSymbolPython, Drawing::FeatureViewSymbol)
template<> const char* Drawing::FeatureViewSymbolPython::getViewProviderName(void) const {
template<>
const char* Drawing::FeatureViewSymbolPython::getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingView";
}
/// @endcond
// explicit template instantiation
template class DrawingExport FeaturePythonT<Drawing::FeatureViewSymbol>;
}
}// namespace App

View File

@@ -35,7 +35,7 @@ namespace Drawing
/** Base class of all View Features in the drawing module
*/
class DrawingExport FeatureViewSymbol : public FeatureView
class DrawingExport FeatureViewSymbol: public FeatureView
{
PROPERTY_HEADER(Drawing::FeatureView);
@@ -44,17 +44,18 @@ public:
FeatureViewSymbol(void);
virtual ~FeatureViewSymbol();
App::PropertyString Symbol;
App::PropertyStringList EditableTexts;
App::PropertyString Symbol;
App::PropertyStringList EditableTexts;
/** @name methods override Feature */
//@{
/// recalculate the Feature
virtual App::DocumentObjectExecReturn *execute(void);
virtual App::DocumentObjectExecReturn* execute(void);
//@}
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
virtual const char* getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawingView";
}
@@ -65,7 +66,7 @@ protected:
using FeatureViewSymbolPython = App::FeaturePythonT<FeatureViewSymbol>;
} //namespace Drawing
}// namespace Drawing
#endif

View File

@@ -22,7 +22,7 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#include <sstream>
#endif
#include "PageGroup.h"
@@ -36,12 +36,11 @@ using namespace Drawing;
PROPERTY_SOURCE(Drawing::PageGroup, App::DocumentObjectGroup)
PageGroup::PageGroup(void)
PageGroup::PageGroup(void)
{
static const char *group = "Drawings";
ADD_PROPERTY_TYPE(Pages,(nullptr),group,App::Prop_None,"List of pages");
static const char* group = "Drawings";
ADD_PROPERTY_TYPE(Pages, (nullptr), group, App::Prop_None, "List of pages");
}
PageGroup::~PageGroup()
{
}
{}

View File

@@ -33,7 +33,7 @@ namespace Drawing
/** Base class of all View Features in the drawing module
*/
class DrawingExport PageGroup : public App::DocumentObjectGroup
class DrawingExport PageGroup: public App::DocumentObjectGroup
{
PROPERTY_HEADER(Drawing::PageGroup);
@@ -45,14 +45,14 @@ public:
App::PropertyLinkList Pages;
/// returns the type name of the ViewProvider
virtual const char* getViewProviderName(void) const {
virtual const char* getViewProviderName(void) const
{
return "DrawingGui::ViewProviderDrawing";
}
};
} //namespace Drawing
}// namespace Drawing
#endif

View File

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

View File

@@ -32,7 +32,6 @@
#include <iomanip>
#include <iostream>
#include <iterator>
#include <iterator>
#include <sstream>
// boost
@@ -40,26 +39,20 @@
// OpenCasCade
#include <Approx_Curve3d.hxx>
#include <BRep_Builder.hxx>
#include <BRep_Tool.hxx>
#include <BRepAdaptor_Curve.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepLProp_CLProps.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include <BRepLib.hxx>
#include <Geom_BezierCurve.hxx>
#include <Geom_BSplineCurve.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include <BRep_Builder.hxx>
#include <BRep_Tool.hxx>
#include <GeomConvert_BSplineCurveKnotSplitting.hxx>
#include <GeomConvert_BSplineCurveToBezierCurve.hxx>
#include <gp_Ax2.hxx>
#include <gp_Circ.hxx>
#include <gp_Dir.hxx>
#include <gp_Elips.hxx>
#include <gp_Pnt.hxx>
#include <gp_Vec.hxx>
#include <Geom_BSplineCurve.hxx>
#include <Geom_BezierCurve.hxx>
#include <HLRAlgo_Projector.hxx>
#include <HLRBRep_Algo.hxx>
#include <HLRBRep_HLRToShape.hxx>
#include <HLRAlgo_Projector.hxx>
#include <Poly_Polygon3D.hxx>
#include <Standard_Failure.hxx>
#include <Standard_Version.hxx>
@@ -69,9 +62,15 @@
#include <TopoDS_Compound.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Shape.hxx>
#include <gp_Ax2.hxx>
#include <gp_Circ.hxx>
#include <gp_Dir.hxx>
#include <gp_Elips.hxx>
#include <gp_Pnt.hxx>
#include <gp_Vec.hxx>
#if OCC_VERSION_HEX < 0x070600
# include <BRepAdaptor_HCurve.hxx>
#include <BRepAdaptor_HCurve.hxx>
#endif
#endif // _PreComp_
#endif// _PreComp_
#endif

View File

@@ -22,25 +22,25 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#include <sstream>
# include <BRepLib.hxx>
# include <BRepMesh_IncrementalMesh.hxx>
# include <gp_Ax2.hxx>
# include <gp_Dir.hxx>
# include <gp_Pnt.hxx>
# include <HLRBRep_Algo.hxx>
# include <HLRBRep_HLRToShape.hxx>
# include <HLRAlgo_Projector.hxx>
# include <TopExp_Explorer.hxx>
# include <TopoDS.hxx>
# include <TopoDS_Shape.hxx>
#include <BRepLib.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include <HLRAlgo_Projector.hxx>
#include <HLRBRep_Algo.hxx>
#include <HLRBRep_HLRToShape.hxx>
#include <TopExp_Explorer.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Shape.hxx>
#include <gp_Ax2.hxx>
#include <gp_Dir.hxx>
#include <gp_Pnt.hxx>
#endif
#include <Base/Exception.h>
#include "ProjectionAlgos.h"
#include "DrawingExport.h"
#include "ProjectionAlgos.h"
using namespace Drawing;
@@ -51,60 +51,61 @@ using namespace std;
//===========================================================================
ProjectionAlgos::ProjectionAlgos(const TopoDS_Shape &Input, const Base::Vector3d &Dir)
: Input(Input), Direction(Dir)
ProjectionAlgos::ProjectionAlgos(const TopoDS_Shape& Input, const Base::Vector3d& Dir)
: Input(Input)
, Direction(Dir)
{
execute();
}
ProjectionAlgos::~ProjectionAlgos()
{
}
{}
//added by tanderson. aka blobfish.
//projection algorithms build a 2d curve(pcurve) but no 3d curve.
//this causes problems with meshing algorithms after save and load.
static const TopoDS_Shape& build3dCurves(const TopoDS_Shape &shape)
// added by tanderson. aka blobfish.
// projection algorithms build a 2d curve(pcurve) but no 3d curve.
// this causes problems with meshing algorithms after save and load.
static const TopoDS_Shape& build3dCurves(const TopoDS_Shape& shape)
{
TopExp_Explorer it;
for (it.Init(shape, TopAbs_EDGE); it.More(); it.Next())
BRepLib::BuildCurve3d(TopoDS::Edge(it.Current()));
return shape;
TopExp_Explorer it;
for (it.Init(shape, TopAbs_EDGE); it.More(); it.Next()) {
BRepLib::BuildCurve3d(TopoDS::Edge(it.Current()));
}
return shape;
}
void ProjectionAlgos::execute(void)
{
Handle( HLRBRep_Algo ) brep_hlr = new HLRBRep_Algo;
Handle(HLRBRep_Algo) brep_hlr = new HLRBRep_Algo;
brep_hlr->Add(Input);
gp_Ax2 transform(gp_Pnt(0,0,0),gp_Dir(Direction.x,Direction.y,Direction.z));
HLRAlgo_Projector projector( transform );
gp_Ax2 transform(gp_Pnt(0, 0, 0), gp_Dir(Direction.x, Direction.y, Direction.z));
HLRAlgo_Projector projector(transform);
brep_hlr->Projector(projector);
brep_hlr->Update();
brep_hlr->Hide();
// extracting the result sets:
HLRBRep_HLRToShape shapes( brep_hlr );
HLRBRep_HLRToShape shapes(brep_hlr);
V = build3dCurves(shapes.VCompound ());// hard edge visibly
V = build3dCurves(shapes.VCompound()); // hard edge visibly
V1 = build3dCurves(shapes.Rg1LineVCompound());// Smoth edges visibly
VN = build3dCurves(shapes.RgNLineVCompound());// contour edges visibly
VO = build3dCurves(shapes.OutLineVCompound());// contours apparents visibly
VI = build3dCurves(shapes.IsoLineVCompound());// isoparamtriques visibly
H = build3dCurves(shapes.HCompound ());// hard edge invisibly
H = build3dCurves(shapes.HCompound()); // hard edge invisibly
H1 = build3dCurves(shapes.Rg1LineHCompound());// Smoth edges invisibly
HN = build3dCurves(shapes.RgNLineHCompound());// contour edges invisibly
HO = build3dCurves(shapes.OutLineHCompound());// contours apparents invisibly
HI = build3dCurves(shapes.IsoLineHCompound());// isoparamtriques invisibly
}
string ProjectionAlgos::getSVG(ExtractionType type,
double tolerance,
XmlAttributes V_style,
XmlAttributes V0_style,
XmlAttributes V1_style,
XmlAttributes H_style,
XmlAttributes H0_style,
string ProjectionAlgos::getSVG(ExtractionType type,
double tolerance,
XmlAttributes V_style,
XmlAttributes V0_style,
XmlAttributes V1_style,
XmlAttributes H_style,
XmlAttributes H0_style,
XmlAttributes H1_style)
{
stringstream result;
@@ -118,14 +119,12 @@ string ProjectionAlgos::getSVG(ExtractionType type,
H_style.insert({"stroke-dasharray", "0.2,0.1)"});
H_style.insert({"fill", "none"});
H_style.insert({"transform", "scale(1,-1)"});
BRepMesh_IncrementalMesh(H,tolerance);
result << "<g";
for (const auto& attribute : H_style)
result << " " << attribute.first << "=\""
<< attribute.second << "\"\n";
result << " >" << endl
<< output.exportEdges(H)
<< "</g>" << endl;
BRepMesh_IncrementalMesh(H, tolerance);
result << "<g";
for (const auto& attribute : H_style) {
result << " " << attribute.first << "=\"" << attribute.second << "\"\n";
}
result << " >" << endl << output.exportEdges(H) << "</g>" << endl;
}
if (!HO.IsNull() && (type & WithHidden)) {
H0_style.insert({"stroke", "rgb(0, 0, 0)"});
@@ -135,14 +134,12 @@ string ProjectionAlgos::getSVG(ExtractionType type,
H0_style.insert({"stroke-dasharray", "0.02,0.1)"});
H0_style.insert({"fill", "none"});
H0_style.insert({"transform", "scale(1,-1)"});
BRepMesh_IncrementalMesh(HO,tolerance);
result << "<g";
for (const auto& attribute : H0_style)
result << " " << attribute.first << "=\""
<< attribute.second << "\"\n";
result << " >" << endl
<< output.exportEdges(HO)
<< "</g>" << endl;
BRepMesh_IncrementalMesh(HO, tolerance);
result << "<g";
for (const auto& attribute : H0_style) {
result << " " << attribute.first << "=\"" << attribute.second << "\"\n";
}
result << " >" << endl << output.exportEdges(HO) << "</g>" << endl;
}
if (!VO.IsNull()) {
V0_style.insert({"stroke", "rgb(0, 0, 0)"});
@@ -151,14 +148,12 @@ string ProjectionAlgos::getSVG(ExtractionType type,
V0_style.insert({"stroke-linejoin", "miter"});
V0_style.insert({"fill", "none"});
V0_style.insert({"transform", "scale(1,-1)"});
BRepMesh_IncrementalMesh(VO,tolerance);
result << "<g";
for (const auto& attribute : V0_style)
result << " " << attribute.first << "=\""
<< attribute.second << "\"\n";
result << " >" << endl
<< output.exportEdges(VO)
<< "</g>" << endl;
BRepMesh_IncrementalMesh(VO, tolerance);
result << "<g";
for (const auto& attribute : V0_style) {
result << " " << attribute.first << "=\"" << attribute.second << "\"\n";
}
result << " >" << endl << output.exportEdges(VO) << "</g>" << endl;
}
if (!V.IsNull()) {
V_style.insert({"stroke", "rgb(0, 0, 0)"});
@@ -167,14 +162,12 @@ string ProjectionAlgos::getSVG(ExtractionType type,
V_style.insert({"stroke-linejoin", "miter"});
V_style.insert({"fill", "none"});
V_style.insert({"transform", "scale(1,-1)"});
BRepMesh_IncrementalMesh(V,tolerance);
result << "<g";
for (const auto& attribute : V_style)
result << " " << attribute.first << "=\""
<< attribute.second << "\"\n";
result << " >" << endl
<< output.exportEdges(V)
<< "</g>" << endl;
BRepMesh_IncrementalMesh(V, tolerance);
result << "<g";
for (const auto& attribute : V_style) {
result << " " << attribute.first << "=\"" << attribute.second << "\"\n";
}
result << " >" << endl << output.exportEdges(V) << "</g>" << endl;
}
if (!V1.IsNull() && (type & WithSmooth)) {
V1_style.insert({"stroke", "rgb(0, 0, 0)"});
@@ -183,14 +176,12 @@ string ProjectionAlgos::getSVG(ExtractionType type,
V1_style.insert({"stroke-linejoin", "miter"});
V1_style.insert({"fill", "none"});
V1_style.insert({"transform", "scale(1,-1)"});
BRepMesh_IncrementalMesh(V1,tolerance);
result << "<g";
for (const auto& attribute : V1_style)
result << " " << attribute.first << "=\""
<< attribute.second << "\"\n";
result << " >" << endl
<< output.exportEdges(V1)
<< "</g>" << endl;
BRepMesh_IncrementalMesh(V1, tolerance);
result << "<g";
for (const auto& attribute : V1_style) {
result << " " << attribute.first << "=\"" << attribute.second << "\"\n";
}
result << " >" << endl << output.exportEdges(V1) << "</g>" << endl;
}
if (!H1.IsNull() && (type & WithSmooth) && (type & WithHidden)) {
H1_style.insert({"stroke", "rgb(0, 0, 0)"});
@@ -200,14 +191,12 @@ string ProjectionAlgos::getSVG(ExtractionType type,
H1_style.insert({"stroke-dasharray", "0.09,0.05)"});
H1_style.insert({"fill", "none"});
H1_style.insert({"transform", "scale(1,-1)"});
BRepMesh_IncrementalMesh(H1,tolerance);
result << "<g";
for (const auto& attribute : H1_style)
result << " " << attribute.first << "=\""
<< attribute.second << "\"\n";
result << " >" << endl
<< output.exportEdges(H1)
<< "</g>" << endl;
BRepMesh_IncrementalMesh(H1, tolerance);
result << "<g";
for (const auto& attribute : H1_style) {
result << " " << attribute.first << "=\"" << attribute.second << "\"\n";
}
result << " >" << endl << output.exportEdges(H1) << "</g>" << endl;
}
return result.str();
}
@@ -220,34 +209,34 @@ string ProjectionAlgos::getDXF(ExtractionType type, double /*scale*/, double tol
DXFOutput output;
if (!H.IsNull() && (type & WithHidden)) {
//float width = 0.15f/scale;
BRepMesh_IncrementalMesh(H,tolerance);
result << output.exportEdges(H);
// float width = 0.15f/scale;
BRepMesh_IncrementalMesh(H, tolerance);
result << output.exportEdges(H);
}
if (!HO.IsNull() && (type & WithHidden)) {
//float width = 0.15f/scale;
BRepMesh_IncrementalMesh(HO,tolerance);
result << output.exportEdges(HO);
// float width = 0.15f/scale;
BRepMesh_IncrementalMesh(HO, tolerance);
result << output.exportEdges(HO);
}
if (!VO.IsNull()) {
//float width = 0.35f/scale;
BRepMesh_IncrementalMesh(VO,tolerance);
result << output.exportEdges(VO);
// float width = 0.35f/scale;
BRepMesh_IncrementalMesh(VO, tolerance);
result << output.exportEdges(VO);
}
if (!V.IsNull()) {
//float width = 0.35f/scale;
BRepMesh_IncrementalMesh(V,tolerance);
result << output.exportEdges(V);
// float width = 0.35f/scale;
BRepMesh_IncrementalMesh(V, tolerance);
result << output.exportEdges(V);
}
if (!V1.IsNull() && (type & WithSmooth)) {
//float width = 0.35f/scale;
BRepMesh_IncrementalMesh(V1,tolerance);
result << output.exportEdges(V1);
// float width = 0.35f/scale;
BRepMesh_IncrementalMesh(V1, tolerance);
result << output.exportEdges(V1);
}
if (!H1.IsNull() && (type & WithSmooth) && (type & WithHidden)) {
//float width = 0.15f/scale;
BRepMesh_IncrementalMesh(H1,tolerance);
result << output.exportEdges(H1);
// float width = 0.15f/scale;
BRepMesh_IncrementalMesh(H1, tolerance);
result << output.exportEdges(H1);
}
return result.str();

View File

@@ -23,8 +23,8 @@
#ifndef _ProjectionAlgos_h_
#define _ProjectionAlgos_h_
#include <string>
#include <TopoDS_Shape.hxx>
#include <string>
#include <Base/Vector3D.h>
#include <Mod/Drawing/DrawingGlobal.h>
@@ -41,44 +41,47 @@ class DrawingExport ProjectionAlgos
{
public:
/// Constructor
ProjectionAlgos(const TopoDS_Shape &Input,const Base::Vector3d &Dir);
ProjectionAlgos(const TopoDS_Shape& Input, const Base::Vector3d& Dir);
virtual ~ProjectionAlgos();
void execute(void);
enum ExtractionType {
enum ExtractionType
{
Plain = 0,
WithHidden = 1,
WithSmooth = 2
};
using XmlAttributes = std::map<std::string,std::string>;
using XmlAttributes = std::map<std::string, std::string>;
std::string getSVG(ExtractionType type, double tolerance=0.05,
XmlAttributes V_style=XmlAttributes(),
XmlAttributes V0_style=XmlAttributes(),
XmlAttributes V1_style=XmlAttributes(),
XmlAttributes H_style=XmlAttributes(),
XmlAttributes H0_style=XmlAttributes(),
XmlAttributes H1_style=XmlAttributes());
std::string getDXF(ExtractionType type, double scale, double tolerance);//added by Dan Falck 2011/09/25
std::string getSVG(ExtractionType type,
double tolerance = 0.05,
XmlAttributes V_style = XmlAttributes(),
XmlAttributes V0_style = XmlAttributes(),
XmlAttributes V1_style = XmlAttributes(),
XmlAttributes H_style = XmlAttributes(),
XmlAttributes H0_style = XmlAttributes(),
XmlAttributes H1_style = XmlAttributes());
std::string
getDXF(ExtractionType type, double scale, double tolerance);// added by Dan Falck 2011/09/25
const TopoDS_Shape &Input;
const Base::Vector3d &Direction;
const TopoDS_Shape& Input;
const Base::Vector3d& Direction;
TopoDS_Shape V ;// hard edge visibly
TopoDS_Shape V; // hard edge visibly
TopoDS_Shape V1;// Smoth edges visibly
TopoDS_Shape VN;// contour edges visibly
TopoDS_Shape VO;// contours apparents visibly
TopoDS_Shape VI;// isoparamtriques visibly
TopoDS_Shape H ;// hard edge invisibly
TopoDS_Shape H; // hard edge invisibly
TopoDS_Shape H1;// Smoth edges invisibly
TopoDS_Shape HN;// contour edges invisibly
TopoDS_Shape HO;// contours apparents invisibly
TopoDS_Shape HI;// isoparamtriques invisibly
};
} //namespace Drawing
}// namespace Drawing
#endif

View File

@@ -63,7 +63,7 @@ INSTALL(
Templates
DESTINATION
${CMAKE_INSTALL_DATADIR}/Mod/Drawing
FILES_MATCHING
FILES_MATCHING
PATTERN "*.svg*"
PATTERN "*.dxf*"
)

View File

@@ -1,62 +1,83 @@
# example how to use the scripting API of the drawing module
#
#
# first of all you need the Part and the Drawing module:
import FreeCAD, Part, Drawing
# create a small sample part
Part.show(Part.makeBox(100,100,100).cut(Part.makeCylinder(80,100)).cut(Part.makeBox(90,40,100)).cut(Part.makeBox(20,85,100)))
Part.show(
Part.makeBox(100, 100, 100)
.cut(Part.makeCylinder(80, 100))
.cut(Part.makeBox(90, 40, 100))
.cut(Part.makeBox(20, 85, 100))
)
# direct projection. The G0 means hard edge, the G1 is tangend continues.
Shape = App.ActiveDocument.Shape.Shape
[visiblyG0,visiblyG1,hiddenG0,hiddenG1] = Drawing.project(Shape)
[visiblyG0, visiblyG1, hiddenG0, hiddenG1] = Drawing.project(Shape)
print("visible edges:", len(visiblyG0.Edges))
print("hidden edges:", len(hiddenG0.Edges))
# all was projected on the Z-plane:
print("Bnd Box shape: X=",Shape.BoundBox.XLength," Y=",Shape.BoundBox.YLength," Z=",Shape.BoundBox.ZLength)
print("Bnd Box project: X=",visiblyG0.BoundBox.XLength," Y=",visiblyG0.BoundBox.YLength," Z=",visiblyG0.BoundBox.ZLength)
print(
"Bnd Box shape: X=",
Shape.BoundBox.XLength,
" Y=",
Shape.BoundBox.YLength,
" Z=",
Shape.BoundBox.ZLength,
)
print(
"Bnd Box project: X=",
visiblyG0.BoundBox.XLength,
" Y=",
visiblyG0.BoundBox.YLength,
" Z=",
visiblyG0.BoundBox.ZLength,
)
# different projection vector
[visiblyG0,visiblyG1,hiddenG0,hiddenG1] = Drawing.project(Shape,Base.Vector(1,1,1))
[visiblyG0, visiblyG1, hiddenG0, hiddenG1] = Drawing.project(Shape, Base.Vector(1, 1, 1))
# project to SVG
resultSVG = Drawing.projectToSVG(Shape,App.Vector(1,1,1))
resultSVG = Drawing.projectToSVG(Shape, App.Vector(1, 1, 1))
print(resultSVG)
# And now the parametric way
#
#
# insert a Page object and assign a template
App.activeDocument().addObject('Drawing::FeaturePage','Page')
App.activeDocument().Page.Template = App.ConfigGet('AppHomePath')+'Mod/Drawing/Templates/A3_Landscape.svg'
App.activeDocument().addObject("Drawing::FeaturePage", "Page")
App.activeDocument().Page.Template = (
App.ConfigGet("AppHomePath") + "Mod/Drawing/Templates/A3_Landscape.svg"
)
# create a view on the "Shape" object, define the position and scale and assign it to a Page
App.activeDocument().addObject('Drawing::FeatureViewPart','View')
App.activeDocument().addObject("Drawing::FeatureViewPart", "View")
App.activeDocument().View.Source = App.activeDocument().Shape
App.activeDocument().View.Direction = (0.0,0.0,1.0)
App.activeDocument().View.Direction = (0.0, 0.0, 1.0)
App.activeDocument().View.X = 10.0
App.activeDocument().View.Y = 10.0
App.activeDocument().Page.addObject(App.activeDocument().View)
# create a second view on the same object but the view is
# create a second view on the same object but the view is
# rotatet 90 degrees.
App.activeDocument().addObject('Drawing::FeatureViewPart','ViewRot')
App.activeDocument().addObject("Drawing::FeatureViewPart", "ViewRot")
App.activeDocument().ViewRot.Source = App.activeDocument().Shape
App.activeDocument().ViewRot.Direction = (0.0,0.0,1.0)
App.activeDocument().ViewRot.Direction = (0.0, 0.0, 1.0)
App.activeDocument().ViewRot.X = 290.0
App.activeDocument().ViewRot.Y = 30.0
App.activeDocument().ViewRot.Scale = 1.0
App.activeDocument().ViewRot.Rotation = 90.0
App.activeDocument().Page.addObject(App.activeDocument().ViewRot)
App.activeDocument().Page.addObject(App.activeDocument().ViewRot)
# create a third view on the same object but with an isometric
# view direction. Also the hidden lines are activated.
App.activeDocument().addObject('Drawing::FeatureViewPart','ViewIso')
App.activeDocument().addObject("Drawing::FeatureViewPart", "ViewIso")
App.activeDocument().ViewIso.Source = App.activeDocument().Shape
App.activeDocument().ViewIso.Direction = (1.0,1.0,1.0)
App.activeDocument().ViewIso.Direction = (1.0, 1.0, 1.0)
App.activeDocument().ViewIso.X = 335.0
App.activeDocument().ViewIso.Y = 140.0
App.activeDocument().ViewIso.ShowHiddenLines = True
App.activeDocument().Page.addObject(App.activeDocument().ViewIso)
App.activeDocument().Page.addObject(App.activeDocument().ViewIso)
# change something and update.
# The update process change the view and the page
@@ -71,14 +92,14 @@ ViewSVG = App.activeDocument().View.ViewResult
print(ViewSVG)
# get the hole result page (its a file in the document temp dir, only read allowed)
print("Resulting SVG document: ",App.activeDocument().Page.PageResult)
file = open(App.activeDocument().Page.PageResult,"r")
print("Result page is ",len(file.readlines())," lines long")
print("Resulting SVG document: ", App.activeDocument().Page.PageResult)
file = open(App.activeDocument().Page.PageResult, "r")
print("Result page is ", len(file.readlines()), " lines long")
# important, give free the file!
del file
# insert a view with your own content:
App.activeDocument().addObject('Drawing::FeatureView','ViewSelf')
App.activeDocument().addObject("Drawing::FeatureView", "ViewSelf")
App.activeDocument().ViewSelf.ViewResult = """<g id="ViewSelf"
stroke="rgb(0, 0, 0)"
stroke-width="0.35"
@@ -95,4 +116,4 @@ App.activeDocument().Page.addObject(App.activeDocument().ViewSelf)
App.activeDocument().recompute()
del Shape,ViewSVG, resultSVG
del Shape, ViewSVG, resultSVG

View File

@@ -29,19 +29,19 @@
// Drawing
#ifndef DrawingExport
#ifdef Drawing_EXPORTS
# define DrawingExport FREECAD_DECL_EXPORT
#define DrawingExport FREECAD_DECL_EXPORT
#else
# define DrawingExport FREECAD_DECL_IMPORT
#define DrawingExport FREECAD_DECL_IMPORT
#endif
#endif
// DrawingGui
#ifndef DrawingGuiExport
#ifdef DrawingGui_EXPORTS
# define DrawingGuiExport FREECAD_DECL_EXPORT
#define DrawingGuiExport FREECAD_DECL_EXPORT
#else
# define DrawingGuiExport FREECAD_DECL_IMPORT
#define DrawingGuiExport FREECAD_DECL_IMPORT
#endif
#endif
#endif //DRAWING_GLOBAL_H
#endif// DRAWING_GLOBAL_H

View File

@@ -1,27 +1,26 @@
#***************************************************************************
#* *
#* (c) Yorik van Havre (yorik@uncreated.net 2015 *
#* *
#* This file is part of the FreeCAD CAx development system. *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* FreeCAD is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Lesser General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with FreeCAD; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#***************************************************************************/
# ***************************************************************************
# * *
# * (c) Yorik van Havre (yorik@uncreated.net 2015 *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************/
"""An SVG patterns generator, able to generate different variants of a pattern
definition, by modifying scale, line thickness and color. The module can generate
@@ -29,7 +28,7 @@ definition, by modifying scale, line thickness and color. The module can generat
be used as image textures."""
# list of available patterns
# fmt: off
Patterns = {
"simple": "M0,0 L10,10",
"line": "M0,5 L10,5",
@@ -132,142 +131,174 @@ AutocadPatterns = {
"TRIANG":"", # small triangles
"ZIGZAG":""
}
# fmt: on
def buildPattern(name, scale=5, thickness=1, color="#000000"):
def buildPattern(name,scale=5,thickness=1,color="#000000"):
"""buildPattern(name,scale=5,thickness=1,color="#000000")
builds an SVG <pattern> fragment from a name and path data"""
name,scale,thickness = decodeName(name,scale,thickness)
name, scale, thickness = decodeName(name, scale, thickness)
if not (name in Patterns):
return None
pname = name + "_" + str(scale).replace(".","") + "_" + str(thickness).replace(".","")
pname = name + "_" + str(scale).replace(".", "") + "_" + str(thickness).replace(".", "")
data = Patterns[name]
template='''<pattern id="$name" patternUnits="userSpaceOnUse"
template = """<pattern id="$name" patternUnits="userSpaceOnUse"
patternTransform="matrix($scale,0,0,$scale,0,0)" x="0" y="0" width="10" height="10">
<g style="fill:none; stroke:$color; stroke-width:$thickness"><path d="$path"/>
</g></pattern>'''
t = template.replace("$name",pname)
t = t.replace("$scale",str(scale))
t = t.replace("$thickness",str(thickness))
t = t.replace("$color",color)
t = t.replace("$path",data)
t = t.replace("\n","")
</g></pattern>"""
t = template.replace("$name", pname)
t = t.replace("$scale", str(scale))
t = t.replace("$thickness", str(thickness))
t = t.replace("$color", color)
t = t.replace("$path", data)
t = t.replace("\n", "")
return t
def buildTextureImage(name,scale=5,thickness=1,color="#000000",size=64):
def buildTextureImage(name, scale=5, thickness=1, color="#000000", size=64):
"""buildTextureImage(name,scale,thickness,color="#000000",size=64)
builds a 64x64 SVG image filled with the given texture"""
name,scale,thickness = decodeName(name,scale,thickness)
name, scale, thickness = decodeName(name, scale, thickness)
if not (name in Patterns):
return None
s = str(size)
template = '''<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
width="'''+s+'''" height="'''+s+'''"><defs>$pattern</defs><rect x="0"
y="$0" width="'''+s+'''" height="'''+s+'''" style="fill:url(#$name);
stroke:none; stroke-width:none"/></svg>'''
pat = buildPattern(name,scale,thickness,color)
t = template.replace("\n","")
t = t.replace("$pattern",pat+"\n")
t = t.replace("$name",name+"_"+str(scale).replace(".","")+"_"+str(thickness).replace(".",""))
template = (
'''<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
width="'''
+ s
+ '''" height="'''
+ s
+ '''"><defs>$pattern</defs><rect x="0"
y="$0" width="'''
+ s
+ '''" height="'''
+ s
+ """" style="fill:url(#$name);
stroke:none; stroke-width:none"/></svg>"""
)
pat = buildPattern(name, scale, thickness, color)
t = template.replace("\n", "")
t = t.replace("$pattern", pat + "\n")
t = t.replace(
"$name", name + "_" + str(scale).replace(".", "") + "_" + str(thickness).replace(".", "")
)
return t
def buildSwatch(name,scale=5,thickness=1,color="#000000",size=64):
def buildSwatch(name, scale=5, thickness=1, color="#000000", size=64):
"""buildSwatch(name,scale,thickness,color="#000000",size=64)
builds a 64x64 SVG image filled with the given texture, a
white background and a border, to serve as a sample"""
name,scale,thickness = decodeName(name,scale,thickness)
name, scale, thickness = decodeName(name, scale, thickness)
if not (name in Patterns):
return None
s = str(size)
template = '''<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
width="'''+s+'''" height="'''+s+'''"><defs>$pattern</defs><rect x="0"
y="$0" width="'''+s+'''" height="'''+s+'''" style="fill:#FFFFFF;
stroke:none; stroke-width:none"/><rect x="0" y="$0" width="'''+s+'''"
height="'''+s+'''" style="fill:url(#$name); stroke:#000000;
stroke-width:2"/></svg>'''
pat = buildPattern(name,scale,thickness,color)
t = template.replace("\n","")
t = t.replace("$pattern",pat+"\n")
t = t.replace("$name",name+"_"+str(scale).replace(".","")+"_"+str(thickness).replace(".",""))
template = (
'''<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
width="'''
+ s
+ '''" height="'''
+ s
+ '''"><defs>$pattern</defs><rect x="0"
y="$0" width="'''
+ s
+ '''" height="'''
+ s
+ '''" style="fill:#FFFFFF;
stroke:none; stroke-width:none"/><rect x="0" y="$0" width="'''
+ s
+ '''"
height="'''
+ s
+ """" style="fill:url(#$name); stroke:#000000;
stroke-width:2"/></svg>"""
)
pat = buildPattern(name, scale, thickness, color)
t = template.replace("\n", "")
t = t.replace("$pattern", pat + "\n")
t = t.replace(
"$name", name + "_" + str(scale).replace(".", "") + "_" + str(thickness).replace(".", "")
)
return t
def buildFileSwatch(name,scale=5,thickness=1,color="#000000",size=64,png=False):
def buildFileSwatch(name, scale=5, thickness=1, color="#000000", size=64, png=False):
"""buildFileSwatch(name,scale,thickness,color="#000000",size=64,png=False)
builds a 64x64 SVG image filled with the given texture, a
white background and a border, to serve as a sample. The image
is saved as a temp file, the filepath is returned"""
s = buildSwatch(name,scale,thickness,color,size)
s = buildSwatch(name, scale, thickness, color, size)
if s:
import tempfile
tf = tempfile.mkstemp(suffix=".svg")[1]
f = open(tf,"wb")
f = open(tf, "wb")
f.write(s)
f.close()
if png:
# we use imagemagick's convert because Qt4 doesn't support SVG patterns...
import os
if os.system("convert -version") == 0:
ptf = os.path.splitext(tf)[0]+".png"
os.system('convert "'+tf+'" "'+ptf+'"')
ptf = os.path.splitext(tf)[0] + ".png"
os.system('convert "' + tf + '" "' + ptf + '"')
return ptf
else:
return tf
return None
def saveTestImage(filename,scales=[2.5,5],thicknesses=[0.1,0.2,1]):
def saveTestImage(filename, scales=[2.5, 5], thicknesses=[0.1, 0.2, 1]):
"""saveTestImage(filename,scales=[2.5,5],thicknesses=[0.1,0.2,1])
builds a test SVG file showing all available patterns at given scales and thicknesses"""
maxcols = 6
row = 0
col = 0
pats = '\n'
cont = '\n'
template = '''<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="$width"
height="$height"><defs>$patterns</defs>$content</svg>'''
pats = "\n"
cont = "\n"
template = """<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="$width"
height="$height"><defs>$patterns</defs>$content</svg>"""
for name in Patterns.keys():
for thickness in thicknesses:
for scale in scales:
pats += buildPattern(name,scale,thickness)
pats += '\n'
subtemplate='''<rect x="$xpos" y="$ypos" width="64" height="64"
style="fill:url(#$pattern); stroke:#000000; stroke-width:2"/>'''
st = subtemplate.replace("$xpos",str(64*col + 8*col + 8))
st = st.replace("$ypos",str(64*row + 8*row + 8))
st = st.replace("$pattern",name+"_"+str(scale)+"_"+str(thickness))
st = st.replace("\n","")
pats += buildPattern(name, scale, thickness)
pats += "\n"
subtemplate = """<rect x="$xpos" y="$ypos" width="64" height="64"
style="fill:url(#$pattern); stroke:#000000; stroke-width:2"/>"""
st = subtemplate.replace("$xpos", str(64 * col + 8 * col + 8))
st = st.replace("$ypos", str(64 * row + 8 * row + 8))
st = st.replace("$pattern", name + "_" + str(scale) + "_" + str(thickness))
st = st.replace("\n", "")
cont += st
cont += '\n'
if col == maxcols-1:
cont += "\n"
if col == maxcols - 1:
col = 0
row += 1
else:
col += 1
t = template.replace("\n","")
t = t.replace("$patterns",pats)
t = t.replace("$content",cont)
t = t.replace("$width",str(8+maxcols*72))
t = t.replace("$height",str(80+row*72))
f = open(filename,"wb")
t = template.replace("\n", "")
t = t.replace("$patterns", pats)
t = t.replace("$content", cont)
t = t.replace("$width", str(8 + maxcols * 72))
t = t.replace("$height", str(80 + row * 72))
f = open(filename, "wb")
f.write(t)
f.close()
def decodeName(name,scale,thickness):
def decodeName(name, scale, thickness):
"""decodeName(name,scale,thickness) : decodes names written in the form 'name_5_1'"""
name = name.split("_")
if len(name) > 1:
try:
@@ -279,11 +310,11 @@ def decodeName(name,scale,thickness):
thickness = float(name[2])
except Exception:
pass
return name[0],scale,thickness
return name[0], scale, thickness
def getPatternNames():
"""getPatternNames : returns available pattern names"""
return Patterns.keys()

View File

@@ -1,35 +1,38 @@
import Part, Drawing
Part.open("D:/_Projekte/FreeCAD/FreeCADData/Schenkel.stp")
App.activeDocument().addObject('Drawing::FeaturePage','Page')
App.activeDocument().Page.Template = 'D:/_Projekte/FreeCAD/FreeCAD_0.9_LibPack7/Mod/Drawing/Templates/A3_Landscape.svg'
App.activeDocument().addObject('Drawing::FeatureViewPart','View')
App.activeDocument().addObject("Drawing::FeaturePage", "Page")
App.activeDocument().Page.Template = (
"D:/_Projekte/FreeCAD/FreeCAD_0.9_LibPack7/Mod/Drawing/Templates/A3_Landscape.svg"
)
App.activeDocument().addObject("Drawing::FeatureViewPart", "View")
App.activeDocument().View.Source = App.activeDocument().Schenkel
App.activeDocument().View.Direction = (0.0,1.0,0.0)
App.activeDocument().View.Direction = (0.0, 1.0, 0.0)
App.activeDocument().View.X = 30.0
App.activeDocument().View.Y = 30.0
App.activeDocument().View.Scale = 1.0
App.activeDocument().Page.addObject(App.activeDocument().View)
App.activeDocument().addObject('Drawing::FeatureViewPart','View1')
App.activeDocument().addObject("Drawing::FeatureViewPart", "View1")
App.activeDocument().View1.Source = App.activeDocument().Schenkel
App.activeDocument().View1.Direction = (0.0,0.0,1.0)
App.activeDocument().View1.Direction = (0.0, 0.0, 1.0)
App.activeDocument().View1.X = 70.0
App.activeDocument().View1.Y = 30.0
App.activeDocument().View1.Scale = 1.0
App.activeDocument().Page.addObject(App.activeDocument().View1)
App.activeDocument().addObject('Drawing::FeatureViewPart','View2')
App.activeDocument().addObject("Drawing::FeatureViewPart", "View2")
App.activeDocument().View2.Source = App.activeDocument().Schenkel
App.activeDocument().View2.Direction = (1.0,0.0,0.0)
App.activeDocument().View2.Direction = (1.0, 0.0, 0.0)
App.activeDocument().View2.X = 70.0
App.activeDocument().View2.Y = 200.0
App.activeDocument().View2.Rotation = 90.0
App.activeDocument().View2.Scale = 1.0
App.activeDocument().Page.addObject(App.activeDocument().View2)
App.activeDocument().addObject('Drawing::FeatureViewPart','View3')
App.activeDocument().addObject("Drawing::FeatureViewPart", "View3")
App.activeDocument().View3.Source = App.activeDocument().Schenkel
App.activeDocument().View3.Direction = (1.0,1.0,1.0)
App.activeDocument().View3.Direction = (1.0, 1.0, 1.0)
App.activeDocument().View3.X = 280.0
App.activeDocument().View3.Y = 90.0
App.activeDocument().View3.Scale = 1.0

View File

@@ -27,9 +27,9 @@
#include <Gui/Application.h>
#include <Gui/Language/Translator.h>
#include "Workbench.h"
#include "ViewProviderPage.h"
#include "ViewProviderView.h"
#include "Workbench.h"
// use a different name to CreateCommand()
@@ -43,7 +43,8 @@ void loadDrawingResource()
Gui::Translator::instance()->refresh();
}
namespace DrawingGui {
namespace DrawingGui
{
extern PyObject* initModule();
}

View File

@@ -22,9 +22,9 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#include <sstream>
# include <QFileInfo>
#include <QFileInfo>
#endif
#include <App/DocumentObjectPy.h>
@@ -42,41 +42,42 @@
#include "DrawingView.h"
namespace DrawingGui {
class Module : public Py::ExtensionModule<Module>
namespace DrawingGui
{
class Module: public Py::ExtensionModule<Module>
{
public:
Module() : Py::ExtensionModule<Module>("DrawingGui")
Module()
: Py::ExtensionModule<Module>("DrawingGui")
{
add_varargs_method("open",&Module::open
);
add_varargs_method("insert",&Module::importer
);
add_varargs_method("export",&Module::exporter
);
initialize("This module is the DrawingGui module."); // register with Python
add_varargs_method("open", &Module::open);
add_varargs_method("insert", &Module::importer);
add_varargs_method("export", &Module::exporter);
initialize("This module is the DrawingGui module.");// register with Python
}
virtual ~Module() {}
virtual ~Module()
{}
private:
virtual Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args)
virtual Py::Object invoke_method_varargs(void* method_def, const Py::Tuple& args)
{
try {
return Py::ExtensionModule<Module>::invoke_method_varargs(method_def, args);
}
catch (const Base::Exception &e) {
catch (const Base::Exception& e) {
throw Py::RuntimeError(e.what());
}
catch (const std::exception &e) {
catch (const std::exception& e) {
throw Py::RuntimeError(e.what());
}
}
Py::Object open(const Py::Tuple& args)
{
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "et","utf-8",&Name))
if (!PyArg_ParseTuple(args.ptr(), "et", "utf-8", &Name)) {
throw Py::Exception();
}
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
@@ -90,7 +91,7 @@ private:
view->setWindowIcon(Gui::BitmapFactory().pixmap("actions/drawing-landscape"));
QFileInfo fi(fileName);
view->setWindowTitle(fi.fileName());
view->resize( 400, 300 );
view->resize(400, 300);
Gui::getMainWindow()->addWindow(view);
}
else {
@@ -103,8 +104,9 @@ private:
{
char* Name;
const char* dummy;
if (!PyArg_ParseTuple(args.ptr(), "et|s","utf-8",&Name,&dummy))
if (!PyArg_ParseTuple(args.ptr(), "et|s", "utf-8", &Name, &dummy)) {
throw Py::Exception();
}
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
@@ -118,9 +120,10 @@ private:
view->setWindowIcon(Gui::BitmapFactory().pixmap("actions/drawing-landscape"));
QFileInfo fi(fileName);
view->setWindowTitle(fi.fileName());
view->resize( 400, 300 );
view->resize(400, 300);
Gui::getMainWindow()->addWindow(view);
} else {
}
else {
throw Py::Exception(PyExc_IOError, "unknown filetype");
}
@@ -130,8 +133,9 @@ private:
{
PyObject* object;
char* Name;
if (!PyArg_ParseTuple(args.ptr(), "Oet",&object,"utf-8",&Name))
if (!PyArg_ParseTuple(args.ptr(), "Oet", &object, "utf-8", &Name)) {
throw Py::Exception();
}
std::string EncodedName = std::string(Name);
PyMem_Free(Name);
@@ -140,7 +144,8 @@ private:
for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) {
PyObject* item = (*it).ptr();
if (PyObject_TypeCheck(item, &(App::DocumentObjectPy::Type))) {
App::DocumentObject* obj = static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
App::DocumentObject* obj =
static_cast<App::DocumentObjectPy*>(item)->getDocumentObjectPtr();
if (obj->getTypeId().isDerivedFrom(Drawing::FeaturePage::getClassTypeId())) {
Base::FileInfo fi_out(EncodedName.c_str());
Base::ofstream str_out(fi_out, std::ios::out | std::ios::binary);
@@ -150,7 +155,8 @@ private:
throw Py::Exception(PyExc_IOError, str.str().c_str());
}
if (fi_out.hasExtension("svg")) {
std::string fn = static_cast<Drawing::FeaturePage*>(obj)->PageResult.getValue();
std::string fn =
static_cast<Drawing::FeaturePage*>(obj)->PageResult.getValue();
Base::FileInfo fi_in(fn);
Base::ifstream str_in(fi_in, std::ios::in | std::ios::binary);
if (!str_in) {
@@ -165,31 +171,45 @@ private:
break;
}
else if (fi_out.hasExtension("dxf")) {
const std::vector<App::DocumentObject*>& views = static_cast<Drawing::FeaturePage*>(obj)->Group.getValues();
for (std::vector<App::DocumentObject*>::const_iterator it = views.begin(); it != views.end(); ++it) {
if ((*it)->getTypeId().isDerivedFrom(Drawing::FeatureViewPart::getClassTypeId())) {
Drawing::FeatureViewPart* view = static_cast<Drawing::FeatureViewPart*>(*it);
const std::vector<App::DocumentObject*>& views =
static_cast<Drawing::FeaturePage*>(obj)->Group.getValues();
for (std::vector<App::DocumentObject*>::const_iterator it = views.begin();
it != views.end();
++it) {
if ((*it)->getTypeId().isDerivedFrom(
Drawing::FeatureViewPart::getClassTypeId())) {
Drawing::FeatureViewPart* view =
static_cast<Drawing::FeatureViewPart*>(*it);
App::DocumentObject* link = view->Source.getValue();
if (!link) {
throw Py::ValueError("No object linked");
}
if (!link->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
if (!link->getTypeId().isDerivedFrom(
Part::Feature::getClassTypeId())) {
throw Py::TypeError("Linked object is not a Part object");
}
TopoDS_Shape shape = static_cast<Part::Feature*>(link)->Shape.getShape().getShape();
TopoDS_Shape shape =
static_cast<Part::Feature*>(link)->Shape.getShape().getShape();
if (!shape.IsNull()) {
Base::Vector3d dir = view->Direction.getValue();
bool hidden = view->ShowHiddenLines.getValue();
bool smooth = view->ShowSmoothLines.getValue();
Drawing::ProjectionAlgos::ExtractionType type = Drawing::ProjectionAlgos::Plain;
if (hidden) type = (Drawing::ProjectionAlgos::ExtractionType)(type|Drawing::ProjectionAlgos::WithHidden);
if (smooth) type = (Drawing::ProjectionAlgos::ExtractionType)(type|Drawing::ProjectionAlgos::WithSmooth);
Drawing::ProjectionAlgos::ExtractionType type =
Drawing::ProjectionAlgos::Plain;
if (hidden) {
type = (Drawing::ProjectionAlgos::ExtractionType)(
type | Drawing::ProjectionAlgos::WithHidden);
}
if (smooth) {
type = (Drawing::ProjectionAlgos::ExtractionType)(
type | Drawing::ProjectionAlgos::WithSmooth);
}
float scale = view->Scale.getValue();
float tol = view->Tolerance.getValue();
Drawing::ProjectionAlgos project(shape, dir);
str_out << project.getDXF(type, scale, tol);
break; // TODO: How to add several shapes?
break;// TODO: How to add several shapes?
}
}
}
@@ -197,11 +217,13 @@ private:
break;
}
else {
throw Py::TypeError("Export of page object as this file format is not supported by Drawing module");
throw Py::TypeError("Export of page object as this file format is not "
"supported by Drawing module");
}
}
else {
throw Py::TypeError("Export of this object type is not supported by Drawing module");
throw Py::TypeError(
"Export of this object type is not supported by Drawing module");
}
}
}
@@ -215,4 +237,4 @@ PyObject* initModule()
return Base::Interpreter().addModule(new Module);
}
} // namespace DrawingGui
}// namespace DrawingGui

View File

@@ -11,15 +11,15 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
# include <vector>
#include <sstream>
#include <vector>
# include <QCoreApplication>
# include <QDir>
# include <QFile>
# include <QFileInfo>
# include <QMessageBox>
# include <QRegExp>
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QMessageBox>
#include <QRegExp>
#endif
#include <App/Document.h>
@@ -52,25 +52,27 @@ using namespace std;
DEF_STD_CMD(CmdDrawingOpen)
CmdDrawingOpen::CmdDrawingOpen()
: Command("Drawing_Open")
: Command("Drawing_Open")
{
sAppModule = "Drawing";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Open SVG...");
sToolTipText = QT_TR_NOOP("Open a scalable vector graphic");
sWhatsThis = "Drawing_Open";
sStatusTip = sToolTipText;
sPixmap = "actions/document-new";
sAppModule = "Drawing";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Open SVG...");
sToolTipText = QT_TR_NOOP("Open a scalable vector graphic");
sWhatsThis = "Drawing_Open";
sStatusTip = sToolTipText;
sPixmap = "actions/document-new";
}
void CmdDrawingOpen::activated(int iMsg)
{
Q_UNUSED(iMsg);
// Reading an image
QString filename = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), QObject::tr("Choose an SVG file to open"), QString(),
QString filename = Gui::FileDialog::getOpenFileName(
Gui::getMainWindow(),
QObject::tr("Choose an SVG file to open"),
QString(),
QString::fromLatin1("%1 (*.svg *.svgz)").arg(QObject::tr("Scalable Vector Graphic")));
if (!filename.isEmpty())
{
if (!filename.isEmpty()) {
filename = Base::Tools::escapeEncodeFilename(filename);
// load the file with the module
Command::doCommand(Command::Gui, "import Drawing, DrawingGui");
@@ -85,14 +87,14 @@ void CmdDrawingOpen::activated(int iMsg)
DEF_STD_CMD_ACL(CmdDrawingNewPage)
CmdDrawingNewPage::CmdDrawingNewPage()
: Command("Drawing_NewPage")
: Command("Drawing_NewPage")
{
sAppModule = "Drawing";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Insert new drawing");
sToolTipText = QT_TR_NOOP("Insert new drawing");
sWhatsThis = "Drawing_NewPage";
sStatusTip = sToolTipText;
sAppModule = "Drawing";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Insert new drawing");
sToolTipText = QT_TR_NOOP("Insert new drawing");
sWhatsThis = "Drawing_NewPage";
sStatusTip = sToolTipText;
}
void CmdDrawingNewPage::activated(int iMsg)
@@ -101,26 +103,31 @@ void CmdDrawingNewPage::activated(int iMsg)
QAction* a = qAsConst(pcAction)->actions()[iMsg];
std::string FeatName = getUniqueObjectName(
QCoreApplication::translate("Drawing_NewPage", "Page").toStdString().c_str());
QCoreApplication::translate("Drawing_NewPage", "Page").toStdString().c_str());
QFileInfo tfi(a->property("Template").toString());
if (tfi.isReadable()) {
QString filename = Base::Tools::escapeEncodeFilename(tfi.filePath());
openCommand("Create page");
doCommand(Doc,"App.activeDocument().addObject('Drawing::FeaturePage','%s')",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.Template = '%s'",FeatName.c_str(), (const char*)filename.toUtf8());
doCommand(Doc,"App.activeDocument().recompute()");
doCommand(Doc,"Gui.activeDocument().getObject('%s').show()",FeatName.c_str());
doCommand(Doc,
"App.activeDocument().addObject('Drawing::FeaturePage','%s')",
FeatName.c_str());
doCommand(Doc,
"App.activeDocument().%s.Template = '%s'",
FeatName.c_str(),
(const char*)filename.toUtf8());
doCommand(Doc, "App.activeDocument().recompute()");
doCommand(Doc, "Gui.activeDocument().getObject('%s').show()", FeatName.c_str());
commitCommand();
}
else {
QMessageBox::critical(Gui::getMainWindow(),
QLatin1String("No template"),
QLatin1String("No template available for this page size"));
QLatin1String("No template"),
QLatin1String("No template available for this page size"));
}
}
Gui::Action * CmdDrawingNewPage::createAction(void)
Gui::Action* CmdDrawingNewPage::createAction(void)
{
Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow());
pcAction->setDropDownMenu(true);
@@ -135,7 +142,7 @@ Gui::Action * CmdDrawingNewPage::createAction(void)
std::string path = App::Application::getResourceDir();
path += "Mod/Drawing/Templates/";
QDir dir(QString::fromUtf8(path.c_str()), QString::fromLatin1("*.svg"));
for (unsigned int i=0; i<dir.count(); i++ ) {
for (unsigned int i = 0; i < dir.count(); i++) {
QRegExp rx(QString::fromLatin1("(A|B|C|D|E)(\\d)_(Landscape|Portrait)(_.*\\.|\\.)svg$"));
if (rx.indexIn(dir[i]) > -1) {
QString paper = rx.cap(1);
@@ -162,11 +169,13 @@ Gui::Action * CmdDrawingNewPage::createAction(void)
lastPaper = paper;
lastId = id;
QFile file(QString::fromLatin1(":/icons/actions/drawing-%1-%2%3.svg").arg(orientation.toLower(), paper).arg(id));
QFile file(QString::fromLatin1(":/icons/actions/drawing-%1-%2%3.svg")
.arg(orientation.toLower(), paper)
.arg(id));
QAction* a = pcAction->addAction(QString());
if (file.open(QFile::ReadOnly)) {
QByteArray data = file.readAll();
a->setIcon(Gui::BitmapFactory().pixmapFromSvg(data, QSize(64,64)));
a->setIcon(Gui::BitmapFactory().pixmapFromSvg(data, QSize(64, 64)));
}
a->setProperty("TemplatePaper", paper);
@@ -204,57 +213,51 @@ void CmdDrawingNewPage::languageChange()
{
Command::languageChange();
if (!_pcAction)
if (!_pcAction) {
return;
}
Gui::ActionGroup* pcAction = qobject_cast<Gui::ActionGroup*>(_pcAction);
QList<QAction*> a = pcAction->actions();
for (QList<QAction*>::iterator it = a.begin(); it != a.end(); ++it) {
if ((*it)->isSeparator())
if ((*it)->isSeparator()) {
continue;
}
QString paper = (*it)->property("TemplatePaper").toString();
int id = (*it)->property("TemplateId").toInt();
QString orientation = (*it)->property("TemplateOrientation").toString();
if (orientation.compare(QLatin1String("landscape"), Qt::CaseInsensitive) == 0)
if (orientation.compare(QLatin1String("landscape"), Qt::CaseInsensitive) == 0) {
orientation = QCoreApplication::translate("Drawing_NewPage", "Landscape");
else if (orientation.compare(QLatin1String("portrait"), Qt::CaseInsensitive) == 0)
}
else if (orientation.compare(QLatin1String("portrait"), Qt::CaseInsensitive) == 0) {
orientation = QCoreApplication::translate("Drawing_NewPage", "Portrait");
}
QString info = (*it)->property("TemplateInfo").toString();
if (info.isEmpty()) {
(*it)->setText(QCoreApplication::translate(
"Drawing_NewPage", "%1%2 %3")
.arg(paper,
QString::number(id),
orientation));
(*it)->setToolTip(QCoreApplication::translate(
"Drawing_NewPage", "Insert new %1%2 %3 drawing")
.arg(paper,
QString::number(id),
orientation));
(*it)->setText(QCoreApplication::translate("Drawing_NewPage", "%1%2 %3")
.arg(paper, QString::number(id), orientation));
(*it)->setToolTip(
QCoreApplication::translate("Drawing_NewPage", "Insert new %1%2 %3 drawing")
.arg(paper, QString::number(id), orientation));
}
else {
(*it)->setText(QCoreApplication::translate(
"Drawing_NewPage", "%1%2 %3 (%4)")
.arg(paper,
QString::number(id),
orientation,
info));
(*it)->setToolTip(QCoreApplication::translate(
"Drawing_NewPage", "Insert new %1%2 %3 (%4) drawing")
.arg(paper,
QString::number(id),
orientation,
info));
(*it)->setText(QCoreApplication::translate("Drawing_NewPage", "%1%2 %3 (%4)")
.arg(paper, QString::number(id), orientation, info));
(*it)->setToolTip(
QCoreApplication::translate("Drawing_NewPage", "Insert new %1%2 %3 (%4) drawing")
.arg(paper, QString::number(id), orientation, info));
}
}
}
bool CmdDrawingNewPage::isActive(void)
{
if (getActiveGuiDocument())
if (getActiveGuiDocument()) {
return true;
else
}
else {
return false;
}
}
//===========================================================================
@@ -264,15 +267,15 @@ bool CmdDrawingNewPage::isActive(void)
DEF_STD_CMD_A(CmdDrawingNewA3Landscape)
CmdDrawingNewA3Landscape::CmdDrawingNewA3Landscape()
: Command("Drawing_NewA3Landscape")
: Command("Drawing_NewA3Landscape")
{
sAppModule = "Drawing";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Insert new A3 landscape drawing");
sToolTipText = QT_TR_NOOP("Insert new A3 landscape drawing");
sWhatsThis = "Drawing_NewA3Landscape";
sStatusTip = sToolTipText;
sPixmap = "actions/drawing-landscape-A3";
sAppModule = "Drawing";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Insert new A3 landscape drawing");
sToolTipText = QT_TR_NOOP("Insert new A3 landscape drawing");
sWhatsThis = "Drawing_NewA3Landscape";
sStatusTip = sToolTipText;
sPixmap = "actions/drawing-landscape-A3";
}
void CmdDrawingNewA3Landscape::activated(int iMsg)
@@ -281,18 +284,20 @@ void CmdDrawingNewA3Landscape::activated(int iMsg)
std::string FeatName = getUniqueObjectName("Page");
openCommand("Create page");
doCommand(Doc,"App.activeDocument().addObject('Drawing::FeaturePage','%s')",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.Template = 'A3_Landscape.svg'",FeatName.c_str());
doCommand(Doc,"App.activeDocument().recompute()");
doCommand(Doc, "App.activeDocument().addObject('Drawing::FeaturePage','%s')", FeatName.c_str());
doCommand(Doc, "App.activeDocument().%s.Template = 'A3_Landscape.svg'", FeatName.c_str());
doCommand(Doc, "App.activeDocument().recompute()");
commitCommand();
}
bool CmdDrawingNewA3Landscape::isActive(void)
{
if (getActiveGuiDocument())
if (getActiveGuiDocument()) {
return true;
else
}
else {
return false;
}
}
@@ -303,45 +308,51 @@ bool CmdDrawingNewA3Landscape::isActive(void)
DEF_STD_CMD(CmdDrawingNewView)
CmdDrawingNewView::CmdDrawingNewView()
: Command("Drawing_NewView")
: Command("Drawing_NewView")
{
sAppModule = "Drawing";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Insert view in drawing");
sToolTipText = QT_TR_NOOP("Insert a new View of a Part in the active drawing");
sWhatsThis = "Drawing_NewView";
sStatusTip = sToolTipText;
sPixmap = "actions/drawing-view";
sAppModule = "Drawing";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Insert view in drawing");
sToolTipText = QT_TR_NOOP("Insert a new View of a Part in the active drawing");
sWhatsThis = "Drawing_NewView";
sStatusTip = sToolTipText;
sPixmap = "actions/drawing-view";
}
void CmdDrawingNewView::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::vector<App::DocumentObject*> shapes = getSelection().getObjectsOfType(Part::Feature::getClassTypeId());
std::vector<App::DocumentObject*> shapes =
getSelection().getObjectsOfType(Part::Feature::getClassTypeId());
if (shapes.empty()) {
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"),
QObject::tr("Select a Part object."));
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("Wrong selection"),
QObject::tr("Select a Part object."));
return;
}
std::vector<App::DocumentObject*> pages = getSelection().getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
std::vector<App::DocumentObject*> pages =
getSelection().getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (pages.empty()) {
pages = this->getDocument()->getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (pages.empty()){
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No page found"),
QObject::tr("Create a page first."));
if (pages.empty()) {
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("No page found"),
QObject::tr("Create a page first."));
return;
}
}
const std::vector<App::DocumentObject*> selectedProjections = getSelection().getObjectsOfType(Drawing::FeatureView::getClassTypeId());
const std::vector<App::DocumentObject*> selectedProjections =
getSelection().getObjectsOfType(Drawing::FeatureView::getClassTypeId());
float newX = 10.0;
float newY = 10.0;
float newScale = 1.0;
float newRotation = 0.0;
Base::Vector3d newDirection(0.0, 0.0, 1.0);
if (!selectedProjections.empty()) {
const Drawing::FeatureView* const myView = static_cast<Drawing::FeatureView*>(selectedProjections.front());
const Drawing::FeatureView* const myView =
static_cast<Drawing::FeatureView*>(selectedProjections.front());
newX = myView->X.getValue();
newY = myView->Y.getValue();
@@ -351,7 +362,8 @@ void CmdDrawingNewView::activated(int iMsg)
// The "Direction" property does not belong to Drawing::FeatureView, but to one of the
// many child classes that are projecting objects into the drawing. Therefore, we get the
// property by name.
const App::PropertyVector* const propDirection = dynamic_cast<App::PropertyVector*>(myView->getPropertyByName("Direction"));
const App::PropertyVector* const propDirection =
dynamic_cast<App::PropertyVector*>(myView->getPropertyByName("Direction"));
if (propDirection) {
newDirection = propDirection->getValue();
}
@@ -360,16 +372,30 @@ void CmdDrawingNewView::activated(int iMsg)
std::string PageName = pages.front()->getNameInDocument();
openCommand("Create view");
for (std::vector<App::DocumentObject*>::iterator it = shapes.begin(); it != shapes.end(); ++it) {
for (std::vector<App::DocumentObject*>::iterator it = shapes.begin(); it != shapes.end();
++it) {
std::string FeatName = getUniqueObjectName("View");
doCommand(Doc,"App.activeDocument().addObject('Drawing::FeatureViewPart','%s')",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.Source = App.activeDocument().%s",FeatName.c_str(),(*it)->getNameInDocument());
doCommand(Doc,"App.activeDocument().%s.Direction = (%e,%e,%e)",FeatName.c_str(), newDirection.x, newDirection.y, newDirection.z);
doCommand(Doc,"App.activeDocument().%s.X = %e",FeatName.c_str(), newX);
doCommand(Doc,"App.activeDocument().%s.Y = %e",FeatName.c_str(), newY);
doCommand(Doc,"App.activeDocument().%s.Scale = %e",FeatName.c_str(), newScale);
doCommand(Doc,"App.activeDocument().%s.Rotation = %e",FeatName.c_str(), newRotation);
doCommand(Doc,"App.activeDocument().%s.addObject(App.activeDocument().%s)",PageName.c_str(),FeatName.c_str());
doCommand(Doc,
"App.activeDocument().addObject('Drawing::FeatureViewPart','%s')",
FeatName.c_str());
doCommand(Doc,
"App.activeDocument().%s.Source = App.activeDocument().%s",
FeatName.c_str(),
(*it)->getNameInDocument());
doCommand(Doc,
"App.activeDocument().%s.Direction = (%e,%e,%e)",
FeatName.c_str(),
newDirection.x,
newDirection.y,
newDirection.z);
doCommand(Doc, "App.activeDocument().%s.X = %e", FeatName.c_str(), newX);
doCommand(Doc, "App.activeDocument().%s.Y = %e", FeatName.c_str(), newY);
doCommand(Doc, "App.activeDocument().%s.Scale = %e", FeatName.c_str(), newScale);
doCommand(Doc, "App.activeDocument().%s.Rotation = %e", FeatName.c_str(), newRotation);
doCommand(Doc,
"App.activeDocument().%s.addObject(App.activeDocument().%s)",
PageName.c_str(),
FeatName.c_str());
}
updateActive();
commitCommand();
@@ -382,33 +408,37 @@ void CmdDrawingNewView::activated(int iMsg)
DEF_STD_CMD_A(CmdDrawingOrthoViews)
CmdDrawingOrthoViews::CmdDrawingOrthoViews()
: Command("Drawing_OrthoViews")
: Command("Drawing_OrthoViews")
{
sAppModule = "Drawing";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Insert orthographic views");
sToolTipText = QT_TR_NOOP("Insert an orthographic projection of a part in the active drawing");
sWhatsThis = "Drawing_OrthoView";
sStatusTip = sToolTipText;
sPixmap = "actions/drawing-orthoviews";
sAppModule = "Drawing";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Insert orthographic views");
sToolTipText = QT_TR_NOOP("Insert an orthographic projection of a part in the active drawing");
sWhatsThis = "Drawing_OrthoView";
sStatusTip = sToolTipText;
sPixmap = "actions/drawing-orthoviews";
}
void CmdDrawingOrthoViews::activated(int iMsg)
{
Q_UNUSED(iMsg);
const std::vector<App::DocumentObject*> shapes = getSelection().getObjectsOfType(Part::Feature::getClassTypeId());
const std::vector<App::DocumentObject*> shapes =
getSelection().getObjectsOfType(Part::Feature::getClassTypeId());
if (shapes.size() != 1) {
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"),
QObject::tr("Select exactly one Part object."));
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("Wrong selection"),
QObject::tr("Select exactly one Part object."));
return;
}
// Check that a page object exists. TaskDlgOrthoViews will then check for a selected page object
// and use that, otherwise it will use the first page in the document.
const std::vector<App::DocumentObject*> pages = this->getDocument()->getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
const std::vector<App::DocumentObject*> pages =
this->getDocument()->getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (pages.empty()) {
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No page found"),
QObject::tr("Create a page first."));
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("No page found"),
QObject::tr("Create a page first."));
return;
}
@@ -419,8 +449,9 @@ void CmdDrawingOrthoViews::activated(int iMsg)
bool CmdDrawingOrthoViews::isActive(void)
{
if (Gui::Control().activeDialog())
if (Gui::Control().activeDialog()) {
return false;
}
return true;
}
@@ -432,15 +463,15 @@ bool CmdDrawingOrthoViews::isActive(void)
DEF_STD_CMD_A(CmdDrawingOpenBrowserView)
CmdDrawingOpenBrowserView::CmdDrawingOpenBrowserView()
: Command("Drawing_OpenBrowserView")
: Command("Drawing_OpenBrowserView")
{
// setting the
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Open &browser view");
sToolTipText = QT_TR_NOOP("Opens the selected page in a browser view");
sWhatsThis = "Drawing_OpenBrowserView";
sStatusTip = QT_TR_NOOP("Opens the selected page in a browser view");
sPixmap = "actions/drawing-openbrowser";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Open &browser view");
sToolTipText = QT_TR_NOOP("Opens the selected page in a browser view");
sWhatsThis = "Drawing_OpenBrowserView";
sStatusTip = QT_TR_NOOP("Opens the selected page in a browser view");
sPixmap = "actions/drawing-openbrowser";
}
void CmdDrawingOpenBrowserView::activated(int iMsg)
@@ -448,14 +479,15 @@ void CmdDrawingOpenBrowserView::activated(int iMsg)
Q_UNUSED(iMsg);
unsigned int n = getSelection().countObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (n != 1) {
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"),
QObject::tr("Select one Page object."));
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("Wrong selection"),
QObject::tr("Select one Page object."));
return;
}
std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
doCommand(Doc,"PageName = App.activeDocument().%s.PageResult",Sel[0].FeatName);
doCommand(Doc,"import WebGui");
doCommand(Doc,"WebGui.openBrowser(PageName)");
doCommand(Doc, "PageName = App.activeDocument().%s.PageResult", Sel[0].FeatName);
doCommand(Doc, "import WebGui");
doCommand(Doc, "WebGui.openBrowser(PageName)");
}
bool CmdDrawingOpenBrowserView::isActive(void)
@@ -470,37 +502,44 @@ bool CmdDrawingOpenBrowserView::isActive(void)
DEF_STD_CMD_A(CmdDrawingAnnotation)
CmdDrawingAnnotation::CmdDrawingAnnotation()
: Command("Drawing_Annotation")
: Command("Drawing_Annotation")
{
// setting the
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("&Annotation");
sToolTipText = QT_TR_NOOP("Inserts an Annotation view in the active drawing");
sWhatsThis = "Drawing_Annotation";
sStatusTip = QT_TR_NOOP("Inserts an Annotation view in the active drawing");
sPixmap = "actions/drawing-annotation";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("&Annotation");
sToolTipText = QT_TR_NOOP("Inserts an Annotation view in the active drawing");
sWhatsThis = "Drawing_Annotation";
sStatusTip = QT_TR_NOOP("Inserts an Annotation view in the active drawing");
sPixmap = "actions/drawing-annotation";
}
void CmdDrawingAnnotation::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::vector<App::DocumentObject*> pages = getSelection().getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
std::vector<App::DocumentObject*> pages =
getSelection().getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (pages.empty()) {
pages = this->getDocument()->getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (pages.empty()){
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No page found"),
QObject::tr("Create a page first."));
if (pages.empty()) {
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("No page found"),
QObject::tr("Create a page first."));
return;
}
}
std::string PageName = pages.front()->getNameInDocument();
std::string FeatName = getUniqueObjectName("Annotation");
openCommand("Create Annotation");
doCommand(Doc,"App.activeDocument().addObject('Drawing::FeatureViewAnnotation','%s')",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.X = 10.0",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.Y = 10.0",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.Scale = 7.0",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.addObject(App.activeDocument().%s)",PageName.c_str(),FeatName.c_str());
doCommand(Doc,
"App.activeDocument().addObject('Drawing::FeatureViewAnnotation','%s')",
FeatName.c_str());
doCommand(Doc, "App.activeDocument().%s.X = 10.0", FeatName.c_str());
doCommand(Doc, "App.activeDocument().%s.Y = 10.0", FeatName.c_str());
doCommand(Doc, "App.activeDocument().%s.Scale = 7.0", FeatName.c_str());
doCommand(Doc,
"App.activeDocument().%s.addObject(App.activeDocument().%s)",
PageName.c_str(),
FeatName.c_str());
updateActive();
commitCommand();
}
@@ -518,34 +557,39 @@ bool CmdDrawingAnnotation::isActive(void)
DEF_STD_CMD_A(CmdDrawingClip)
CmdDrawingClip::CmdDrawingClip()
: Command("Drawing_Clip")
: Command("Drawing_Clip")
{
// setting the
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("&Clip");
sToolTipText = QT_TR_NOOP("Inserts a clip group in the active drawing");
sWhatsThis = "Drawing_Annotation";
sStatusTip = QT_TR_NOOP("Inserts a clip group in the active drawing");
sPixmap = "actions/drawing-clip";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("&Clip");
sToolTipText = QT_TR_NOOP("Inserts a clip group in the active drawing");
sWhatsThis = "Drawing_Annotation";
sStatusTip = QT_TR_NOOP("Inserts a clip group in the active drawing");
sPixmap = "actions/drawing-clip";
}
void CmdDrawingClip::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::vector<App::DocumentObject*> pages = getSelection().getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
std::vector<App::DocumentObject*> pages =
getSelection().getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (pages.empty()) {
pages = this->getDocument()->getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (pages.empty()){
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No page found"),
QObject::tr("Create a page first."));
if (pages.empty()) {
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("No page found"),
QObject::tr("Create a page first."));
return;
}
}
std::string PageName = pages.front()->getNameInDocument();
std::string FeatName = getUniqueObjectName("Clip");
openCommand("Create Clip");
doCommand(Doc,"App.activeDocument().addObject('Drawing::FeatureClip','%s')",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.addObject(App.activeDocument().%s)",PageName.c_str(),FeatName.c_str());
doCommand(Doc, "App.activeDocument().addObject('Drawing::FeatureClip','%s')", FeatName.c_str());
doCommand(Doc,
"App.activeDocument().%s.addObject(App.activeDocument().%s)",
PageName.c_str(),
FeatName.c_str());
updateActive();
commitCommand();
}
@@ -563,45 +607,56 @@ bool CmdDrawingClip::isActive(void)
DEF_STD_CMD_A(CmdDrawingSymbol)
CmdDrawingSymbol::CmdDrawingSymbol()
: Command("Drawing_Symbol")
: Command("Drawing_Symbol")
{
// setting the
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("&Symbol");
sToolTipText = QT_TR_NOOP("Inserts a symbol from a svg file in the active drawing");
sWhatsThis = "Drawing_Symbol";
sStatusTip = QT_TR_NOOP("Inserts a symbol from a svg file in the active drawing");
sPixmap = "actions/drawing-symbol";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("&Symbol");
sToolTipText = QT_TR_NOOP("Inserts a symbol from a svg file in the active drawing");
sWhatsThis = "Drawing_Symbol";
sStatusTip = QT_TR_NOOP("Inserts a symbol from a svg file in the active drawing");
sPixmap = "actions/drawing-symbol";
}
void CmdDrawingSymbol::activated(int iMsg)
{
Q_UNUSED(iMsg);
std::vector<App::DocumentObject*> pages = getSelection().getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
std::vector<App::DocumentObject*> pages =
getSelection().getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (pages.empty()) {
pages = this->getDocument()->getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (pages.empty()){
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No page found"),
QObject::tr("Create a page first."));
if (pages.empty()) {
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("No page found"),
QObject::tr("Create a page first."));
return;
}
}
// Reading an image
QString filename = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), QObject::tr("Choose an SVG file to open"), QString(),
QString filename = Gui::FileDialog::getOpenFileName(
Gui::getMainWindow(),
QObject::tr("Choose an SVG file to open"),
QString(),
QString::fromLatin1("%1 (*.svg *.svgz)").arg(QObject::tr("Scalable Vector Graphic")));
if (!filename.isEmpty())
{
if (!filename.isEmpty()) {
std::string PageName = pages.front()->getNameInDocument();
std::string FeatName = getUniqueObjectName("Symbol");
filename = Base::Tools::escapeEncodeFilename(filename);
openCommand("Create Symbol");
doCommand(Doc,"import Drawing");
doCommand(Doc,"f = open(\"%s\",'r')",(const char*)filename.toUtf8());
doCommand(Doc,"svg = f.read()");
doCommand(Doc,"f.close()");
doCommand(Doc,"App.activeDocument().addObject('Drawing::FeatureViewSymbol','%s')",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.Symbol = Drawing.removeSvgTags(svg)",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.addObject(App.activeDocument().%s)",PageName.c_str(),FeatName.c_str());
doCommand(Doc, "import Drawing");
doCommand(Doc, "f = open(\"%s\",'r')", (const char*)filename.toUtf8());
doCommand(Doc, "svg = f.read()");
doCommand(Doc, "f.close()");
doCommand(Doc,
"App.activeDocument().addObject('Drawing::FeatureViewSymbol','%s')",
FeatName.c_str());
doCommand(Doc,
"App.activeDocument().%s.Symbol = Drawing.removeSvgTags(svg)",
FeatName.c_str());
doCommand(Doc,
"App.activeDocument().%s.addObject(App.activeDocument().%s)",
PageName.c_str(),
FeatName.c_str());
updateActive();
commitCommand();
}
@@ -620,15 +675,15 @@ bool CmdDrawingSymbol::isActive(void)
DEF_STD_CMD_A(CmdDrawingExportPage)
CmdDrawingExportPage::CmdDrawingExportPage()
: Command("Drawing_ExportPage")
: Command("Drawing_ExportPage")
{
// setting the
sGroup = QT_TR_NOOP("File");
sMenuText = QT_TR_NOOP("&Export page...");
sToolTipText = QT_TR_NOOP("Export a page to an SVG file");
sWhatsThis = "Drawing_ExportPage";
sStatusTip = QT_TR_NOOP("Export a page to an SVG file");
sPixmap = "document-save";
sGroup = QT_TR_NOOP("File");
sMenuText = QT_TR_NOOP("&Export page...");
sToolTipText = QT_TR_NOOP("Export a page to an SVG file");
sWhatsThis = "Drawing_ExportPage";
sStatusTip = QT_TR_NOOP("Export a page to an SVG file");
sPixmap = "document-save";
}
void CmdDrawingExportPage::activated(int iMsg)
@@ -636,8 +691,9 @@ void CmdDrawingExportPage::activated(int iMsg)
Q_UNUSED(iMsg);
unsigned int n = getSelection().countObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (n != 1) {
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"),
QObject::tr("Select one Page object."));
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("Wrong selection"),
QObject::tr("Select one Page object."));
return;
}
@@ -645,17 +701,20 @@ void CmdDrawingExportPage::activated(int iMsg)
filter << QString::fromLatin1("%1 (*.svg)").arg(QObject::tr("Scalable Vector Graphic"));
filter << QString::fromLatin1("%1 (*.*)").arg(QObject::tr("All Files"));
QString fn = Gui::FileDialog::getSaveFileName(Gui::getMainWindow(), QObject::tr("Export page"), QString(), filter.join(QLatin1String(";;")));
QString fn = Gui::FileDialog::getSaveFileName(Gui::getMainWindow(),
QObject::tr("Export page"),
QString(),
filter.join(QLatin1String(";;")));
if (!fn.isEmpty()) {
std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
openCommand("Drawing export page");
doCommand(Doc,"PageFile = open(App.activeDocument().%s.PageResult,'r')",Sel[0].FeatName);
doCommand(Doc, "PageFile = open(App.activeDocument().%s.PageResult,'r')", Sel[0].FeatName);
std::string fname = (const char*)fn.toUtf8();
fname = Base::Tools::escapeEncodeFilename(fname);
doCommand(Doc,"OutFile = open(\"%s\",'w')",fname.c_str());
doCommand(Doc,"OutFile.write(PageFile.read())");
doCommand(Doc,"del OutFile,PageFile");
doCommand(Doc, "OutFile = open(\"%s\",'w')", fname.c_str());
doCommand(Doc, "OutFile.write(PageFile.read())");
doCommand(Doc, "del OutFile,PageFile");
commitCommand();
}
@@ -673,14 +732,14 @@ bool CmdDrawingExportPage::isActive(void)
DEF_STD_CMD_A(CmdDrawingProjectShape)
CmdDrawingProjectShape::CmdDrawingProjectShape()
: Command("Drawing_ProjectShape")
: Command("Drawing_ProjectShape")
{
// setting the
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Project shape...");
sToolTipText = QT_TR_NOOP("Project shape onto a user-defined plane");
sStatusTip = QT_TR_NOOP("Project shape onto a user-defined plane");
sWhatsThis = "Drawing_ProjectShape";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("Project shape...");
sToolTipText = QT_TR_NOOP("Project shape onto a user-defined plane");
sStatusTip = QT_TR_NOOP("Project shape onto a user-defined plane");
sWhatsThis = "Drawing_ProjectShape";
}
void CmdDrawingProjectShape::activated(int iMsg)
@@ -701,7 +760,6 @@ bool CmdDrawingProjectShape::isActive(void)
}
//===========================================================================
// Drawing_Draft_View
//===========================================================================
@@ -709,22 +767,23 @@ bool CmdDrawingProjectShape::isActive(void)
DEF_STD_CMD_A(CmdDrawingDraftView)
CmdDrawingDraftView::CmdDrawingDraftView()
: Command("Drawing_DraftView")
: Command("Drawing_DraftView")
{
// setting the
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("&Draft View");
sToolTipText = QT_TR_NOOP("Inserts a Draft view of the selected object(s) in the active drawing");
sWhatsThis = "Drawing_DraftView";
sStatusTip = QT_TR_NOOP("Inserts a Draft view of the selected object(s) in the active drawing");
sPixmap = "actions/drawing-draft-view";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("&Draft View");
sToolTipText =
QT_TR_NOOP("Inserts a Draft view of the selected object(s) in the active drawing");
sWhatsThis = "Drawing_DraftView";
sStatusTip = QT_TR_NOOP("Inserts a Draft view of the selected object(s) in the active drawing");
sPixmap = "actions/drawing-draft-view";
}
void CmdDrawingDraftView::activated(int iMsg)
{
Q_UNUSED(iMsg);
addModule(Gui,"Draft");
doCommand(Gui,"Gui.runCommand(\"Draft_Drawing\")");
addModule(Gui, "Draft");
doCommand(Gui, "Gui.runCommand(\"Draft_Drawing\")");
}
bool CmdDrawingDraftView::isActive(void)
@@ -740,39 +799,51 @@ bool CmdDrawingDraftView::isActive(void)
DEF_STD_CMD_A(CmdDrawingSpreadsheetView)
CmdDrawingSpreadsheetView::CmdDrawingSpreadsheetView()
: Command("Drawing_SpreadsheetView")
: Command("Drawing_SpreadsheetView")
{
// setting the
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("&Spreadsheet View");
sToolTipText = QT_TR_NOOP("Inserts a view of a selected spreadsheet in the active drawing");
sWhatsThis = "Drawing_SpreadsheetView";
sStatusTip = QT_TR_NOOP("Inserts a view of a selected spreadsheet in the active drawing");
sPixmap = "actions/drawing-spreadsheet";
sGroup = QT_TR_NOOP("Drawing");
sMenuText = QT_TR_NOOP("&Spreadsheet View");
sToolTipText = QT_TR_NOOP("Inserts a view of a selected spreadsheet in the active drawing");
sWhatsThis = "Drawing_SpreadsheetView";
sStatusTip = QT_TR_NOOP("Inserts a view of a selected spreadsheet in the active drawing");
sPixmap = "actions/drawing-spreadsheet";
}
void CmdDrawingSpreadsheetView::activated(int iMsg)
{
Q_UNUSED(iMsg);
const std::vector<App::DocumentObject*> spreads = getSelection().getObjectsOfType(Spreadsheet::Sheet::getClassTypeId());
const std::vector<App::DocumentObject*> spreads =
getSelection().getObjectsOfType(Spreadsheet::Sheet::getClassTypeId());
if (spreads.size() != 1) {
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"),
QObject::tr("Select exactly one Spreadsheet object."));
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("Wrong selection"),
QObject::tr("Select exactly one Spreadsheet object."));
return;
}
const std::vector<App::DocumentObject*> pages = this->getDocument()->getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
const std::vector<App::DocumentObject*> pages =
this->getDocument()->getObjectsOfType(Drawing::FeaturePage::getClassTypeId());
if (pages.empty()) {
QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No page found"),
QObject::tr("Create a page first."));
QMessageBox::warning(Gui::getMainWindow(),
QObject::tr("No page found"),
QObject::tr("Create a page first."));
return;
}
std::string SpreadName = spreads.front()->getNameInDocument();
std::string PageName = pages.front()->getNameInDocument();
openCommand("Create spreadsheet view");
std::string FeatName = getUniqueObjectName("View");
doCommand(Doc,"App.activeDocument().addObject('Drawing::FeatureViewSpreadsheet','%s')",FeatName.c_str());
doCommand(Doc,"App.activeDocument().%s.Source = App.activeDocument().%s",FeatName.c_str(),SpreadName.c_str());
doCommand(Doc,"App.activeDocument().%s.addObject(App.activeDocument().%s)",PageName.c_str(),FeatName.c_str());
doCommand(Doc,
"App.activeDocument().addObject('Drawing::FeatureViewSpreadsheet','%s')",
FeatName.c_str());
doCommand(Doc,
"App.activeDocument().%s.Source = App.activeDocument().%s",
FeatName.c_str(),
SpreadName.c_str());
doCommand(Doc,
"App.activeDocument().%s.addObject(App.activeDocument().%s)",
PageName.c_str(),
FeatName.c_str());
updateActive();
commitCommand();
}
@@ -785,7 +856,7 @@ bool CmdDrawingSpreadsheetView::isActive(void)
void CreateDrawingCommands(void)
{
Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();
Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager();
rcCmdMgr.addCommand(new CmdDrawingOpen());
rcCmdMgr.addCommand(new CmdDrawingNewPage());

View File

@@ -22,27 +22,27 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <cmath>
#include <cmath>
# include <QAction>
# include <QApplication>
# include <QContextMenuEvent>
# include <QFileInfo>
# include <QFileDialog>
# include <QGLWidget>
# include <QGraphicsRectItem>
# include <QGraphicsSvgItem>
# include <QGridLayout>
# include <QGroupBox>
# include <QListWidget>
# include <QMenu>
# include <QMessageBox>
# include <QPainter>
# include <QPaintEvent>
# include <QPrinter>
# include <QPrintDialog>
# include <QPrintPreviewDialog>
# include <QWheelEvent>
#include <QAction>
#include <QApplication>
#include <QContextMenuEvent>
#include <QFileDialog>
#include <QFileInfo>
#include <QGLWidget>
#include <QGraphicsRectItem>
#include <QGraphicsSvgItem>
#include <QGridLayout>
#include <QGroupBox>
#include <QListWidget>
#include <QMenu>
#include <QMessageBox>
#include <QPaintEvent>
#include <QPainter>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QPrinter>
#include <QWheelEvent>
#endif
@@ -59,7 +59,7 @@
using namespace DrawingGui;
SvgView::SvgView(QWidget *parent)
SvgView::SvgView(QWidget* parent)
: QGraphicsView(parent)
, m_renderer(Native)
, m_svgItem(nullptr)
@@ -83,7 +83,7 @@ SvgView::SvgView(QWidget *parent)
setBackgroundBrush(tilePixmap);
}
void SvgView::drawBackground(QPainter *p, const QRectF &)
void SvgView::drawBackground(QPainter* p, const QRectF&)
{
p->save();
p->resetTransform();
@@ -91,12 +91,13 @@ void SvgView::drawBackground(QPainter *p, const QRectF &)
p->restore();
}
void SvgView::openFile(const QFile &file)
void SvgView::openFile(const QFile& file)
{
if (!file.exists())
if (!file.exists()) {
return;
}
QGraphicsScene *s = scene();
QGraphicsScene* s = scene();
bool drawBackground = (m_backgroundItem ? m_backgroundItem->isVisible() : true);
bool drawOutline = (m_outlineItem ? m_outlineItem->isVisible() : false);
@@ -140,7 +141,8 @@ void SvgView::setRenderer(RendererType type)
#ifndef QT_NO_OPENGL
setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers)));
#endif
} else {
}
else {
setViewport(new QWidget);
}
}
@@ -156,21 +158,23 @@ void SvgView::setHighQualityAntialiasing(bool highQualityAntialiasing)
void SvgView::setViewBackground(bool enable)
{
if (!m_backgroundItem)
if (!m_backgroundItem) {
return;
}
m_backgroundItem->setVisible(enable);
}
void SvgView::setViewOutline(bool enable)
{
if (!m_outlineItem)
if (!m_outlineItem) {
return;
}
m_outlineItem->setVisible(enable);
}
void SvgView::paintEvent(QPaintEvent *event)
void SvgView::paintEvent(QPaintEvent* event)
{
if (m_renderer == Image) {
if (m_image.size() != viewport()->size()) {
@@ -183,17 +187,18 @@ void SvgView::paintEvent(QPaintEvent *event)
QPainter p(viewport());
p.drawImage(0, 0, m_image);
} else {
}
else {
QGraphicsView::paintEvent(event);
}
}
void SvgView::wheelEvent(QWheelEvent *event)
void SvgView::wheelEvent(QWheelEvent* event)
{
int delta = -event->angleDelta().y();
if (m_invertZoom)
if (m_invertZoom) {
delta = -delta;
}
qreal factor = std::pow(1.2, delta / 240.0);
scale(factor, factor);
event->accept();
@@ -204,7 +209,8 @@ void SvgView::wheelEvent(QWheelEvent *event)
/* TRANSLATOR DrawingGui::DrawingView */
DrawingView::DrawingView(Gui::Document* doc, QWidget* parent)
: Gui::MDIView(doc, parent), m_view(new SvgView)
: Gui::MDIView(doc, parent)
, m_view(new SvgView)
{
m_backgroundAction = new QAction(tr("&Background"), this);
m_backgroundAction->setEnabled(false);
@@ -233,41 +239,42 @@ DrawingView::DrawingView(Gui::Document* doc, QWidget* parent)
m_highQualityAntialiasingAction->setEnabled(false);
m_highQualityAntialiasingAction->setCheckable(true);
m_highQualityAntialiasingAction->setChecked(false);
connect(m_highQualityAntialiasingAction, SIGNAL(toggled(bool)),
m_view, SLOT(setHighQualityAntialiasing(bool)));
connect(m_highQualityAntialiasingAction,
SIGNAL(toggled(bool)),
m_view,
SLOT(setHighQualityAntialiasing(bool)));
#endif
QActionGroup *rendererGroup = new QActionGroup(this);
QActionGroup* rendererGroup = new QActionGroup(this);
rendererGroup->addAction(m_nativeAction);
#ifndef QT_NO_OPENGL
rendererGroup->addAction(m_glAction);
#endif
rendererGroup->addAction(m_imageAction);
connect(rendererGroup, SIGNAL(triggered(QAction *)),
this, SLOT(setRenderer(QAction *)));
connect(rendererGroup, SIGNAL(triggered(QAction*)), this, SLOT(setRenderer(QAction*)));
setCentralWidget(m_view);
//setWindowTitle(tr("SVG Viewer"));
// setWindowTitle(tr("SVG Viewer"));
m_orientation = QPageLayout::Landscape;
m_pageSize = QPageSize::A4;
ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath
("User parameter:BaseApp/Preferences/View");
ParameterGrp::handle hGrp =
App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View");
bool on = hGrp->GetBool("InvertZoom", true);
m_view->setZoomInverted(on);
}
DrawingView::~DrawingView()
{
}
{}
void DrawingView::load (const QString & fileName)
void DrawingView::load(const QString& fileName)
{
if (!fileName.isEmpty()) {
QFile file(fileName);
if (!file.exists()) {
QMessageBox::critical(this, tr("Open SVG File"),
tr("Could not open file '%1'.").arg(fileName));
QMessageBox::critical(this,
tr("Open SVG File"),
tr("Could not open file '%1'.").arg(fileName));
m_outlineAction->setEnabled(false);
m_backgroundAction->setEnabled(false);
@@ -278,7 +285,7 @@ void DrawingView::load (const QString & fileName)
if (!fileName.startsWith(QLatin1String(":/"))) {
m_currentPath = fileName;
//setWindowTitle(tr("%1 - SVG Viewer").arg(m_currentPath));
// setWindowTitle(tr("%1 - SVG Viewer").arg(m_currentPath));
}
m_outlineAction->setEnabled(true);
@@ -318,7 +325,9 @@ void DrawingView::findPrinterSettings(const QString& fileName)
pageSizes[QPageSize::B7] = QString::fromLatin1("B7");
pageSizes[QPageSize::B8] = QString::fromLatin1("B8");
pageSizes[QPageSize::B9] = QString::fromLatin1("B9");
for (QMap<QPageSize::PageSizeId, QString>::iterator it = pageSizes.begin(); it != pageSizes.end(); ++it) {
for (QMap<QPageSize::PageSizeId, QString>::iterator it = pageSizes.begin();
it != pageSizes.end();
++it) {
if (fileName.startsWith(it.value(), Qt::CaseInsensitive)) {
m_pageSize = it.key();
break;
@@ -334,8 +343,9 @@ void DrawingView::setDocumentObject(const std::string& name)
void DrawingView::closeEvent(QCloseEvent* ev)
{
MDIView::closeEvent(ev);
if (!ev->isAccepted())
if (!ev->isAccepted()) {
return;
}
// when closing the view from GUI notify the view provider to mark it invisible
if (_pcDocument && !m_objectName.empty()) {
@@ -343,13 +353,14 @@ void DrawingView::closeEvent(QCloseEvent* ev)
if (doc) {
App::DocumentObject* obj = doc->getObject(m_objectName.c_str());
Gui::ViewProvider* vp = _pcDocument->getViewProvider(obj);
if (vp)
if (vp) {
vp->hide();
}
}
}
}
void DrawingView::contextMenuEvent(QContextMenuEvent *event)
void DrawingView::contextMenuEvent(QContextMenuEvent* event)
{
QMenu menu;
menu.addAction(this->m_backgroundAction);
@@ -363,14 +374,15 @@ void DrawingView::contextMenuEvent(QContextMenuEvent *event)
menu.exec(event->globalPos());
}
void DrawingView::setRenderer(QAction *action)
void DrawingView::setRenderer(QAction* action)
{
#ifndef QT_NO_OPENGL
m_highQualityAntialiasingAction->setEnabled(false);
#endif
if (action == m_nativeAction)
if (action == m_nativeAction) {
m_view->setRenderer(SvgView::Native);
}
#ifndef QT_NO_OPENGL
else if (action == m_glAction) {
m_highQualityAntialiasingAction->setEnabled(true);
@@ -382,35 +394,35 @@ void DrawingView::setRenderer(QAction *action)
}
}
bool DrawingView::onMsg(const char* pMsg, const char** )
bool DrawingView::onMsg(const char* pMsg, const char**)
{
if (strcmp("ViewFit",pMsg) == 0) {
if (strcmp("ViewFit", pMsg) == 0) {
viewAll();
return true;
}
else if (strcmp("Save",pMsg) == 0) {
Gui::Document *doc = getGuiDocument();
else if (strcmp("Save", pMsg) == 0) {
Gui::Document* doc = getGuiDocument();
if (doc) {
doc->save();
return true;
}
}
else if (strcmp("SaveAs",pMsg) == 0) {
Gui::Document *doc = getGuiDocument();
else if (strcmp("SaveAs", pMsg) == 0) {
Gui::Document* doc = getGuiDocument();
if (doc) {
doc->saveAs();
return true;
}
}
else if(strcmp("Undo",pMsg) == 0 ) {
Gui::Document *doc = getGuiDocument();
else if (strcmp("Undo", pMsg) == 0) {
Gui::Document* doc = getGuiDocument();
if (doc) {
doc->undo(1);
return true;
}
}
else if(strcmp("Redo",pMsg) == 0 ) {
Gui::Document *doc = getGuiDocument();
else if (strcmp("Redo", pMsg) == 0) {
Gui::Document* doc = getGuiDocument();
if (doc) {
doc->redo(1);
return true;
@@ -421,35 +433,41 @@ bool DrawingView::onMsg(const char* pMsg, const char** )
bool DrawingView::onHasMsg(const char* pMsg) const
{
if (strcmp("ViewFit",pMsg) == 0)
if (strcmp("ViewFit", pMsg) == 0) {
return true;
else if (strcmp("Save",pMsg) == 0)
}
else if (strcmp("Save", pMsg) == 0) {
return getGuiDocument() != nullptr;
else if (strcmp("SaveAs",pMsg) == 0)
}
else if (strcmp("SaveAs", pMsg) == 0) {
return getGuiDocument() != nullptr;
else if (strcmp("Undo",pMsg) == 0) {
}
else if (strcmp("Undo", pMsg) == 0) {
App::Document* doc = getAppDocument();
return doc && doc->getAvailableUndos() > 0;
}
else if (strcmp("Redo",pMsg) == 0) {
else if (strcmp("Redo", pMsg) == 0) {
App::Document* doc = getAppDocument();
return doc && doc->getAvailableRedos() > 0;
}
else if (strcmp("Print",pMsg) == 0)
else if (strcmp("Print", pMsg) == 0) {
return true;
else if (strcmp("PrintPreview",pMsg) == 0)
}
else if (strcmp("PrintPreview", pMsg) == 0) {
return true;
else if (strcmp("PrintPdf",pMsg) == 0)
}
else if (strcmp("PrintPdf", pMsg) == 0) {
return true;
}
return false;
}
void DrawingView::onRelabel(Gui::Document *pDoc)
void DrawingView::onRelabel(Gui::Document* pDoc)
{
if (!bIsPassive && pDoc) {
QString cap = QString::fromLatin1("%1 : %2[*]")
.arg(QString::fromUtf8(pDoc->getDocument()->Label.getValue()),
objectName());
QString cap =
QString::fromLatin1("%1 : %2[*]")
.arg(QString::fromUtf8(pDoc->getDocument()->Label.getValue()), objectName());
setWindowTitle(cap);
}
}
@@ -462,12 +480,12 @@ void DrawingView::printPdf()
dlg.setWindowTitle(tr("Export PDF"));
dlg.setNameFilters(QStringList() << QString::fromLatin1("%1 (*.pdf)").arg(tr("PDF file")));
QGridLayout *gridLayout;
QGridLayout *formLayout;
QGroupBox *groupBox;
QListWidget *listWidget;
QGridLayout* gridLayout;
QGridLayout* formLayout;
QGroupBox* groupBox;
QListWidget* listWidget;
QListWidgetItem* item;
QWidget *form = new QWidget(&dlg);
QWidget* form = new QWidget(&dlg);
form->resize(40, 300);
formLayout = new QGridLayout(form);
groupBox = new QGroupBox(form);
@@ -489,8 +507,8 @@ void DrawingView::printPdf()
item->setData(Qt::UserRole, QVariant(QPageSize::A4));
item = new QListWidgetItem(tr("A5"), listWidget);
item->setData(Qt::UserRole, QVariant(QPageSize::A5));
int index = 4; // by default A4
for (int i=0; i<listWidget->count(); i++) {
int index = 4;// by default A4
for (int i = 0; i < listWidget->count(); i++) {
if (listWidget->item(i)->data(Qt::UserRole).toInt() == m_pageSize) {
index = i;
break;
@@ -540,8 +558,7 @@ void DrawingView::printPreview()
printer.setPageOrientation(m_orientation);
QPrintPreviewDialog dlg(&printer, this);
connect(&dlg, SIGNAL(paintRequested (QPrinter *)),
this, SLOT(print(QPrinter *)));
connect(&dlg, SIGNAL(paintRequested(QPrinter*)), this, SLOT(print(QPrinter*)));
dlg.exec();
}
@@ -570,35 +587,46 @@ void DrawingView::print(QPrinter* printer)
bool doPrint = paintType != QPaintEngine::Picture;
if (doPrint && printer->pageLayout().orientation() != this->m_orientation) {
int ret = QMessageBox::warning(this, tr("Different orientation"),
int ret = QMessageBox::warning(
this,
tr("Different orientation"),
tr("The printer uses a different orientation than the drawing.\n"
"Do you want to continue?"),
QMessageBox::Yes | QMessageBox::No);
if (ret != QMessageBox::Yes)
QMessageBox::Yes | QMessageBox::No);
if (ret != QMessageBox::Yes) {
return;
}
}
else if (doPrint && realPaperSize != this->m_pageSize) {
int ret = QMessageBox::warning(this, tr("Different paper size"),
int ret = QMessageBox::warning(
this,
tr("Different paper size"),
tr("The printer uses a different paper size than the drawing.\n"
"Do you want to continue?"),
QMessageBox::Yes | QMessageBox::No);
if (ret != QMessageBox::Yes)
QMessageBox::Yes | QMessageBox::No);
if (ret != QMessageBox::Yes) {
return;
}
}
else if (doPrint && curPaperSize != this->m_pageSize) {
int ret = QMessageBox::warning(this, tr("Different paper size"),
int ret = QMessageBox::warning(
this,
tr("Different paper size"),
tr("The printer uses a different paper size than the drawing.\n"
"Do you want to continue?"),
QMessageBox::Yes | QMessageBox::No);
if (ret != QMessageBox::Yes)
QMessageBox::Yes | QMessageBox::No);
if (ret != QMessageBox::Yes) {
return;
}
}
}
QPainter p(printer);
if (!p.isActive() && !printer->outputFileName().isEmpty()) {
qApp->setOverrideCursor(Qt::ArrowCursor);
QMessageBox::critical(this, tr("Opening file failed"),
QMessageBox::critical(
this,
tr("Opening file failed"),
tr("Can't open file '%1' for writing.").arg(printer->outputFileName()));
qApp->restoreOverrideCursor();
return;
@@ -607,8 +635,9 @@ void DrawingView::print(QPrinter* printer)
#ifdef Q_OS_WIN32
// On Windows the preview looks broken when using paperRect as render area.
// Although the picture is scaled when using pageRect, it looks just fine.
if (paintType == QPaintEngine::Picture)
if (paintType == QPaintEngine::Picture) {
rect = printer->pageLayout().paintRectPixels(printer->resolution());
}
#endif
this->m_view->scene()->render(&p, rect);
p.end();
@@ -617,48 +646,45 @@ void DrawingView::print(QPrinter* printer)
QPageSize::PageSizeId DrawingView::getPageSize(int w, int h) const
{
static const float paperSizes[][2] = {
{210, 297}, // A4
{176, 250}, // B5
{215.9f, 279.4f}, // Letter
{215.9f, 355.6f}, // Legal
{190.5f, 254}, // Executive
{841, 1189}, // A0
{594, 841}, // A1
{420, 594}, // A2
{297, 420}, // A3
{148, 210}, // A5
{105, 148}, // A6
{74, 105}, // A7
{52, 74}, // A8
{37, 52}, // A8
{1000, 1414}, // B0
{707, 1000}, // B1
{31, 44}, // B10
{500, 707}, // B2
{353, 500}, // B3
{250, 353}, // B4
{125, 176}, // B6
{88, 125}, // B7
{62, 88}, // B8
{33, 62}, // B9
{163, 229}, // C5E
{105, 241}, // US Common
{110, 220}, // DLE
{210, 330}, // Folio
{431.8f, 279.4f}, // Ledger
{210, 297}, // A4
{176, 250}, // B5
{215.9f, 279.4f},// Letter
{215.9f, 355.6f},// Legal
{190.5f, 254}, // Executive
{841, 1189}, // A0
{594, 841}, // A1
{420, 594}, // A2
{297, 420}, // A3
{148, 210}, // A5
{105, 148}, // A6
{74, 105}, // A7
{52, 74}, // A8
{37, 52}, // A8
{1000, 1414}, // B0
{707, 1000}, // B1
{31, 44}, // B10
{500, 707}, // B2
{353, 500}, // B3
{250, 353}, // B4
{125, 176}, // B6
{88, 125}, // B7
{62, 88}, // B8
{33, 62}, // B9
{163, 229}, // C5E
{105, 241}, // US Common
{110, 220}, // DLE
{210, 330}, // Folio
{431.8f, 279.4f},// Ledger
{279.4f, 431.8f} // Tabloid
};
QPageSize::PageSizeId ps = QPageSize::Custom;
for (int i=0; i<30; i++) {
if (std::abs(paperSizes[i][0]-w) <= 1 &&
std::abs(paperSizes[i][1]-h) <= 1) {
for (int i = 0; i < 30; i++) {
if (std::abs(paperSizes[i][0] - w) <= 1 && std::abs(paperSizes[i][1] - h) <= 1) {
ps = static_cast<QPageSize::PageSizeId>(i);
break;
}
else
if (std::abs(paperSizes[i][0]-h) <= 1 &&
std::abs(paperSizes[i][1]-w) <= 1) {
else if (std::abs(paperSizes[i][0] - h) <= 1 && std::abs(paperSizes[i][1] - w) <= 1) {
ps = static_cast<QPageSize::PageSizeId>(i);
break;

View File

@@ -45,19 +45,25 @@ QT_END_NAMESPACE
namespace DrawingGui
{
class DrawingGuiExport SvgView : public QGraphicsView
class DrawingGuiExport SvgView: public QGraphicsView
{
Q_OBJECT
public:
enum RendererType { Native, OpenGL, Image };
enum RendererType
{
Native,
OpenGL,
Image
};
SvgView(QWidget *parent = nullptr);
SvgView(QWidget* parent = nullptr);
void openFile(const QFile &file);
void openFile(const QFile& file);
void setRenderer(RendererType type = Native);
void drawBackground(QPainter *p, const QRectF &rect);
void setZoomInverted(bool on) {
void drawBackground(QPainter* p, const QRectF& rect);
void setZoomInverted(bool on)
{
m_invertZoom = on;
}
@@ -67,21 +73,21 @@ public Q_SLOTS:
void setViewOutline(bool enable);
protected:
void wheelEvent(QWheelEvent *event);
void paintEvent(QPaintEvent *event);
void wheelEvent(QWheelEvent* event);
void paintEvent(QPaintEvent* event);
private:
RendererType m_renderer;
QGraphicsItem *m_svgItem;
QGraphicsRectItem *m_backgroundItem;
QGraphicsRectItem *m_outlineItem;
QGraphicsItem* m_svgItem;
QGraphicsRectItem* m_backgroundItem;
QGraphicsRectItem* m_outlineItem;
QImage m_image;
bool m_invertZoom;
};
class DrawingGuiExport DrawingView : public Gui::MDIView
class DrawingGuiExport DrawingView: public Gui::MDIView
{
Q_OBJECT
@@ -90,14 +96,14 @@ public:
virtual ~DrawingView();
public Q_SLOTS:
void load(const QString &path = QString());
void setRenderer(QAction *action);
void load(const QString& path = QString());
void setRenderer(QAction* action);
void viewAll();
public:
bool onMsg(const char* pMsg,const char** ppReturn);
bool onMsg(const char* pMsg, const char** ppReturn);
bool onHasMsg(const char* pMsg) const;
void onRelabel(Gui::Document *pDoc);
void onRelabel(Gui::Document* pDoc);
void print();
void printPdf();
void printPreview();
@@ -106,20 +112,20 @@ public:
PyObject* getPyObject();
protected:
void contextMenuEvent(QContextMenuEvent *event);
void contextMenuEvent(QContextMenuEvent* event);
void closeEvent(QCloseEvent*);
void findPrinterSettings(const QString&);
QPageSize::PageSizeId getPageSize(int w, int h) const;
private:
QAction *m_nativeAction;
QAction *m_glAction;
QAction *m_imageAction;
QAction *m_highQualityAntialiasingAction;
QAction *m_backgroundAction;
QAction *m_outlineAction;
QAction* m_nativeAction;
QAction* m_glAction;
QAction* m_imageAction;
QAction* m_highQualityAntialiasingAction;
QAction* m_backgroundAction;
QAction* m_outlineAction;
SvgView *m_view;
SvgView* m_view;
std::string m_objectName;
QString m_currentPath;
@@ -127,6 +133,6 @@ private:
QPageSize::PageSizeId m_pageSize;
};
} // namespace DrawingViewGui
}// namespace DrawingGui
#endif // DRAWINGGUI_DRAWINGVIEW_H
#endif// DRAWINGGUI_DRAWINGVIEW_H

View File

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

View File

@@ -26,7 +26,7 @@
#include <FCConfig.h>
#ifdef _MSC_VER
# pragma warning(disable : 4005)
#pragma warning(disable : 4005)
#endif
#ifdef _PreComp_
@@ -55,15 +55,15 @@
#include <QListWidget>
#include <QMenu>
#include <QMessageBox>
#include <QPainter>
#include <QPaintEvent>
#include <QPrinter>
#include <QPainter>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QPrinter>
#include <QRegExp>
#include <QTimer>
#include <QWheelEvent>
#endif //_PreComp_
#endif//_PreComp_
#endif // DRAWINGGUI_PRECOMPILED_H
#endif// DRAWINGGUI_PRECOMPILED_H

View File

@@ -1,5 +1,5 @@
<RCC>
<qresource>
<qresource>
<file>icons/Page.svg</file>
<file>icons/Pages.svg</file>
<file>icons/View.svg</file>
@@ -26,4 +26,4 @@
<file>icons/actions/drawing-draft-view.svg</file>
<file>icons/actions/drawing-spreadsheet.svg</file>
</qresource>
</RCC>
</RCC>

View File

@@ -22,8 +22,8 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QCheckBox>
# include <QMessageBox>
#include <QCheckBox>
#include <QMessageBox>
#endif
#include <Gui/Application.h>
@@ -43,26 +43,24 @@ using namespace DrawingGui;
TaskProjection::TaskProjection()
{
QString texts[10] =
{
tr("Visible sharp edges"),
tr("Visible smooth edges"),
tr("Visible sewn edges"),
tr("Visible outline edges"),
tr("Visible isoparameters"),
tr("Hidden sharp edges"),
tr("Hidden smooth edges"),
tr("Hidden sewn edges"),
tr("Hidden outline edges"),
tr("Hidden isoparameters")
};
QString texts[10] = {tr("Visible sharp edges"),
tr("Visible smooth edges"),
tr("Visible sewn edges"),
tr("Visible outline edges"),
tr("Visible isoparameters"),
tr("Hidden sharp edges"),
tr("Hidden smooth edges"),
tr("Hidden sewn edges"),
tr("Hidden outline edges"),
tr("Hidden isoparameters")};
widget = new QWidget();
QVBoxLayout *mainLayout = new QVBoxLayout;
QVBoxLayout* mainLayout = new QVBoxLayout;
for (int i=0; i<10; i++) {
for (int i = 0; i < 10; i++) {
QCheckBox* cb = new QCheckBox();
if (i < 5)
if (i < 5) {
cb->setChecked(true);
}
cb->setText(texts[i]);
mainLayout->addWidget(cb);
boxes.push_back(cb);
@@ -70,8 +68,7 @@ TaskProjection::TaskProjection()
widget->setLayout(mainLayout);
taskbox = new Gui::TaskView::TaskBox(
QPixmap(), tr("Project shapes"), false, nullptr);
taskbox = new Gui::TaskView::TaskBox(QPixmap(), tr("Project shapes"), false, nullptr);
taskbox->groupLayout()->addWidget(widget);
Content.push_back(taskbox);
}
@@ -85,54 +82,76 @@ bool TaskProjection::accept()
{
Gui::Document* document = Gui::Application::Instance->activeDocument();
if (!document) {
QMessageBox::warning(widget, tr("No active document"),
tr("There is currently no active document to complete the operation"));
QMessageBox::warning(widget,
tr("No active document"),
tr("There is currently no active document to complete the operation"));
return true;
}
std::list<Gui::MDIView*> mdis = document->getMDIViewsOfType(Gui::View3DInventor::getClassTypeId());
std::list<Gui::MDIView*> mdis =
document->getMDIViewsOfType(Gui::View3DInventor::getClassTypeId());
if (mdis.empty()) {
QMessageBox::warning(widget, tr("No active view"),
tr("There is currently no active view to complete the operation"));
QMessageBox::warning(widget,
tr("No active view"),
tr("There is currently no active view to complete the operation"));
return false;
}
Gui::View3DInventorViewer* viewer = static_cast<Gui::View3DInventor*>(mdis.front())->getViewer();
Gui::View3DInventorViewer* viewer =
static_cast<Gui::View3DInventor*>(mdis.front())->getViewer();
SbVec3f pnt, dir;
viewer->getNearPlane(pnt, dir);
float x=0, y=1,z=1;
dir.getValue(x,y,z);
float x = 0, y = 1, z = 1;
dir.getValue(x, y, z);
std::vector<Part::Feature*> shapes = Gui::Selection().getObjectsOfType<Part::Feature>();
Gui::Command::openCommand("Project shape");
Gui::Command::addModule(Gui::Command::Doc,"Drawing");
Gui::Command::addModule(Gui::Command::Doc, "Drawing");
for (std::vector<Part::Feature*>::iterator it = shapes.begin(); it != shapes.end(); ++it) {
const char* object = (*it)->getNameInDocument();
Gui::Command::doCommand(
Gui::Command::Doc,
"FreeCAD.ActiveDocument.addObject('Drawing::FeatureProjection','%s_proj')",
object);
Gui::Command::doCommand(
Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.Direction=FreeCAD.Vector(%f,%f,%f)",
x,
y,
z);
Gui::Command::doCommand(
Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.Source=FreeCAD.ActiveDocument.%s",
object);
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.addObject('Drawing::FeatureProjection','%s_proj')", object);
"FreeCAD.ActiveDocument.ActiveObject.VCompound=%s",
(boxes[0]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.Direction=FreeCAD.Vector(%f,%f,%f)", x,y,z);
"FreeCAD.ActiveDocument.ActiveObject.Rg1LineVCompound=%s",
(boxes[1]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.Source=FreeCAD.ActiveDocument.%s", object);
"FreeCAD.ActiveDocument.ActiveObject.RgNLineVCompound=%s",
(boxes[2]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.VCompound=%s", (boxes[0]->isChecked() ? "True" : "False"));
"FreeCAD.ActiveDocument.ActiveObject.OutLineVCompound=%s",
(boxes[3]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.Rg1LineVCompound=%s", (boxes[1]->isChecked() ? "True" : "False"));
"FreeCAD.ActiveDocument.ActiveObject.IsoLineVCompound=%s",
(boxes[4]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.RgNLineVCompound=%s", (boxes[2]->isChecked() ? "True" : "False"));
"FreeCAD.ActiveDocument.ActiveObject.HCompound=%s",
(boxes[5]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.OutLineVCompound=%s", (boxes[3]->isChecked() ? "True" : "False"));
"FreeCAD.ActiveDocument.ActiveObject.Rg1LineHCompound=%s",
(boxes[6]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.IsoLineVCompound=%s", (boxes[4]->isChecked() ? "True" : "False"));
"FreeCAD.ActiveDocument.ActiveObject.RgNLineHCompound=%s",
(boxes[7]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.HCompound=%s", (boxes[5]->isChecked() ? "True" : "False"));
"FreeCAD.ActiveDocument.ActiveObject.OutLineHCompound=%s",
(boxes[8]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.Rg1LineHCompound=%s", (boxes[6]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.RgNLineHCompound=%s", (boxes[7]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.OutLineHCompound=%s", (boxes[8]->isChecked() ? "True" : "False"));
Gui::Command::doCommand(Gui::Command::Doc,
"FreeCAD.ActiveDocument.ActiveObject.IsoLineHCompound=%s", (boxes[9]->isChecked() ? "True" : "False"));
"FreeCAD.ActiveDocument.ActiveObject.IsoLineHCompound=%s",
(boxes[9]->isChecked() ? "True" : "False"));
}
Gui::Command::updateActive();
Gui::Command::commitCommand();

View File

@@ -37,7 +37,7 @@ namespace DrawingGui
/**
* Embed the panel into a task dialog.
*/
class TaskProjection : public Gui::TaskView::TaskDialog
class TaskProjection: public Gui::TaskView::TaskDialog
{
Q_OBJECT
@@ -49,9 +49,13 @@ public:
bool accept();
virtual QDialogButtonBox::StandardButtons getStandardButtons() const
{ return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; }
{
return QDialogButtonBox::Ok | QDialogButtonBox::Cancel;
}
virtual bool isAllowedAlterDocument(void) const
{ return true; }
{
return true;
}
private:
QWidget* widget;
@@ -59,8 +63,7 @@ private:
Gui::TaskView::TaskBox* taskbox;
};
} //namespace DrawingGui
}// namespace DrawingGui
#endif // DRAWINGGUI_TASKDIALOG
#endif// DRAWINGGUI_TASKDIALOG

File diff suppressed because it is too large Load Diff

View File

@@ -36,175 +36,198 @@
#include <Mod/Drawing/App/FeatureViewPart.h>
namespace DrawingGui {
namespace DrawingGui
{
class Ui_TaskOrthoViews;
class orthoview
{
public:
orthoview(App::Document * parent, App::DocumentObject * part, App::DocumentObject * page, Base::BoundBox3d * partbox);
orthoview(App::Document* parent,
App::DocumentObject* part,
App::DocumentObject* page,
Base::BoundBox3d* partbox);
~orthoview();
void set_data(int r_x, int r_y);
void set_projection(const gp_Ax2& cs);
void setPos(float = 0, float = 0);
void setScale(float newscale);
float getScale();
void deleteme();
void hidden(bool);
void smooth(bool);
void set_data(int r_x, int r_y);
void set_projection(const gp_Ax2& cs);
void setPos(float = 0, float = 0);
void setScale(float newscale);
float getScale();
void deleteme();
void hidden(bool);
void smooth(bool);
App::DocumentObject* getViewPart() {
App::DocumentObject* getViewPart()
{
return this_view;
}
private:
void calcCentre();
void calcCentre();
public: // these aren't used by orthoView, but just informational, hence public
bool ortho; // orthonometric? or axonometric
bool auto_scale; // scale for axonometric has not been manually changed?
int rel_x, rel_y; // relative position of this view
bool away, tri; // binary parameters for axonometric view
int axo; // 0 / 1 / 2 = iso / di / tri metric
gp_Dir up, right; // directions prior to rotations (ie, what was used to orientate the projection)
public: // these aren't used by orthoView, but just informational, hence public
bool ortho; // orthonometric? or axonometric
bool auto_scale; // scale for axonometric has not been manually changed?
int rel_x, rel_y;// relative position of this view
bool away, tri; // binary parameters for axonometric view
int axo; // 0 / 1 / 2 = iso / di / tri metric
gp_Dir up,
right;// directions prior to rotations (ie, what was used to orientate the projection)
private:
App::Document * parent_doc;
Drawing::FeatureViewPart * this_view;
App::Document* parent_doc;
Drawing::FeatureViewPart* this_view;
std::string myname;
float x, y; // 2D projection coords of bbox centre relative to origin
float cx, cy, cz; // coords of bbox centre in 3D space
float pageX, pageY; // required coords of centre of bbox projection on page
float scale; // scale of projection
gp_Dir X_dir, Y_dir, Z_dir; // directions of projection, X_dir makes x on page, Y_dir is y on page, Z_dir is out of page
std::string myname;
float x, y; // 2D projection coords of bbox centre relative to origin
float cx, cy, cz; // coords of bbox centre in 3D space
float pageX, pageY; // required coords of centre of bbox projection on page
float scale; // scale of projection
gp_Dir X_dir, Y_dir, Z_dir;// directions of projection, X_dir makes x on page, Y_dir is y on
// page, Z_dir is out of page
};
class OrthoViews
{
public:
OrthoViews(App::Document*, const char * pagename, const char * partname);
OrthoViews(App::Document*, const char* pagename, const char* partname);
~OrthoViews();
void set_primary(gp_Dir facing, gp_Dir right);
void add_view(int rel_x, int rel_y);
void del_view(int rel_x, int rel_y);
void del_all();
void set_projection(int proj);
void set_hidden(bool state);
void set_smooth(bool state);
void set_Axo(int rel_x, int rel_y, gp_Dir up, gp_Dir right, bool away = false, int axo = 0, bool tri = false);
void set_Axo(int rel_x, int rel_y);
void set_Axo_scale(int rel_x, int rel_y, float axo_scale);
void set_Ortho(int rel_x, int rel_y);
int is_Ortho(int rel_x, int rel_y);
bool get_Axo(int rel_x, int rel_y, int & axo, gp_Dir & up, gp_Dir & right, bool & away, bool & tri, float & axo_scale);
void auto_dims(bool setting);
void set_configs(float configs[5]);
void get_configs(float configs[5]);
void set_primary(gp_Dir facing, gp_Dir right);
void add_view(int rel_x, int rel_y);
void del_view(int rel_x, int rel_y);
void del_all();
void set_projection(int proj);
void set_hidden(bool state);
void set_smooth(bool state);
void set_Axo(int rel_x,
int rel_y,
gp_Dir up,
gp_Dir right,
bool away = false,
int axo = 0,
bool tri = false);
void set_Axo(int rel_x, int rel_y);
void set_Axo_scale(int rel_x, int rel_y, float axo_scale);
void set_Ortho(int rel_x, int rel_y);
int is_Ortho(int rel_x, int rel_y);
bool get_Axo(int rel_x,
int rel_y,
int& axo,
gp_Dir& up,
gp_Dir& right,
bool& away,
bool& tri,
float& axo_scale);
void auto_dims(bool setting);
void set_configs(float configs[5]);
void get_configs(float configs[5]);
private:
void set_orientation(int index);
void load_page(); // get page / titleblock dims from template
void choose_page(); // determine correct portion of page to use to avoid interference with title block
void set_all_orientations(); // update orientations of all views following change in primary view
void calc_layout_size(); // what's the real world size of chosen layout, excluding spaces
void calc_offsets();
void set_views();
void calc_scale();
void process_views();
int index(int rel_x, int rel_y);
void slotDeletedObject(const App::DocumentObject& Obj);
void slotDeletedDocument(const App::Document& Obj);
void set_orientation(int index);
void load_page();// get page / titleblock dims from template
void
choose_page();// determine correct portion of page to use to avoid interference with title block
void set_all_orientations();// update orientations of all views following change in primary view
void calc_layout_size(); // what's the real world size of chosen layout, excluding spaces
void calc_offsets();
void set_views();
void calc_scale();
void process_views();
int index(int rel_x, int rel_y);
void slotDeletedObject(const App::DocumentObject& Obj);
void slotDeletedDocument(const App::Document& Obj);
private:
std::vector<orthoview *> views;
Base::BoundBox3d bbox;
App::Document * parent_doc;
App::DocumentObject * part;
App::DocumentObject * page;
std::vector<orthoview*> views;
Base::BoundBox3d bbox;
App::Document* parent_doc;
App::DocumentObject* part;
App::DocumentObject* page;
int large[4]; // arrays containing page size info [margin_x, margin_y, size_x, size_y] = [x1, y1, x2-x1, y2-y1]
int small_h[4], small_v[4]; // page size avoiding title block, using maximum horizontal / vertical space
int * page_dims; // points to one of above arrays for which set of page dimensions to use
int block[4]; // title block info [corner x, corner y, width, height], eg [-1, 1, w, h] is in top left corner
bool title;
int * horiz, * vert; // points to min or max r_x / r_y depending upon which corner title block is in
int large[4];// arrays containing page size info [margin_x, margin_y, size_x, size_y] = [x1, y1,
// x2-x1, y2-y1]
int small_h[4],
small_v[4];// page size avoiding title block, using maximum horizontal / vertical space
int* page_dims;// points to one of above arrays for which set of page dimensions to use
int block[4];// title block info [corner x, corner y, width, height], eg [-1, 1, w, h] is in top
// left corner
bool title;
int *horiz,
*vert;// points to min or max r_x / r_y depending upon which corner title block is in
int rotate_coeff; // 1st (= -1) or 3rd (= 1) angle
int min_r_x, max_r_x; // extreme relative positions of views
int min_r_y, max_r_y; // " " "
float width, height, depth; // of non-scaled primary view
float layout_width, layout_height; // of non-scaled layout without spaces
float gap_x, gap_y, min_space; // required spacing between views
float offset_x, offset_y; // coords of centre of upper left view
float scale;
int num_gaps_x, num_gaps_y; // how many gaps between views/edges? = num of views in given direction + 1
gp_Ax2 primary; // coord system of primary view
int rotate_coeff; // 1st (= -1) or 3rd (= 1) angle
int min_r_x, max_r_x; // extreme relative positions of views
int min_r_y, max_r_y; // " " "
float width, height, depth; // of non-scaled primary view
float layout_width, layout_height;// of non-scaled layout without spaces
float gap_x, gap_y, min_space; // required spacing between views
float offset_x, offset_y; // coords of centre of upper left view
float scale;
int num_gaps_x,
num_gaps_y;// how many gaps between views/edges? = num of views in given direction + 1
gp_Ax2 primary;// coord system of primary view
bool hidden, smooth;
bool autodims;
bool hidden, smooth;
bool autodims;
boost::signals2::scoped_connection connectDocumentDeletedObject;
boost::signals2::scoped_connection connectApplicationDeletedDocument;
};
class TaskOrthoViews : public QWidget//: public Gui::TaskView::TaskBox
class TaskOrthoViews: public QWidget//: public Gui::TaskView::TaskBox
{
Q_OBJECT
public:
TaskOrthoViews(QWidget *parent = nullptr);
TaskOrthoViews(QWidget* parent = nullptr);
~TaskOrthoViews();
bool user_input();
void clean_up();
protected Q_SLOTS:
void ShowContextMenu(const QPoint & pos);
void ShowContextMenu(const QPoint& pos);
void setPrimary(int dir);
void cb_toggled(bool toggle);
void projectionChanged(int index);
void hidden(int i);
void smooth(int i);
void toggle_auto(int i);
void data_entered(const QString & text);
void data_entered(const QString& text);
void change_axo(int p = 3);
void axo_button();
void axo_scale(const QString & text);
void axo_scale(const QString& text);
void text_return();
protected:
void changeEvent(QEvent * e);
void changeEvent(QEvent* e);
private:
void setup_axo_tab();
void set_configs();
private:
//class Private;
Ui_TaskOrthoViews * ui;
// class Private;
Ui_TaskOrthoViews* ui;
OrthoViews * orthos;
QCheckBox * c_boxes[5][5]; // matrix of pointers to gui checkboxes
QLineEdit * inputs[5]; // pointers to manual position/scale boxes
OrthoViews* orthos;
QCheckBox* c_boxes[5][5];// matrix of pointers to gui checkboxes
QLineEdit* inputs[5]; // pointers to manual position/scale boxes
float data[5]; // scale, x_pos, y_pos, horiz, vert
int axo_r_x, axo_r_y; // relative position of axo view currently being edited
bool txt_return; // flag to show if return was pressed while editing a text box;
float data[5]; // scale, x_pos, y_pos, horiz, vert
int axo_r_x, axo_r_y;// relative position of axo view currently being edited
bool txt_return; // flag to show if return was pressed while editing a text box;
};
//////////////////////////////////////////////////////////////
/// simulation dialog for the TaskView
class TaskDlgOrthoViews : public Gui::TaskView::TaskDialog
class TaskDlgOrthoViews: public Gui::TaskView::TaskDialog
{
Q_OBJECT
@@ -219,12 +242,11 @@ public:
void clicked(int);
private:
TaskOrthoViews * widget;
TaskOrthoViews* widget;
Gui::TaskView::TaskBox* taskbox;
};
} //namespace DrawingGui
}// namespace DrawingGui
#endif // GUI_TASKVIEW_OrthoViews_H
#endif// GUI_TASKVIEW_OrthoViews_H

View File

@@ -22,8 +22,8 @@
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QMenu>
# include <QTimer>
#include <QMenu>
#include <QTimer>
#endif
#include <App/DocumentObject.h>
@@ -45,12 +45,12 @@ PROPERTY_SOURCE(DrawingGui::ViewProviderDrawingPage, Gui::ViewProviderDocumentOb
// Construction/Destruction
ViewProviderDrawingPage::ViewProviderDrawingPage()
: view(nullptr)
: view(nullptr)
{
sPixmap = "Page";
ADD_PROPERTY(HintScale,(10.0));
ADD_PROPERTY(HintOffsetX,(10.0));
ADD_PROPERTY(HintOffsetY,(10.0));
ADD_PROPERTY(HintScale, (10.0));
ADD_PROPERTY(HintOffsetX, (10.0));
ADD_PROPERTY(HintOffsetY, (10.0));
// do not show this in the property editor
Visibility.setStatus(App::Property::Hidden, true);
@@ -58,10 +58,9 @@ ViewProviderDrawingPage::ViewProviderDrawingPage()
}
ViewProviderDrawingPage::~ViewProviderDrawingPage()
{
}
{}
void ViewProviderDrawingPage::attach(App::DocumentObject *pcFeat)
void ViewProviderDrawingPage::attach(App::DocumentObject* pcFeat)
{
// call parent attach method
ViewProviderDocumentObject::attach(pcFeat);
@@ -109,25 +108,26 @@ void ViewProviderDrawingPage::updateData(const App::Property* prop)
if (std::string(getPageObject()->PageResult.getValue()) != "") {
if (view) {
view->load(QString::fromUtf8(getPageObject()->PageResult.getValue()));
if (view->isHidden())
if (view->isHidden()) {
QTimer::singleShot(300, view, SLOT(viewAll()));
else
}
else {
view->viewAll();
}
}
}
}
else if (pcObject && prop == &pcObject->Label) {
if (view){
if (view) {
const char* objname = pcObject->Label.getValue();
view->setObjectName(QString::fromUtf8(objname));
Gui::Document* doc = Gui::Application::Instance->getDocument
(pcObject->getDocument());
Gui::Document* doc = Gui::Application::Instance->getDocument(pcObject->getDocument());
view->onRelabel(doc);
}
}
}
bool ViewProviderDrawingPage::onDelete(const std::vector<std::string> & items)
bool ViewProviderDrawingPage::onDelete(const std::vector<std::string>& items)
{
if (view) {
view->parentWidget()->deleteLater();
@@ -157,9 +157,8 @@ bool ViewProviderDrawingPage::doubleClicked(void)
DrawingView* ViewProviderDrawingPage::showDrawingView()
{
if (!view){
Gui::Document* doc = Gui::Application::Instance->getDocument
(this->pcObject->getDocument());
if (!view) {
Gui::Document* doc = Gui::Application::Instance->getDocument(this->pcObject->getDocument());
view = new DrawingView(doc, Gui::getMainWindow());
view->setWindowIcon(Gui::BitmapFactory().pixmap("actions/drawing-landscape"));

View File

@@ -30,14 +30,16 @@
#include "DrawingView.h"
namespace Drawing{
class FeaturePage;
namespace Drawing
{
class FeaturePage;
}
namespace DrawingGui {
namespace DrawingGui
{
class DrawingGuiExport ViewProviderDrawingPage : public Gui::ViewProviderDocumentObjectGroup
class DrawingGuiExport ViewProviderDrawingPage: public Gui::ViewProviderDocumentObjectGroup
{
PROPERTY_HEADER(DrawingGui::ViewProviderDrawingPage);
@@ -47,13 +49,16 @@ public:
/// destructor
virtual ~ViewProviderDrawingPage();
App::PropertyFloat HintScale;
App::PropertyFloat HintOffsetX;
App::PropertyFloat HintOffsetY;
App::PropertyFloat HintScale;
App::PropertyFloat HintOffsetX;
App::PropertyFloat HintOffsetY;
virtual void attach(App::DocumentObject *);
virtual void attach(App::DocumentObject*);
virtual void setDisplayMode(const char* ModeName);
virtual bool useNewSelectionModel(void) const {return false;}
virtual bool useNewSelectionModel(void) const
{
return false;
}
/// returns a list of all possible modes
virtual std::vector<std::string> getDisplayModes(void) const;
/// Hides the view provider
@@ -65,7 +70,7 @@ public:
virtual bool doubleClicked(void);
void setupContextMenu(QMenu*, QObject*, const char*);
virtual void updateData(const App::Property*);
virtual bool onDelete(const std::vector<std::string> &);
virtual bool onDelete(const std::vector<std::string>&);
Drawing::FeaturePage* getPageObject() const;
@@ -77,8 +82,7 @@ private:
QPointer<DrawingView> view;
};
} // namespace DrawingGui
}// namespace DrawingGui
#endif // DRAWINGGUI_VIEWPROVIDERPAGE_H
#endif// DRAWINGGUI_VIEWPROVIDERPAGE_H

View File

@@ -42,10 +42,9 @@ ViewProviderDrawingView::ViewProviderDrawingView()
}
ViewProviderDrawingView::~ViewProviderDrawingView()
{
}
{}
void ViewProviderDrawingView::attach(App::DocumentObject *pcFeat)
void ViewProviderDrawingView::attach(App::DocumentObject* pcFeat)
{
// call parent attach method
ViewProviderDocumentObject::attach(pcFeat);
@@ -67,15 +66,17 @@ void ViewProviderDrawingView::show(void)
ViewProviderDocumentObject::show();
App::DocumentObject* obj = getObject();
if (!obj || obj->isRestoring())
if (!obj || obj->isRestoring()) {
return;
}
if (obj->getTypeId().isDerivedFrom(Drawing::FeatureView::getClassTypeId())) {
// The 'Visible' property is marked as 'Output'. To update the drawing on recompute
// the parent page object is touched.
static_cast<Drawing::FeatureView*>(obj)->Visible.setValue(true);
std::vector<App::DocumentObject*> inp = obj->getInList();
for (std::vector<App::DocumentObject*>::iterator it = inp.begin(); it != inp.end(); ++it)
for (std::vector<App::DocumentObject*>::iterator it = inp.begin(); it != inp.end(); ++it) {
(*it)->touch();
}
}
}
@@ -84,15 +85,17 @@ void ViewProviderDrawingView::hide(void)
ViewProviderDocumentObject::hide();
App::DocumentObject* obj = getObject();
if (!obj || obj->isRestoring())
if (!obj || obj->isRestoring()) {
return;
}
if (obj->getTypeId().isDerivedFrom(Drawing::FeatureView::getClassTypeId())) {
// The 'Visible' property is marked as 'Output'. To update the drawing on recompute
// the parent page object is touched.
static_cast<Drawing::FeatureView*>(obj)->Visible.setValue(false);
std::vector<App::DocumentObject*> inp = obj->getInList();
for (std::vector<App::DocumentObject*>::iterator it = inp.begin(); it != inp.end(); ++it)
for (std::vector<App::DocumentObject*>::iterator it = inp.begin(); it != inp.end(); ++it) {
(*it)->touch();
}
}
}
@@ -112,19 +115,20 @@ void ViewProviderDrawingView::finishRestoring()
}
void ViewProviderDrawingView::updateData(const App::Property*)
{
}
{}
// Python viewprovider -----------------------------------------------------------------------
namespace Gui {
namespace Gui
{
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(DrawingGui::ViewProviderDrawingViewPython, DrawingGui::ViewProviderDrawingView)
PROPERTY_SOURCE_TEMPLATE(DrawingGui::ViewProviderDrawingViewPython,
DrawingGui::ViewProviderDrawingView)
/// @endcond
// explicit template instantiation
template class DrawingGuiExport ViewProviderPythonFeatureT<DrawingGui::ViewProviderDrawingView>;
}
}// namespace Gui
// ----------------------------------------------------------------------------
@@ -140,10 +144,9 @@ ViewProviderDrawingClip::ViewProviderDrawingClip()
}
ViewProviderDrawingClip::~ViewProviderDrawingClip()
{
}
{}
void ViewProviderDrawingClip::attach(App::DocumentObject *pcFeat)
void ViewProviderDrawingClip::attach(App::DocumentObject* pcFeat)
{
// call parent attach method
ViewProviderDocumentObject::attach(pcFeat);
@@ -166,15 +169,17 @@ void ViewProviderDrawingClip::show(void)
ViewProviderDocumentObjectGroup::show();
App::DocumentObject* obj = getObject();
if (!obj || obj->isRestoring())
if (!obj || obj->isRestoring()) {
return;
}
if (obj->getTypeId().isDerivedFrom(Drawing::FeatureClip::getClassTypeId())) {
// The 'Visible' property is marked as 'Output'. To update the drawing on recompute
// the parent page object is touched.
static_cast<Drawing::FeatureClip*>(obj)->Visible.setValue(true);
std::vector<App::DocumentObject*> inp = obj->getInList();
for (std::vector<App::DocumentObject*>::iterator it = inp.begin(); it != inp.end(); ++it)
for (std::vector<App::DocumentObject*>::iterator it = inp.begin(); it != inp.end(); ++it) {
(*it)->touch();
}
}
}
@@ -183,15 +188,17 @@ void ViewProviderDrawingClip::hide(void)
ViewProviderDocumentObjectGroup::hide();
App::DocumentObject* obj = getObject();
if (!obj || obj->isRestoring())
if (!obj || obj->isRestoring()) {
return;
}
if (obj->getTypeId().isDerivedFrom(Drawing::FeatureClip::getClassTypeId())) {
// The 'Visible' property is marked as 'Output'. To update the drawing on recompute
// the parent page object is touched.
static_cast<Drawing::FeatureClip*>(obj)->Visible.setValue(false);
std::vector<App::DocumentObject*> inp = obj->getInList();
for (std::vector<App::DocumentObject*>::iterator it = inp.begin(); it != inp.end(); ++it)
for (std::vector<App::DocumentObject*>::iterator it = inp.begin(); it != inp.end(); ++it) {
(*it)->touch();
}
}
}
@@ -211,5 +218,4 @@ void ViewProviderDrawingClip::finishRestoring()
}
void ViewProviderDrawingClip::updateData(const App::Property*)
{
}
{}

View File

@@ -26,10 +26,11 @@
#include <Gui/ViewProviderDocumentObjectGroup.h>
namespace DrawingGui {
namespace DrawingGui
{
class DrawingGuiExport ViewProviderDrawingView : public Gui::ViewProviderDocumentObject
class DrawingGuiExport ViewProviderDrawingView: public Gui::ViewProviderDocumentObject
{
PROPERTY_HEADER(DrawingGui::ViewProviderDrawingView);
@@ -40,9 +41,12 @@ public:
virtual ~ViewProviderDrawingView();
virtual void attach(App::DocumentObject *);
virtual void attach(App::DocumentObject*);
virtual void setDisplayMode(const char* ModeName);
virtual bool useNewSelectionModel(void) const {return false;}
virtual bool useNewSelectionModel(void) const
{
return false;
}
/// returns a list of all possible modes
virtual std::vector<std::string> getDisplayModes(void) const;
virtual void updateData(const App::Property*);
@@ -61,7 +65,7 @@ public:
using ViewProviderDrawingViewPython = Gui::ViewProviderPythonFeatureT<ViewProviderDrawingView>;
class DrawingGuiExport ViewProviderDrawingClip : public Gui::ViewProviderDocumentObjectGroup
class DrawingGuiExport ViewProviderDrawingClip: public Gui::ViewProviderDocumentObjectGroup
{
PROPERTY_HEADER(DrawingGui::ViewProviderDrawingClip);
@@ -72,9 +76,12 @@ public:
virtual ~ViewProviderDrawingClip();
virtual void attach(App::DocumentObject *);
virtual void attach(App::DocumentObject*);
virtual void setDisplayMode(const char* ModeName);
virtual bool useNewSelectionModel(void) const {return false;}
virtual bool useNewSelectionModel(void) const
{
return false;
}
/// returns a list of all possible modes
virtual std::vector<std::string> getDisplayModes(void) const;
virtual void updateData(const App::Property*);
@@ -91,8 +98,7 @@ public:
//@}
};
} // namespace DrawingGui
}// namespace DrawingGui
#endif // DRAWINGGUI_VIEWPROVIDERVIEW_H
#endif// DRAWINGGUI_VIEWPROVIDERVIEW_H

View File

@@ -30,7 +30,7 @@
using namespace DrawingGui;
#if 0 // needed for Qt's lupdate utility
#if 0// needed for Qt's lupdate utility
qApp->translate("Workbench", "Drawing");
#endif
@@ -38,12 +38,10 @@ using namespace DrawingGui;
TYPESYSTEM_SOURCE(DrawingGui::Workbench, Gui::StdWorkbench)
Workbench::Workbench()
{
}
{}
Workbench::~Workbench()
{
}
{}
Gui::MenuItem* Workbench::setupMenuBar() const
{
@@ -100,7 +98,7 @@ Gui::ToolBarItem* Workbench::setupCommandBars() const
*img << "Drawing_Open";
img = new Gui::ToolBarItem(root);
img->setCommand("Drawing types");
//*img << "Drawing_NewA3Landscape";
//*img << "Drawing_NewA3Landscape";
*img << "Drawing_NewPage";
*img << "Drawing_OrthoViews";
*img << "Drawing_OpenBrowserView";
@@ -112,4 +110,3 @@ Gui::ToolBarItem* Workbench::setupCommandBars() const
*img << "Drawing_NewView";
return root;
}

View File

@@ -26,12 +26,13 @@
#include <Gui/Workbench.h>
namespace DrawingGui {
namespace DrawingGui
{
/**
* @author Werner Mayer
*/
class Workbench : public Gui::StdWorkbench
class Workbench: public Gui::StdWorkbench
{
TYPESYSTEM_HEADER();
@@ -45,7 +46,7 @@ protected:
Gui::ToolBarItem* setupCommandBars() const;
};
} // namespace DrawingGui
}// namespace DrawingGui
#endif // DRAWING_WORKBENCH_H
#endif// DRAWING_WORKBENCH_H

View File

@@ -1,29 +1,28 @@
# FreeCAD init script of the Image module
# (c) 2001 Juergen Riegel
#***************************************************************************
#* (c) Juergen Riegel (juergen.riegel@web.de) 2002 *
#* *
#* This file is part of the FreeCAD CAx development system. *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* FreeCAD is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Lesser General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with FreeCAD; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#* Juergen Riegel 2002 *
#***************************************************************************/
# ***************************************************************************
# * (c) Juergen Riegel (juergen.riegel@web.de) 2002 *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# * Juergen Riegel 2002 *
# ***************************************************************************/
FreeCAD.Console.PrintLog("Drawing became obsolete in 0.17; "
"consider using TechDraw instead.\n")
FreeCAD.Console.PrintLog("Drawing became obsolete in 0.17; " "consider using TechDraw instead.\n")

View File

@@ -5,52 +5,56 @@
# This is the second one of three init scripts, the third one
# runs when the gui is up
#***************************************************************************
#* (c) Juergen Riegel (juergen.riegel@web.de) 2002
#* *
#* This file is part of the FreeCAD CAx development system. *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* FreeCAD is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Lesser General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with FreeCAD; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#* Juergen Riegel 2002 *
#***************************************************************************/
# ***************************************************************************
# * (c) Juergen Riegel (juergen.riegel@web.de) 2002
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# * Juergen Riegel 2002 *
# ***************************************************************************/
class DrawingWorkbench (Workbench):
class DrawingWorkbench(Workbench):
"Drawing workbench object"
def __init__(self):
self.__class__.Icon = FreeCAD.getResourceDir() + "Mod/Drawing/Resources/icons/DrawingWorkbench.svg"
self.__class__.Icon = (
FreeCAD.getResourceDir() + "Mod/Drawing/Resources/icons/DrawingWorkbench.svg"
)
self.__class__.MenuText = "Drawing"
self.__class__.ToolTip = "Drawing workbench"
def Initialize(self):
# load the module
import DrawingGui
def Activated(self):
FreeCAD.Console.PrintWarning("Drawing became obsolete in 0.17; "
"consider using TechDraw instead.\n")
FreeCAD.Console.PrintWarning(
"Drawing became obsolete in 0.17; " "consider using TechDraw instead.\n"
)
def GetClassName(self):
return "DrawingGui::Workbench"
Gui.addWorkbench(DrawingWorkbench())
# Append the open handler
FreeCAD.addImportType("Drawing (*.svg *.svgz)","DrawingGui")
FreeCAD.addExportType("Drawing (*.svg *.svgz *.dxf)","DrawingGui")
FreeCAD.addImportType("Drawing (*.svg *.svgz)", "DrawingGui")
FreeCAD.addExportType("Drawing (*.svg *.svgz *.dxf)", "DrawingGui")

View File

@@ -2,4 +2,3 @@
* \ingroup CWORKBENCHES
* \brief Manages output of 2D sheets from FreeCAD documents
*/