Merge branch 'master' of ssh://git.code.sf.net/p/free-cad/code

This commit is contained in:
wmayer 2014-01-12 18:49:24 +01:00
commit 99d10a6e49
24 changed files with 3801 additions and 2894 deletions

View File

@ -194,7 +194,7 @@ App::DocumentObjectExecReturn *FeatureViewPart::execute(void)
bool smooth = ShowSmoothLines.getValue();
try {
ProjectionAlgos Alg(ProjectionAlgos::invertY(shape),Dir);
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

View File

@ -90,7 +90,7 @@ using namespace std;
ProjectionAlgos::ProjectionAlgos(const TopoDS_Shape &Input, const Base::Vector3d &Dir)
ProjectionAlgos::ProjectionAlgos(const TopoDS_Shape &Input, const Base::Vector3d &Dir)
: Input(Input), Direction(Dir)
{
execute();
@ -99,6 +99,13 @@ ProjectionAlgos::ProjectionAlgos(const TopoDS_Shape &Input, const Base::Vector3d
ProjectionAlgos::~ProjectionAlgos()
{
}
/*
// no longer used, replaced invertY by adding
// << " transform=\"scale(1,-1)\"" << endl
// to getSVG(...) below.
// invertY, as here, wasn't right for intended purpose - always reflected in model Y direction rather
// than SVG projection Y direction. Also better to reflect about (0,0,0) rather than bbox centre
TopoDS_Shape ProjectionAlgos::invertY(const TopoDS_Shape& shape)
{
@ -113,6 +120,7 @@ TopoDS_Shape ProjectionAlgos::invertY(const TopoDS_Shape& shape)
BRepBuilderAPI_Transform mkTrf(shape, mat);
return mkTrf.Shape();
}
*/
void ProjectionAlgos::execute(void)
{
@ -154,14 +162,15 @@ std::string ProjectionAlgos::getSVG(ExtractionType type, double scale, double to
if (!H.IsNull() && (type & WithHidden)) {
double width = hiddenscale;
BRepMesh::Mesh(H,tolerance);
result << "<g"
result << "<g"
//<< " id=\"" << ViewName << "\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
<< " stroke-dasharray=\"0.2,0.1\"" << endl
<< " fill=\"none\"" << endl
<< " transform=\"scale(1,-1)\"" << endl
<< " >" << endl
<< output.exportEdges(H)
<< "</g>" << endl;
@ -169,14 +178,15 @@ std::string ProjectionAlgos::getSVG(ExtractionType type, double scale, double to
if (!HO.IsNull() && (type & WithHidden)) {
double width = hiddenscale;
BRepMesh::Mesh(HO,tolerance);
result << "<g"
result << "<g"
//<< " id=\"" << ViewName << "\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
<< " stroke-dasharray=\"0.02,0.1\"" << endl
<< " fill=\"none\"" << endl
<< " transform=\"scale(1,-1)\"" << endl
<< " >" << endl
<< output.exportEdges(HO)
<< "</g>" << endl;
@ -184,13 +194,14 @@ std::string ProjectionAlgos::getSVG(ExtractionType type, double scale, double to
if (!VO.IsNull()) {
double width = scale;
BRepMesh::Mesh(VO,tolerance);
result << "<g"
result << "<g"
//<< " id=\"" << ViewName << "\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
<< " fill=\"none\"" << endl
<< " transform=\"scale(1,-1)\"" << endl
<< " >" << endl
<< output.exportEdges(VO)
<< "</g>" << endl;
@ -198,13 +209,14 @@ std::string ProjectionAlgos::getSVG(ExtractionType type, double scale, double to
if (!V.IsNull()) {
double width = scale;
BRepMesh::Mesh(V,tolerance);
result << "<g"
result << "<g"
//<< " id=\"" << ViewName << "\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
<< " fill=\"none\"" << endl
<< " transform=\"scale(1,-1)\"" << endl
<< " >" << endl
<< output.exportEdges(V)
<< "</g>" << endl;
@ -212,13 +224,14 @@ std::string ProjectionAlgos::getSVG(ExtractionType type, double scale, double to
if (!V1.IsNull() && (type & WithSmooth)) {
double width = scale;
BRepMesh::Mesh(V1,tolerance);
result << "<g"
result << "<g"
//<< " id=\"" << ViewName << "\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
<< " fill=\"none\"" << endl
<< " transform=\"scale(1,-1)\"" << endl
<< " >" << endl
<< output.exportEdges(V1)
<< "</g>" << endl;
@ -226,14 +239,15 @@ std::string ProjectionAlgos::getSVG(ExtractionType type, double scale, double to
if (!H1.IsNull() && (type & WithSmooth) && (type & WithHidden)) {
double width = hiddenscale;
BRepMesh::Mesh(H1,tolerance);
result << "<g"
result << "<g"
//<< " id=\"" << ViewName << "\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
<< " stroke-dasharray=\"0.09,0.05\"" << endl
<< " fill=\"none\"" << endl
<< " transform=\"scale(1,-1)\"" << endl
<< " >" << endl
<< output.exportEdges(H1)
<< "</g>" << endl;
@ -247,7 +261,7 @@ std::string ProjectionAlgos::getDXF(ExtractionType type, double scale, double to
{
std::stringstream result;
DXFOutput output;
result << "0" << endl
<< "SECTION" << endl
@ -257,9 +271,9 @@ std::string ProjectionAlgos::getDXF(ExtractionType type, double scale, double to
if (!H.IsNull() && (type & WithHidden)) {
//float width = 0.15f/scale;
BRepMesh::Mesh(H,tolerance);
result //<< "<g"
result //<< "<g"
//<< " id=\"" << ViewName << "\"" << endl
/*<< " stroke=\"rgb(0, 0, 0)\"" << endl
/*<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
@ -272,9 +286,9 @@ std::string ProjectionAlgos::getDXF(ExtractionType type, double scale, double to
if (!HO.IsNull() && (type & WithHidden)) {
//float width = 0.15f/scale;
BRepMesh::Mesh(HO,tolerance);
result //<< "<g"
result //<< "<g"
//<< " id=\"" << ViewName << "\"" << endl
/*<< " stroke=\"rgb(0, 0, 0)\"" << endl
/*<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
@ -287,10 +301,10 @@ std::string ProjectionAlgos::getDXF(ExtractionType type, double scale, double to
if (!VO.IsNull()) {
//float width = 0.35f/scale;
BRepMesh::Mesh(VO,tolerance);
result //<< "<g"
result //<< "<g"
//<< " id=\"" << ViewName << "\"" << endl
/*<< " stroke=\"rgb(0, 0, 0)\"" << endl
/*<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
@ -303,9 +317,9 @@ std::string ProjectionAlgos::getDXF(ExtractionType type, double scale, double to
if (!V.IsNull()) {
//float width = 0.35f/scale;
BRepMesh::Mesh(V,tolerance);
result //<< "<g"
result //<< "<g"
//<< " id=\"" << ViewName << "\"" << endl
/*<< " stroke=\"rgb(0, 0, 0)\"" << endl
/*<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
@ -319,10 +333,10 @@ std::string ProjectionAlgos::getDXF(ExtractionType type, double scale, double to
if (!V1.IsNull() && (type & WithSmooth)) {
//float width = 0.35f/scale;
BRepMesh::Mesh(V1,tolerance);
result //<< "<g"
result //<< "<g"
//<< " id=\"" << ViewName << "\"" << endl
/* << " stroke=\"rgb(0, 0, 0)\"" << endl
/* << " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl
<< " stroke-linejoin=\"miter\"" << endl
@ -335,9 +349,9 @@ std::string ProjectionAlgos::getDXF(ExtractionType type, double scale, double to
if (!H1.IsNull() && (type & WithSmooth) && (type & WithHidden)) {
//float width = 0.15f/scale;
BRepMesh::Mesh(H1,tolerance);
result //<< "<g"
result //<< "<g"
//<< " id=\"" << ViewName << "\"" << endl
/*<< " stroke=\"rgb(0, 0, 0)\"" << endl
/*<< " stroke=\"rgb(0, 0, 0)\"" << endl
<< " stroke-width=\"" << width << "\"" << endl
<< " stroke-linecap=\"butt\"" << endl

View File

@ -43,9 +43,9 @@ public:
virtual ~ProjectionAlgos();
void execute(void);
static TopoDS_Shape invertY(const TopoDS_Shape&);
// static TopoDS_Shape invertY(const TopoDS_Shape&);
enum ExtractionType {
enum ExtractionType {
Plain = 0,
WithHidden = 1,
WithSmooth = 2

File diff suppressed because it is too large Load Diff

View File

@ -28,53 +28,127 @@
#include "ui_TaskOrthoViews.h"
#include <Base/BoundBox.h>
#include <gp_Ax2.hxx>
#include <vector>
#include <Mod/Drawing/App/FeatureViewPart.h>
class Ui_TaskOrthoViews;
using namespace std;
namespace DrawingGui {
class orthoView
class orthoview
{
public:
orthoView(std::string, const char *, const char *, Base::BoundBox3d);
~orthoView();
orthoview(App::Document * parent, App::DocumentObject * part, App::DocumentObject * page, Base::BoundBox3d * partbox);
~orthoview();
void activate(bool);
void setDir(int);
void setDir(float,float,float,float,int);
void setPos(float = 0, float = 0);
void setScale(float);
void setOrientation(int);
void deleteme();
void hidden(int);
void smooth(int);
public:
bool active;
float width;
float height;
void set_data(int r_x, int r_y);
void set_projection(gp_Ax2 cs);
void setPos(float = 0, float = 0);
void setScale(float newscale);
float getScale();
void deleteme();
void hidden(bool);
void smooth(bool);
private:
void calcCentre();
void updateView();
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)
private:
std::string myname;
Base::BoundBox3d mybox;
int dir;
float angle;
float n[3];
int orientation;
float x, y;
float pageX, pageY;
float scale;
bool axo;
float vert[3];
App::Document * parent_doc;
Drawing::FeatureViewPart * this_view;
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(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]);
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);
private:
vector<orthoview *> views;
Base::BoundBox3d bbox;
App::Document * parent_doc;
App::DocumentObject * part;
App::DocumentObject * page;
string page_name, part_name;
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
bool hidden, smooth;
bool autodims;
};
class TaskOrthoViews : public QWidget//: public Gui::TaskView::TaskBox
@ -85,70 +159,43 @@ public:
TaskOrthoViews(QWidget *parent = 0);
~TaskOrthoViews();
bool user_input();
void clean_up(bool);
void clean_up();
protected Q_SLOTS:
void setPrimary(int);
void setRotate(int);
void cb_toggled(bool);
void projectionChanged(int);
void hidden(int);
void smooth(int);
void toggle_auto(int);
void data_entered();
void axoChanged(int);
void axoTopChanged(int);
void axo_flip();
void axoScale();
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 change_axo(int p = 3);
void axo_button();
void axo_scale(const QString & text);
void text_return();
protected:
void changeEvent(QEvent *);
void changeEvent(QEvent * e);
private:
void pagesize(std::string&);
void autodims();
void compute();
void validate_cbs();
void view_data(int, int, int &, int &);
void updateSecondaries();
void set_axo();
void setup_axo_tab();
void set_configs();
private:
class Private;
//class Private;
Ui_TaskOrthoViews * ui;
orthoView * views[4];
QCheckBox * c_boxes[5][5]; //matrix of pointers to gui checkboxes
QLineEdit * inputs[5]; //pointers to manual position/scale boxes
float * data[5]; //pointers to scale, x_pos, y_pos, horiz, vert
int map1[4][3][2]; //contains view directions and rotations for vertical secondary positions, for primaries 1,2,3,4
int map2[4][3][2]; //contains view directions and rotations for H and V secondary positions, primaries 5,6
float axonometric[3][6][4][4]; //contains view direction vectors and rotations for axonometric views
OrthoViews * orthos;
QCheckBox * c_boxes[5][5]; // matrix of pointers to gui checkboxes
QLineEdit * inputs[5]; // pointers to manual position/scale boxes
int view_status[4][4]; //matrix containing status of four orthoView objects (in use, axo, rel x, rel y)
int view_count; //number of active views
int primary; //view direction of primary view
float x_pos, y_pos; //x and y coords for primary view
int rotate; //rotate primary view clockwise by rotate*90
int proj; //first (=-1) or third (=1) angle projection
float scale; //scale of drawing
bool autoscale; //whether or not to run autodims
float horiz, vert; //centre-centre distances
bool axo_flipped;
int axo;
float pagewidth, pageheight; //these are actually the available width and height, calculated in constructor.
float pageh1, pageh2; //h1 - total usable page height, h2 - total height allowing for info box.
int margin;
int min_space; //minimum space between views, and page edge
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;
};
//////////////////////////////////////////////////////////////
@ -162,20 +209,15 @@ public:
TaskDlgOrthoViews();
~TaskDlgOrthoViews();
public:
void open();
bool accept();
bool reject();
void clicked(int);
// QDialogButtonBox::StandardButtons getStandardButtons() const
// { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; }
private:
TaskOrthoViews * widget;
Gui::TaskView::TaskBox* taskbox;
};
} //namespace DrawingGui

View File

@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>259</width>
<height>496</height>
<width>250</width>
<height>486</height>
</rect>
</property>
<property name="sizePolicy">
@ -31,7 +31,7 @@
<item row="3" column="1">
<widget class="QCheckBox" name="cb12">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -39,6 +39,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -50,7 +56,7 @@
<item row="4" column="1">
<widget class="QCheckBox" name="cb13">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -58,6 +64,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -69,7 +81,7 @@
<item row="4" column="2">
<widget class="QCheckBox" name="cb23">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -77,6 +89,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -88,7 +106,7 @@
<item row="4" column="3">
<widget class="QCheckBox" name="cb33">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -96,6 +114,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -107,7 +131,7 @@
<item row="2" column="1">
<widget class="QCheckBox" name="cb11">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -115,6 +139,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -132,7 +162,7 @@
<item row="2" column="3">
<widget class="QCheckBox" name="cb31">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -140,6 +170,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -151,7 +187,7 @@
<item row="2" column="2">
<widget class="QCheckBox" name="cb21">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -159,6 +195,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -170,7 +212,7 @@
<item row="3" column="3">
<widget class="QCheckBox" name="cb32">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -178,6 +220,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -189,7 +237,7 @@
<item row="5" column="2">
<widget class="QCheckBox" name="cb24">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -197,6 +245,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -208,7 +262,7 @@
<item row="1" column="2">
<widget class="QCheckBox" name="cb20">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -216,6 +270,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -227,7 +287,7 @@
<item row="3" column="4">
<widget class="QCheckBox" name="cb42">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -235,6 +295,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -264,7 +330,7 @@
<string/>
</property>
<property name="checked">
<bool>false</bool>
<bool>true</bool>
</property>
</widget>
</item>
@ -281,7 +347,7 @@
<item row="3" column="0">
<widget class="QCheckBox" name="cb02">
<property name="enabled">
<bool>false</bool>
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
@ -289,6 +355,12 @@
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="contextMenuPolicy">
<enum>Qt::CustomContextMenu</enum>
</property>
<property name="toolTip">
<string>Right click for axonometric settings</string>
</property>
<property name="layoutDirection">
<enum>Qt::RightToLeft</enum>
</property>
@ -393,7 +465,7 @@
<bool>false</bool>
</property>
<property name="text">
<string>Primary x / y</string>
<string>Top left x / y</string>
</property>
<property name="margin">
<number>2</number>
@ -441,7 +513,7 @@
<bool>false</bool>
</property>
<property name="text">
<string>Secondary dx / dy</string>
<string>Spacing dx / dy </string>
</property>
<property name="margin">
<number>2</number>
@ -507,8 +579,59 @@
<string>Axonometric</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_7">
<item row="0" column="0">
<item row="1" column="0" rowspan="2">
<layout class="QGridLayout" name="gridLayout_6">
<item row="2" column="0">
<widget class="QLabel" name="label_9">
<property name="text">
<string> Axis out and right</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_11">
<property name="text">
<string> Vertical tilt</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="axoUp">
<property name="enabled">
<bool>true</bool>
</property>
<item>
<property name="text">
<string>X +ve</string>
</property>
</item>
<item>
<property name="text">
<string>Y +ve</string>
</property>
</item>
<item>
<property name="text">
<string>Z +ve</string>
</property>
</item>
<item>
<property name="text">
<string>X -ve</string>
</property>
</item>
<item>
<property name="text">
<string>Y -ve</string>
</property>
</item>
<item>
<property name="text">
<string>Z -ve</string>
</property>
</item>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="axoProj">
<property name="enabled">
@ -531,17 +654,7 @@
</item>
</widget>
</item>
<item row="4" column="1">
<widget class="QPushButton" name="flip">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Switch direction</string>
</property>
</widget>
</item>
<item row="3" column="0">
<item row="4" column="0">
<widget class="QLabel" name="label_10">
<property name="text">
<string> Scale</string>
@ -558,95 +671,77 @@
<item row="1" column="0">
<widget class="QLabel" name="label_8">
<property name="text">
<string> Top face</string>
<string> Axis aligned up</string>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_9">
<property name="text">
<string> Left face</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="axoTop">
<property name="enabled">
<bool>true</bool>
</property>
<item>
<property name="text">
<string>Front</string>
</property>
</item>
<item>
<property name="text">
<string>Right</string>
</property>
</item>
<item>
<property name="text">
<string>Back</string>
</property>
</item>
<item>
<property name="text">
<string>Left</string>
</property>
</item>
<item>
<property name="text">
<string>Top</string>
</property>
</item>
<item>
<property name="text">
<string>Bottom</string>
</property>
</item>
</widget>
</item>
<item row="2" column="1">
<widget class="QComboBox" name="axoLeft">
<widget class="QComboBox" name="axoRight">
<property name="enabled">
<bool>true</bool>
</property>
<item>
<property name="text">
<string>Right</string>
<string>Y +ve</string>
</property>
</item>
<item>
<property name="text">
<string>Left</string>
<string>Z +ve</string>
</property>
</item>
<item>
<property name="text">
<string>Top</string>
<string>Y -ve</string>
</property>
</item>
<item>
<property name="text">
<string>Bottom</string>
<string>Z -ve</string>
</property>
</item>
</widget>
</item>
<item row="3" column="1">
<item row="4" column="1">
<widget class="QLineEdit" name="axoScale">
<property name="enabled">
<bool>true</bool>
</property>
</widget>
</item>
<item row="4" column="0">
<item row="3" column="1">
<widget class="QPushButton" name="vert_flip">
<property name="text">
<string>Flip</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="label_12">
<property name="text">
<string> Trimetric</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QPushButton" name="tri_flip">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Flip</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
</layout>
@ -693,12 +788,12 @@
<item row="0" column="0">
<widget class="QLabel" name="textLabel1">
<property name="text">
<string>Primary View</string>
<string>View from:</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="primary">
<widget class="QComboBox" name="view_from">
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContentsOnFirstShow</enum>
</property>
@ -707,37 +802,32 @@
</property>
<item>
<property name="text">
<string/>
<string>X +ve</string>
</property>
</item>
<item>
<property name="text">
<string>Front</string>
<string>Y +ve</string>
</property>
</item>
<item>
<property name="text">
<string>Right</string>
<string>Z +ve</string>
</property>
</item>
<item>
<property name="text">
<string>Back</string>
<string>X -ve</string>
</property>
</item>
<item>
<property name="text">
<string>Left</string>
<string>Y -ve</string>
</property>
</item>
<item>
<property name="text">
<string>Top</string>
</property>
</item>
<item>
<property name="text">
<string>Bottom</string>
<string>Z -ve</string>
</property>
</item>
</widget>
@ -745,33 +835,33 @@
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>- Rotate</string>
<string>Axis aligned right:</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QComboBox" name="rotate">
<widget class="QComboBox" name="axis_right">
<item>
<property name="text">
<string notr="true">0</string>
<string notr="true">Y +ve</string>
</property>
</item>
<item>
<property name="text">
<string notr="true">90</string>
<string notr="true">Z +ve</string>
</property>
</item>
<item>
<property name="text">
<string notr="true">180</string>
<string notr="true">Y -ve</string>
</property>
</item>
<item>
<property name="text">
<string notr="true">270</string>
<string notr="true">Z -ve</string>
</property>
</item>
</widget>

View File

@ -18,6 +18,8 @@
inkscape:version="0.48.1 r9760"
sodipodi:docname="A3_Landscape.svg"
inkscape:output_extension="org.inkscape.output.svg.inkscape">
<!-- Working space 10 10 410 287 -->
<!-- Title block 220 227 410 287 -->
<metadata
id="metadata849">
<rdf:RDF>

Before

Width:  |  Height:  |  Size: 126 KiB

After

Width:  |  Height:  |  Size: 126 KiB

View File

@ -17,6 +17,8 @@
inkscape:version="0.47 r22583"
sodipodi:docname="A4_Landscape.svg"
inkscape:output_extension="org.inkscape.output.svg.inkscape">
<!-- Working space 10 10 287 200 -->
<!-- Title block 147 153 287 200 -->
<metadata
id="metadata849">
<rdf:RDF>

Before

Width:  |  Height:  |  Size: 82 KiB

After

Width:  |  Height:  |  Size: 82 KiB

View File

@ -1,7 +1,7 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
@ -21,26 +21,42 @@
#* *
#***************************************************************************
class PlotWorkbench ( Workbench ):
""" @brief Workbench of Plot module. Here toolbars & icons are append. """
from plotUtils import Paths
import PlotGui
Icon = 'Icon.svg'
MenuText = "Plot"
ToolTip = "The Plot module is used to edit/save output plots performed by other tools"
class PlotWorkbench(Workbench):
"""Workbench of Plot module."""
from plotUtils import Paths
import PlotGui
Icon = 'Icon.svg'
MenuText = "Plot"
ToolTip = ("The Plot module is used to edit/save output plots performed "
"by other tools")
def Initialize(self):
from PySide import QtCore, QtGui
cmdlst = ["Plot_SaveFig",
"Plot_Axes",
"Plot_Series",
"Plot_Grid",
"Plot_Legend",
"Plot_Labels",
"Plot_Positions"]
self.appendToolbar(str(QtCore.QT_TRANSLATE_NOOP(
"Plot",
"Plot edition tools")), cmdlst)
self.appendMenu(str(QtCore.QT_TRANSLATE_NOOP(
"Plot",
"Plot")), cmdlst)
try:
import matplotlib
except ImportError:
from PySide import QtCore, QtGui
msg = QtGui.QApplication.translate(
"plot_console",
"matplotlib not found, Plot module will be disabled",
None,
QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintMessage(msg + '\n')
def Initialize(self):
from PyQt4 import QtCore, QtGui
cmdlst = ["Plot_SaveFig", "Plot_Axes", "Plot_Series", "Plot_Grid", "Plot_Legend", "Plot_Labels", "Plot_Positions"]
self.appendToolbar(str(QtCore.QT_TRANSLATE_NOOP("Plot", "Plot edition tools")),cmdlst)
self.appendMenu(str(QtCore.QT_TRANSLATE_NOOP("Plot", "Plot")),cmdlst)
try:
import matplotlib
except ImportError:
from PyQt4 import QtCore, QtGui
msg = QtGui.QApplication.translate("plot_console", "matplotlib not found, Plot module will be disabled",
None,QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintMessage(msg + '\n')
Gui.addWorkbench(PlotWorkbench())

View File

@ -1,7 +1,7 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
@ -21,301 +21,409 @@
#* *
#***************************************************************************
# FreeCAD
import FreeCAD
# PyQt4
from PyQt4 import QtCore, QtGui
import PySide
from PySide import QtCore, QtGui
# Matplot lib
try:
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure
except ImportError:
msg = QtGui.QApplication.translate("plot_console", "matplotlib not found, so Plot module can not be loaded",
None,QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintMessage(msg + '\n')
raise ImportError("matplotlib not installed")
msg = QtGui.QApplication.translate(
"plot_console",
"matplotlib not found, so Plot module can not be loaded",
None,
QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintMessage(msg + '\n')
raise ImportError("matplotlib not installed")
def getMainWindow():
""" getMainWindow(): Gets FreeCAD main window. """
toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow":
return i
return None
""" Return the FreeCAD main window. """
toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow":
return i
return None
def getMdiArea():
""" getMdiArea(): Gets FreeCAD MdiArea. """
mw = getMainWindow()
if not mw:
return None
return mw.findChild(QtGui.QMdiArea)
""" Return FreeCAD MdiArea. """
mw = getMainWindow()
if not mw:
return None
childs = mw.children()
for c in childs:
if isinstance(c, PySide.QtGui.QMdiArea):
return c
return None
def getPlot():
""" getPlot(): Gets selected Plot document if exist. """
# Get active tab
mdi = getMdiArea()
if not mdi:
return None
sub = mdi.activeSubWindow()
if not sub:
return None
# Explore childrens looking for Plot class
for i in sub.children():
if i.metaObject().className() == "Plot":
return i
return None
""" Return the selected Plot document if exist. """
# Get active tab
mdi = getMdiArea()
if not mdi:
return None
sub = mdi.activeSubWindow()
if not sub:
return None
# Explore childrens looking for Plot class
for i in sub.children():
if i.metaObject().className() == "Plot":
return i
return None
def figure(winTitle="plot"):
""" figure(winTitle="plot"): Create a new plot subwindow.\n winTitle = Tab title. """
mdi = getMdiArea()
if not mdi:
return None
win = Plot(winTitle)
sub=mdi.addSubWindow(win)
sub.show()
return win
"""Create a new plot subwindow/tab.
Keyword arguments:
winTitle -- Plot tab title.
"""
mdi = getMdiArea()
if not mdi:
return None
win = Plot(winTitle)
sub = mdi.addSubWindow(win)
sub.show()
return win
def plot(x, y, name=None):
"""Plots a new serie (as line plot)
Keyword arguments:
x -- X values
y -- Y values
name -- Data serie name (for legend).
"""
# Get active plot, or create another one if don't exist
plt = getPlot()
if not plt:
plt = figure()
# Call to plot
return plt.plot(x, y, name)
def plot(x,y,name=None):
""" plot(x,y,name=None): Plots a new serie (as line plot)\n x = X values\n y = Y values\n name = Serie name (for legend). """
# Get active plot, or create another one if don't exist
plt = getPlot()
if not plt:
plt = figure()
# Call to plot
return plt.plot(x,y,name)
def series():
""" lines(): Get all lines from selected plot. """
plt = getPlot()
if not plt:
return []
return plt.series
"""Return all the lines from a selected plot."""
plt = getPlot()
if not plt:
return []
return plt.series
def removeSerie(index):
""" removeSerie(index): Removes a serie from plot.\n index = Index of serie to remove. """
# Get active series
plt = getPlot()
if not plt:
return
plots = plt.series
if not plots:
return
# Remove line from plot
axes = plots[index].axes
axes.lines.pop(plots[index].lid)
# Remove serie from list
del plt.series[index]
# Update GUI
plt.update()
"""Remove a data serie from the active plot.
Keyword arguments:
index -- Index of the serie to remove.
"""
# Get active series
plt = getPlot()
if not plt:
return
plots = plt.series
if not plots:
return
# Remove line from plot
axes = plots[index].axes
axes.lines.pop(plots[index].lid)
# Remove serie from list
del plt.series[index]
# Update GUI
plt.update()
def legend(status=True, pos=None, fontsize=None):
""" legend(status=True): Show/Hide legend.\n status = True if legend must be shown, False otherwise.\n pos = Legend position.\n fontsize = Font size """
plt = getPlot()
if not plt:
return
plt.legend = status
if fontsize:
plt.legSiz = fontsize
# Hide all legends
for axes in plt.axesList:
axes.legend_ = None
# Legend must be activated on last axes
axes = plt.axesList[-1]
if status:
# Setup legend handles and names
lines = series()
handles = []
names = []
for l in lines:
if l.name != None:
handles.append(l.line)
names.append(l.name)
# Show the legend (at selected position or at best)
if pos:
l = axes.legend(handles, names, bbox_to_anchor=pos)
plt.legPos = pos
else:
l = axes.legend(handles, names, loc='best')
# Update canvas in order to compute legend data
plt.canvas.draw()
# Get resultant position
fax = axes.get_frame().get_extents()
fl = l.get_frame()
plt.legPos = ((fl._x+fl._width-fax.x0) / fax.width, (fl._y+fl._height-fax.y0) / fax.height)
# Set fontsize
for t in l.get_texts():
t.set_fontsize(plt.legSiz)
plt.update()
"""Show/Hide the legend from the active plot.
Keyword arguments:
status -- True if legend must be shown, False otherwise.
pos -- Legend position.
fontsize -- Font size
"""
plt = getPlot()
if not plt:
return
plt.legend = status
if fontsize:
plt.legSiz = fontsize
# Hide all legends
for axes in plt.axesList:
axes.legend_ = None
# Legend must be activated on last axes
axes = plt.axesList[-1]
if status:
# Setup legend handles and names
lines = series()
handles = []
names = []
for l in lines:
if l.name is not None:
handles.append(l.line)
names.append(l.name)
# Show the legend (at selected position or at best)
if pos:
l = axes.legend(handles, names, bbox_to_anchor=pos)
plt.legPos = pos
else:
l = axes.legend(handles, names, loc='best')
# Update canvas in order to compute legend data
plt.canvas.draw()
# Get resultant position
fax = axes.get_frame().get_extents()
fl = l.get_frame()
plt.legPos = (
(fl._x + fl._width - fax.x0) / fax.width,
(fl._y + fl._height - fax.y0) / fax.height)
# Set fontsize
for t in l.get_texts():
t.set_fontsize(plt.legSiz)
plt.update()
def grid(status=True):
""" grid(status=True): Show/Hide grid.\n status = True if grid must be shown, False otherwise. """
plt = getPlot()
if not plt:
return
plt.grid = status
axes = plt.axes
axes.grid(status)
plt.update()
"""Show/Hide the grid from the active plot.
Keyword arguments:
status -- True if grid must be shown, False otherwise.
"""
plt = getPlot()
if not plt:
return
plt.grid = status
axes = plt.axes
axes.grid(status)
plt.update()
def title(string):
""" title(string): Setup plot title.\n string = Title to set. """
plt = getPlot()
if not plt:
return
axes = plt.axes
axes.set_title(string)
plt.update()
"""Setup the plot title.
Keyword arguments:
string -- Plot title.
"""
plt = getPlot()
if not plt:
return
axes = plt.axes
axes.set_title(string)
plt.update()
def xlabel(string):
""" xlabel(string): Setup x label.\n string = Title to set. """
plt = getPlot()
if not plt:
return
axes = plt.axes
axes.set_xlabel(string)
plt.update()
"""Setup the x label.
Keyword arguments:
string -- Title to set.
"""
plt = getPlot()
if not plt:
return
axes = plt.axes
axes.set_xlabel(string)
plt.update()
def ylabel(string):
""" ylabel(string): Setup y label.\n string = Title to set. """
plt = getPlot()
if not plt:
return
axes = plt.axes
axes.set_ylabel(string)
plt.update()
"""Setup the y label.
Keyword arguments:
string -- Title to set.
"""
plt = getPlot()
if not plt:
return
axes = plt.axes
axes.set_ylabel(string)
plt.update()
def axesList():
""" axesList(): Gets plot axes list. """
plt = getPlot()
if not plt:
return []
return plt.axesList
"""Return the plot axes sets list. """
plt = getPlot()
if not plt:
return []
return plt.axesList
def axes():
""" axes(): Gets active plot axes. """
plt = getPlot()
if not plt:
return None
return plt.axes
"""Return the active plot axes."""
plt = getPlot()
if not plt:
return None
return plt.axes
def addNewAxes(rect=None, frameon=True, patchcolor='none'):
""" addNewAxes(pos=None, frameon=True): Add new axes to plot, setting it as active one.\n rect = Axes area, None to copy last axes data.\n frameon = True to show frame, False otherwise.\n patchcolor = Patch color, 'none' for transparent plot. """
plt = getPlot()
if not plt:
return None
fig = plt.fig
if rect == None:
rect = plt.axes.get_position()
ax = fig.add_axes(rect, frameon=frameon)
ax.xaxis.set_ticks_position('bottom')
ax.spines['top'].set_color('none')
ax.yaxis.set_ticks_position('left')
ax.spines['right'].set_color('none')
ax.patch.set_facecolor(patchcolor)
plt.axesList.append(ax)
plt.setActiveAxes(-1)
plt.update()
return ax
"""Add new axes to plot, setting it as the active one.
Keyword arguments:
rect -- Axes area, None to copy from the last axes data.
frameon -- True to show frame, False otherwise.
patchcolor -- Patch color, 'none' for transparent plot.
"""
plt = getPlot()
if not plt:
return None
fig = plt.fig
if rect is None:
rect = plt.axes.get_position()
ax = fig.add_axes(rect, frameon=frameon)
ax.xaxis.set_ticks_position('bottom')
ax.spines['top'].set_color('none')
ax.yaxis.set_ticks_position('left')
ax.spines['right'].set_color('none')
ax.patch.set_facecolor(patchcolor)
plt.axesList.append(ax)
plt.setActiveAxes(-1)
plt.update()
return ax
def save(path, figsize=None, dpi=None):
""" save(path): Save plot.\n path = Destination file path.\n figsize = w,h figure size tuple in inches.\n dpi = Dots per inch."""
plt = getPlot()
if not plt:
return
# Backup figure options
fig = plt.fig
sizeBack = fig.get_size_inches()
dpiBack = fig.get_dpi()
# Save figure with new options
if figsize:
fig.set_size_inches(figsize[0], figsize[1])
if dpi:
fig.set_dpi(dpi)
plt.canvas.print_figure(path)
# Restore figure options
fig.set_size_inches(sizeBack[0], sizeBack[1])
fig.set_dpi(dpiBack)
plt.update()
"""Save plot.
Keyword arguments:
path -- Destination file path.
figsize -- w,h figure size tuple in inches.
dpi -- Dots per inch.
"""
plt = getPlot()
if not plt:
return
# Backup figure options
fig = plt.fig
sizeBack = fig.get_size_inches()
dpiBack = fig.get_dpi()
# Save figure with new options
if figsize:
fig.set_size_inches(figsize[0], figsize[1])
if dpi:
fig.set_dpi(dpi)
plt.canvas.print_figure(path)
# Restore figure options
fig.set_size_inches(sizeBack[0], sizeBack[1])
fig.set_dpi(dpiBack)
plt.update()
class Line():
def __init__(self, axes, x, y, name):
""" __init__(axes, x, y, name): Construct new plot serie.\n axes = Active axes\n x = X values\n y = Y values\n name = Serie name (for legend). """
self.axes = axes
self.x = x
self.y = y
self.name = name
self.lid = len(axes.lines)
self.line, = axes.plot(x,y)
def setp(self, prop, value):
""" setp(prop, value): Change line property value.\n prop = Property name.\n value = New property value. """
plt.setp(self.line, prop, value)
def getp(self, prop):
""" getp(prop): Get property value.\n prop = Property name."""
return plt.getp(self.line, prop)
def __init__(self, axes, x, y, name):
"""Construct a new plot serie.
Keyword arguments:
axes -- Active axes
x -- X values
y -- Y values
name -- Data serie name (for legend).
"""
self.axes = axes
self.x = x
self.y = y
self.name = name
self.lid = len(axes.lines)
self.line, = axes.plot(x, y)
def setp(self, prop, value):
"""Change a line property value.
Keyword arguments:
prop -- Property name.
value -- New property value.
"""
plt.setp(self.line, prop, value)
def getp(self, prop):
"""Get line property value.
Keyword arguments:
prop -- Property name.
"""
return plt.getp(self.line, prop)
class Plot(QtGui.QWidget):
def __init__(self, winTitle="plot", parent = None, flags = QtCore.Qt.WindowFlags(0)):
""" __init__(winTitle="plot", parent = None, flags = Qt.WindowFlags(0)): Construct a new plot widget.\n winTitle = Tab title.\n parent = Widget parent.\n flags = QWidget flags"""
QtGui.QWidget.__init__(self, parent, flags)
self.setWindowTitle(winTitle)
# Create matplotlib canvas
self.fig = Figure()
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
# Get axes
self.axes = self.fig.add_subplot(111)
self.axesList = [self.axes]
self.axes.xaxis.set_ticks_position('bottom')
self.axes.spines['top'].set_color('none')
self.axes.yaxis.set_ticks_position('left')
self.axes.spines['right'].set_color('none')
# Setup layout
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.canvas)
self.setLayout(vbox)
# Active series
self.series = []
# Indicators
self.skip = False
self.legend = False
self.legPos = (1.0,1.0)
self.legSiz = 14
self.grid = False
def plot(self, x, y, name=None):
""" plot(self, x, y, name=None): Plot a new line and return it.\n x = X values\n y = Y values\n name = Serie name (for legend). """
l = Line(self.axes, x, y, name)
self.series.append(l)
# Update window
self.update()
return l
def __init__(self,
winTitle="plot",
parent=None,
flags=QtCore.Qt.WindowFlags(0)):
"""Construct a new plot widget.
def update(self):
""" update(): Updates plot. """
if not self.skip:
self.skip = True
if self.legend:
legend(self.legend, self.legPos, self.legSiz)
self.canvas.draw()
self.skip = False
Keyword arguments:
winTitle -- Tab title.
parent -- Widget parent.
flags -- QWidget flags
"""
QtGui.QWidget.__init__(self, parent, flags)
self.setWindowTitle(winTitle)
# Create matplotlib canvas
self.fig = Figure()
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
# Get axes
self.axes = self.fig.add_subplot(111)
self.axesList = [self.axes]
self.axes.xaxis.set_ticks_position('bottom')
self.axes.spines['top'].set_color('none')
self.axes.yaxis.set_ticks_position('left')
self.axes.spines['right'].set_color('none')
# Setup layout
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.canvas)
self.setLayout(vbox)
# Active series
self.series = []
# Indicators
self.skip = False
self.legend = False
self.legPos = (1.0, 1.0)
self.legSiz = 14
self.grid = False
def isGrid(self):
""" isGrid(): Return True if Grid is active, False otherwise. """
return bool(self.grid)
def plot(self, x, y, name=None):
"""Plot a new line and return it.
def isLegend(self):
""" isLegend(): Return True if Legend is active, False otherwise. """
return bool(self.legend)
Keyword arguments:
x -- X values
y -- Y values
name -- Serie name (for legend). """
l = Line(self.axes, x, y, name)
self.series.append(l)
# Update window
self.update()
return l
def setActiveAxes(self, index):
""" setActiveAxes(index): Change current active axes.\n index = Index of the new active axes. """
self.axes = self.axesList[index]
self.fig.sca(self.axes)
def update(self):
"""Update the plot, redrawing the canvas."""
if not self.skip:
self.skip = True
if self.legend:
legend(self.legend, self.legPos, self.legSiz)
self.canvas.draw()
self.skip = False
def isGrid(self):
"""Return True if Grid is active, False otherwise."""
return bool(self.grid)
def isLegend(self):
"""Return True if Legend is active, False otherwise."""
return bool(self.legend)
def setActiveAxes(self, index):
"""Change the current active axes.
Keyword arguments:
index -- Index of the new active axes set.
"""
self.axes = self.axesList[index]
self.fig.sca(self.axes)

View File

@ -1,7 +1,7 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
@ -21,126 +21,163 @@
#* *
#***************************************************************************
from PyQt4 import QtCore, QtGui
import FreeCAD, FreeCADGui, os
import PySide
from PySide import QtCore, QtGui
import FreeCAD
import FreeCADGui
import os
# Load resources
import Plot_rc
FreeCADGui.addLanguagePath(":/Plot/translations")
FreeCADGui.addIconPath(":/Plot/icons")
"""
# Setup tranlations
from plotUtils import Paths
path = Paths.translationsPath()
FreeCADGui.addLanguagePath(path)
import os
import FreeCAD
translator = QtCore.QTranslator()
dirList=os.listdir(path)
for fname in dirList:
valid = translator.load(os.path.join(path, fname))
if valid:
QtGui.QApplication.installTranslator(translator)
"""
class Save:
def Activated(self):
import plotSave
plotSave.load()
class Save:
def Activated(self):
import plotSave
plotSave.load()
def GetResources(self):
# from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Save.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_SaveFig", "Save plot")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_SaveFig", "Save plot as image file")
return {'Pixmap' : 'Save', 'MenuText': MenuText, 'ToolTip': ToolTip}
def GetResources(self):
# from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Save.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP(
"Plot_SaveFig",
"Save plot")
ToolTip = QtCore.QT_TRANSLATE_NOOP(
"Plot_SaveFig",
"Save the plot as an image file")
return {'Pixmap': 'Save',
'MenuText': MenuText,
'ToolTip': ToolTip}
class Axes:
def Activated(self):
import plotAxes
plotAxes.load()
def GetResources(self):
# from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Axes.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Axes", "Configure axes")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Axes", "Configure axes parameters")
return {'Pixmap' : 'Axes', 'MenuText': MenuText, 'ToolTip': ToolTip}
class Axes:
def Activated(self):
import plotAxes
plotAxes.load()
class Series:
def Activated(self):
import plotSeries
plotSeries.load()
def GetResources(self):
MenuText = QtCore.QT_TRANSLATE_NOOP(
"Plot_Axes",
"Configure axes")
ToolTip = QtCore.QT_TRANSLATE_NOOP(
"Plot_Axes",
"Configure the axes parameters")
return {'Pixmap': 'Axes',
'MenuText': MenuText,
'ToolTip': ToolTip}
def GetResources(self):
# from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Series.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Series", "Configure series")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Series", "Configure series drawing style and label")
return {'Pixmap' : 'Series', 'MenuText': MenuText, 'ToolTip': ToolTip}
class Grid:
def Activated(self):
import Plot
plt = Plot.getPlot()
if not plt:
msg = QtGui.QApplication.translate("plot_console", "Grid must be activated on top of a plot document",
None,QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintError(msg+"\n")
return
flag = plt.isGrid()
Plot.grid(not flag)
class Series:
def Activated(self):
import plotSeries
plotSeries.load()
def GetResources(self):
# from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Grid.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Grid", "Show/Hide grid")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Grid", "Show/Hide grid on selected plot")
return {'Pixmap' : 'Grid', 'MenuText': MenuText, 'ToolTip': ToolTip}
def GetResources(self):
# from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Series.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP(
"Plot_Series",
"Configure series")
ToolTip = QtCore.QT_TRANSLATE_NOOP(
"Plot_Series",
"Configure series drawing style and label")
return {'Pixmap': 'Series',
'MenuText': MenuText,
'ToolTip': ToolTip}
class Legend:
def Activated(self):
import Plot
plt = Plot.getPlot()
if not plt:
msg = QtGui.QApplication.translate("plot_console", "Legend must be activated on top of a plot document",
None,QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintError(msg+"\n")
return
flag = plt.isLegend()
Plot.legend(not flag)
def GetResources(self):
# from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Legend.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Legend", "Show/Hide legend")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Legend", "Show/Hide legend on selected plot")
return {'Pixmap' : 'Legend', 'MenuText': MenuText, 'ToolTip': ToolTip}
class Grid:
def Activated(self):
import Plot
plt = Plot.getPlot()
if not plt:
msg = QtGui.QApplication.translate(
"plot_console",
"The grid must be activated on top of a plot document",
None,
QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintError(msg + "\n")
return
flag = plt.isGrid()
Plot.grid(not flag)
class Labels:
def Activated(self):
import plotLabels
plotLabels.load()
def GetResources(self):
# from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Grid.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP(
"Plot_Grid",
"Show/Hide grid")
ToolTip = QtCore.QT_TRANSLATE_NOOP(
"Plot_Grid",
"Show/Hide grid on selected plot")
return {'Pixmap': 'Grid',
'MenuText': MenuText,
'ToolTip': ToolTip}
def GetResources(self):
# from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Labels.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Labels", "Set labels")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Labels", "Set title and axes labels")
return {'Pixmap' : 'Labels', 'MenuText': MenuText, 'ToolTip': ToolTip}
class Positions:
def Activated(self):
import plotPositions
plotPositions.load()
class Legend:
def Activated(self):
import Plot
plt = Plot.getPlot()
if not plt:
msg = QtGui.QApplication.translate(
"plot_console",
"The legend must be activated on top of a plot document",
None,
QtGui.QApplication.UnicodeUTF8)
FreeCAD.Console.PrintError(msg + "\n")
return
flag = plt.isLegend()
Plot.legend(not flag)
def GetResources(self):
MenuText = QtCore.QT_TRANSLATE_NOOP(
"Plot_Legend",
"Show/Hide legend")
ToolTip = QtCore.QT_TRANSLATE_NOOP(
"Plot_Legend",
"Show/Hide legend on selected plot")
return {'Pixmap': 'Legend',
'MenuText': MenuText,
'ToolTip': ToolTip}
class Labels:
def Activated(self):
import plotLabels
plotLabels.load()
def GetResources(self):
MenuText = QtCore.QT_TRANSLATE_NOOP(
"Plot_Labels",
"Set labels")
ToolTip = QtCore.QT_TRANSLATE_NOOP(
"Plot_Labels",
"Set title and axes labels")
return {'Pixmap': 'Labels',
'MenuText': MenuText,
'ToolTip': ToolTip}
class Positions:
def Activated(self):
import plotPositions
plotPositions.load()
def GetResources(self):
MenuText = QtCore.QT_TRANSLATE_NOOP(
"Plot_Positions",
"Set positions and sizes")
ToolTip = QtCore.QT_TRANSLATE_NOOP(
"Plot_Positions",
"Set labels and legend positions and sizes")
return {'Pixmap': 'Positions',
'MenuText': MenuText,
'ToolTip': ToolTip}
def GetResources(self):
# from plotUtils import Paths
# IconPath = Paths.iconsPath() + "/Positions.svg"
MenuText = QtCore.QT_TRANSLATE_NOOP("Plot_Positions", "Set positions and sizes")
ToolTip = QtCore.QT_TRANSLATE_NOOP("Plot_Positions", "Set labels and legend positions and sizes")
return {'Pixmap' : 'Positions', 'MenuText': MenuText, 'ToolTip': ToolTip}
FreeCADGui.addCommand('Plot_SaveFig', Save())
FreeCADGui.addCommand('Plot_Axes', Axes())
@ -149,4 +186,3 @@ FreeCADGui.addCommand('Plot_Grid', Grid())
FreeCADGui.addCommand('Plot_Legend', Legend())
FreeCADGui.addCommand('Plot_Labels', Labels())
FreeCADGui.addCommand('Plot_Positions', Positions())

View File

@ -7,7 +7,7 @@
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
from PySide import QtCore
qt_resource_data = "\
\x00\x00\x00\x10\

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
@ -21,16 +21,9 @@
#* *
#***************************************************************************
# FreeCAD modules
import FreeCAD
import FreeCADGui
# Qt libraries
from PyQt4 import QtGui,QtCore
# Main object
import TaskPanel
def load():
""" Loads the tool """
TaskPanel.createTask()
"""Load the tool"""
TaskPanel.createTask()

View File

@ -1,225 +1,322 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#* USA *
#* *
#***************************************************************************
# FreeCAD modules
import FreeCAD as App
import FreeCADGui as Gui
# Qt library
from PyQt4 import QtGui,QtCore
# Module
from PySide import QtGui, QtCore
import Plot
from plotUtils import Paths
class TaskPanel:
def __init__(self):
self.ui = Paths.modulePath() + "/plotLabels/TaskPanel.ui"
self.skip = False
def __init__(self):
self.ui = Paths.modulePath() + "/plotLabels/TaskPanel.ui"
self.skip = False
def accept(self):
return True
def accept(self):
return True
def reject(self):
return True
def reject(self):
return True
def clicked(self, index):
pass
def clicked(self, index):
pass
def open(self):
pass
def open(self):
pass
def needsFullSpace(self):
return True
def needsFullSpace(self):
return True
def isAllowedAlterSelection(self):
return False
def isAllowedAlterSelection(self):
return False
def isAllowedAlterView(self):
return True
def isAllowedAlterView(self):
return True
def isAllowedAlterDocument(self):
return False
def isAllowedAlterDocument(self):
return False
def helpRequested(self):
pass
def helpRequested(self):
pass
def setupUi(self):
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.axId = form.findChild(QtGui.QSpinBox, "axesIndex")
form.title = form.findChild(QtGui.QLineEdit, "title")
form.titleSize = form.findChild(QtGui.QSpinBox, "titleSize")
form.xLabel = form.findChild(QtGui.QLineEdit, "titleX")
form.xSize = form.findChild(QtGui.QSpinBox, "xSize")
form.yLabel = form.findChild(QtGui.QLineEdit, "titleY")
form.ySize = form.findChild(QtGui.QSpinBox, "ySize")
self.form = form
self.retranslateUi()
# Look for active axes if can
axId = 0
plt = Plot.getPlot()
if plt:
while plt.axes != plt.axesList[axId]:
axId = axId + 1
form.axId.setValue(axId)
self.updateUI()
QtCore.QObject.connect(form.axId, QtCore.SIGNAL('valueChanged(int)'),self.onAxesId)
QtCore.QObject.connect(form.title, QtCore.SIGNAL("editingFinished()"),self.onLabels)
QtCore.QObject.connect(form.xLabel, QtCore.SIGNAL("editingFinished()"),self.onLabels)
QtCore.QObject.connect(form.yLabel, QtCore.SIGNAL("editingFinished()"),self.onLabels)
QtCore.QObject.connect(form.titleSize,QtCore.SIGNAL("valueChanged(int)"),self.onFontSizes)
QtCore.QObject.connect(form.xSize, QtCore.SIGNAL("valueChanged(int)"),self.onFontSizes)
QtCore.QObject.connect(form.ySize, QtCore.SIGNAL("valueChanged(int)"),self.onFontSizes)
QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea)
return False
def setupUi(self):
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
form.title = self.widget(QtGui.QLineEdit, "title")
form.titleSize = self.widget(QtGui.QSpinBox, "titleSize")
form.xLabel = self.widget(QtGui.QLineEdit, "titleX")
form.xSize = self.widget(QtGui.QSpinBox, "xSize")
form.yLabel = self.widget(QtGui.QLineEdit, "titleY")
form.ySize = self.widget(QtGui.QSpinBox, "ySize")
self.form = form
self.retranslateUi()
# Look for active axes if can
axId = 0
plt = Plot.getPlot()
if plt:
while plt.axes != plt.axesList[axId]:
axId = axId + 1
form.axId.setValue(axId)
self.updateUI()
QtCore.QObject.connect(form.axId,
QtCore.SIGNAL('valueChanged(int)'),
self.onAxesId)
QtCore.QObject.connect(form.title,
QtCore.SIGNAL("editingFinished()"),
self.onLabels)
QtCore.QObject.connect(form.xLabel,
QtCore.SIGNAL("editingFinished()"),
self.onLabels)
QtCore.QObject.connect(form.yLabel,
QtCore.SIGNAL("editingFinished()"),
self.onLabels)
QtCore.QObject.connect(form.titleSize,
QtCore.SIGNAL("valueChanged(int)"),
self.onFontSizes)
QtCore.QObject.connect(form.xSize,
QtCore.SIGNAL("valueChanged(int)"),
self.onFontSizes)
QtCore.QObject.connect(form.ySize,
QtCore.SIGNAL("valueChanged(int)"),
self.onFontSizes)
QtCore.QObject.connect(
Plot.getMdiArea(),
QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),
self.onMdiArea)
return False
def getMainWindow(self):
"returns the main window"
# using QtGui.qApp.activeWindow() isn't very reliable because if another
# widget than the mainwindow is active (e.g. a dialog) the wrong widget is
# returned
toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow":
return i
raise Exception("No main window found")
def getMainWindow(self):
toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow":
return i
raise Exception("No main window found")
def retranslateUi(self):
""" Set user interface locale strings.
"""
self.form.setWindowTitle(QtGui.QApplication.translate("plot_labels", "Set labels",
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "axesLabel").setText(QtGui.QApplication.translate("plot_labels", "Active axes",
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "titleLabel").setText(QtGui.QApplication.translate("plot_labels", "Title",
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "xLabel").setText(QtGui.QApplication.translate("plot_labels", "X label",
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "yLabel").setText(QtGui.QApplication.translate("plot_labels", "Y label",
None,QtGui.QApplication.UnicodeUTF8))
self.form.axId.setToolTip(QtGui.QApplication.translate("plot_labels", "Index of the active axes",
None,QtGui.QApplication.UnicodeUTF8))
self.form.title.setToolTip(QtGui.QApplication.translate("plot_labels", "Title (associated to active axes)",
None,QtGui.QApplication.UnicodeUTF8))
self.form.titleSize.setToolTip(QtGui.QApplication.translate("plot_labels", "Title font size",
None,QtGui.QApplication.UnicodeUTF8))
self.form.xLabel.setToolTip(QtGui.QApplication.translate("plot_labels", "X axis title",
None,QtGui.QApplication.UnicodeUTF8))
self.form.xSize.setToolTip(QtGui.QApplication.translate("plot_labels", "X axis title font size",
None,QtGui.QApplication.UnicodeUTF8))
self.form.yLabel.setToolTip(QtGui.QApplication.translate("plot_labels", "Y axis title",
None,QtGui.QApplication.UnicodeUTF8))
self.form.ySize.setToolTip(QtGui.QApplication.translate("plot_labels", "Y axis title font size",
None,QtGui.QApplication.UnicodeUTF8))
def widget(self, class_id, name):
"""Return the selected widget.
def onAxesId(self, value):
""" Executed when axes index is modified. """
if not self.skip:
self.skip = True
# UI control in some special plot cases
plt = Plot.getPlot()
if not plt:
self.updateUI()
self.skip = False
return
# UI control in most cases
self.form.axId.setMaximum(len(plt.axesList))
if self.form.axId.value() >= len(plt.axesList):
self.form.axId.setValue(len(plt.axesList)-1)
# Send new control to Plot instance
plt.setActiveAxes(self.form.axId.value())
self.updateUI()
self.skip = False
Keyword arguments:
class_id -- Class identifier
name -- Name of the widget
"""
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
return form.findChild(class_id, name)
def onLabels(self):
""" Executed when labels have been modified. """
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
# Set labels
Plot.title(unicode(self.form.title.text()))
Plot.xlabel(unicode(self.form.xLabel.text()))
Plot.ylabel(unicode(self.form.yLabel.text()))
plt.update()
def retranslateUi(self):
""" Set the user interface locale strings.
"""
self.form.setWindowTitle(QtGui.QApplication.translate(
"plot_labels",
"Set labels",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "axesLabel").setText(
QtGui.QApplication.translate("plot_labels",
"Active axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "titleLabel").setText(
QtGui.QApplication.translate("plot_labels",
"Title",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "xLabel").setText(
QtGui.QApplication.translate("plot_labels",
"X label",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "yLabel").setText(
QtGui.QApplication.translate("plot_labels",
"Y label",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "axesIndex").setToolTip(QtGui.QApplication.translate(
"plot_labels",
"Index of the active axes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLineEdit, "title").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"Title (associated to active axes)",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "titleSize").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"Title font size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLineEdit, "titleX").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"X axis title",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "xSize").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"X axis title font size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLineEdit, "titleY").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"Y axis title",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "ySize").setToolTip(
QtGui.QApplication.translate(
"plot_labels",
"Y axis title font size",
None,
QtGui.QApplication.UnicodeUTF8))
def onFontSizes(self, value):
""" Executed when font sizes have been modified. """
# Get apply environment
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
# Set font sizes
ax = plt.axes
ax.title.set_fontsize(self.form.titleSize.value())
ax.xaxis.label.set_fontsize(self.form.xSize.value())
ax.yaxis.label.set_fontsize(self.form.ySize.value())
plt.update()
def onAxesId(self, value):
""" Executed when axes index is modified. """
if not self.skip:
self.skip = True
# No active plot case
plt = Plot.getPlot()
if not plt:
self.updateUI()
self.skip = False
return
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
def onMdiArea(self, subWin):
""" Executed when window is selected on mdi area.
@param subWin Selected window.
"""
plt = Plot.getPlot()
if plt != subWin:
self.updateUI()
form.axId.setMaximum(len(plt.axesList))
if form.axId.value() >= len(plt.axesList):
form.axId.setValue(len(plt.axesList) - 1)
# Send new control to Plot instance
plt.setActiveAxes(form.axId.value())
self.updateUI()
self.skip = False
def onLabels(self):
""" Executed when labels have been modified. """
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.title = self.widget(QtGui.QLineEdit, "title")
form.xLabel = self.widget(QtGui.QLineEdit, "titleX")
form.yLabel = self.widget(QtGui.QLineEdit, "titleY")
Plot.title(unicode(form.title.text()))
Plot.xlabel(unicode(form.xLabel.text()))
Plot.ylabel(unicode(form.yLabel.text()))
plt.update()
def onFontSizes(self, value):
""" Executed when font sizes have been modified. """
# Get apply environment
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.titleSize = self.widget(QtGui.QSpinBox, "titleSize")
form.xSize = self.widget(QtGui.QSpinBox, "xSize")
form.ySize = self.widget(QtGui.QSpinBox, "ySize")
ax = plt.axes
ax.title.set_fontsize(form.titleSize.value())
ax.xaxis.label.set_fontsize(form.xSize.value())
ax.yaxis.label.set_fontsize(form.ySize.value())
plt.update()
def onMdiArea(self, subWin):
""" Executed when window is selected on mdi area.
Keyword arguments:
subWin -- Selected window.
"""
plt = Plot.getPlot()
if plt != subWin:
self.updateUI()
def updateUI(self):
""" Setup UI controls values if possible """
# Get again all the subwidgets (to avoid PySide Pitfalls)
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.axId = self.widget(QtGui.QSpinBox, "axesIndex")
form.title = self.widget(QtGui.QLineEdit, "title")
form.titleSize = self.widget(QtGui.QSpinBox, "titleSize")
form.xLabel = self.widget(QtGui.QLineEdit, "titleX")
form.xSize = self.widget(QtGui.QSpinBox, "xSize")
form.yLabel = self.widget(QtGui.QLineEdit, "titleY")
form.ySize = self.widget(QtGui.QSpinBox, "ySize")
plt = Plot.getPlot()
form.axId.setEnabled(bool(plt))
form.title.setEnabled(bool(plt))
form.titleSize.setEnabled(bool(plt))
form.xLabel.setEnabled(bool(plt))
form.xSize.setEnabled(bool(plt))
form.yLabel.setEnabled(bool(plt))
form.ySize.setEnabled(bool(plt))
if not plt:
return
# Ensure that active axes is correct
index = min(form.axId.value(), len(plt.axesList) - 1)
form.axId.setValue(index)
# Store data before starting changing it.
ax = plt.axes
t = ax.get_title()
x = ax.get_xlabel()
y = ax.get_ylabel()
tt = ax.title.get_fontsize()
xx = ax.xaxis.label.get_fontsize()
yy = ax.yaxis.label.get_fontsize()
# Set labels
form.title.setText(t)
form.xLabel.setText(x)
form.yLabel.setText(y)
# Set font sizes
form.titleSize.setValue(tt)
form.xSize.setValue(xx)
form.ySize.setValue(yy)
def updateUI(self):
""" Setup UI controls values if possible """
plt = Plot.getPlot()
self.form.axId.setEnabled(bool(plt))
self.form.title.setEnabled(bool(plt))
self.form.titleSize.setEnabled(bool(plt))
self.form.xLabel.setEnabled(bool(plt))
self.form.xSize.setEnabled(bool(plt))
self.form.yLabel.setEnabled(bool(plt))
self.form.ySize.setEnabled(bool(plt))
if not plt:
return
# Ensure that active axes is correct
index = min(self.form.axId.value(), len(plt.axesList)-1)
self.form.axId.setValue(index)
# Store data before starting changing it.
ax = plt.axes
t = ax.get_title()
x = ax.get_xlabel()
y = ax.get_ylabel()
tt = ax.title.get_fontsize()
xx = ax.xaxis.label.get_fontsize()
yy = ax.yaxis.label.get_fontsize()
# Set labels
self.form.title.setText(t)
self.form.xLabel.setText(x)
self.form.yLabel.setText(y)
# Set font sizes
self.form.titleSize.setValue(tt)
self.form.xSize.setValue(xx)
self.form.ySize.setValue(yy)
def createTask():
panel = TaskPanel()
Gui.Control.showDialog(panel)
if panel.setupUi():
Gui.Control.closeDialog(panel)
return None
return panel
panel = TaskPanel()
Gui.Control.showDialog(panel)
if panel.setupUi():
Gui.Control.closeDialog(panel)
return None
return panel

View File

@ -1,7 +1,7 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
@ -21,16 +21,9 @@
#* *
#***************************************************************************
# FreeCAD modules
import FreeCAD
import FreeCADGui
# Qt libraries
from PyQt4 import QtGui,QtCore
# Main object
import TaskPanel
def load():
""" Loads the tool """
TaskPanel.createTask()
"""Load the tool"""
TaskPanel.createTask()

View File

@ -1,234 +1,301 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#* USA *
#* *
#***************************************************************************
# FreeCAD modules
import FreeCAD as App
import FreeCADGui as Gui
# Qt library
from PyQt4 import QtGui,QtCore
# Module
from PySide import QtGui, QtCore
import Plot
from plotUtils import Paths
class TaskPanel:
def __init__(self):
self.ui = Paths.modulePath() + "/plotPositions/TaskPanel.ui"
self.skip = False
self.item = 0
self.names = []
self.objs = []
self.plt = None
def __init__(self):
self.ui = Paths.modulePath() + "/plotPositions/TaskPanel.ui"
self.skip = False
self.item = 0
self.names = []
self.objs = []
self.plt = None
def accept(self):
return True
def accept(self):
return True
def reject(self):
return True
def reject(self):
return True
def clicked(self, index):
pass
def clicked(self, index):
pass
def open(self):
pass
def open(self):
pass
def needsFullSpace(self):
return True
def needsFullSpace(self):
return True
def isAllowedAlterSelection(self):
return False
def isAllowedAlterSelection(self):
return False
def isAllowedAlterView(self):
return True
def isAllowedAlterView(self):
return True
def isAllowedAlterDocument(self):
return False
def isAllowedAlterDocument(self):
return False
def helpRequested(self):
pass
def helpRequested(self):
pass
def setupUi(self):
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = form.findChild(QtGui.QListWidget, "items")
form.x = form.findChild(QtGui.QDoubleSpinBox, "x")
form.y = form.findChild(QtGui.QDoubleSpinBox, "y")
form.s = form.findChild(QtGui.QDoubleSpinBox, "size")
self.form = form
self.retranslateUi()
self.updateUI()
QtCore.QObject.connect(form.items, QtCore.SIGNAL("currentRowChanged(int)"),self.onItem)
QtCore.QObject.connect(form.x, QtCore.SIGNAL("valueChanged(double)"),self.onData)
QtCore.QObject.connect(form.y, QtCore.SIGNAL("valueChanged(double)"),self.onData)
QtCore.QObject.connect(form.s, QtCore.SIGNAL("valueChanged(double)"),self.onData)
QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea)
return False
def setupUi(self):
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.x = self.widget(QtGui.QDoubleSpinBox, "x")
form.y = self.widget(QtGui.QDoubleSpinBox, "y")
form.s = self.widget(QtGui.QDoubleSpinBox, "size")
self.form = form
self.retranslateUi()
self.updateUI()
QtCore.QObject.connect(
form.items,
QtCore.SIGNAL("currentRowChanged(int)"),
self.onItem)
QtCore.QObject.connect(
form.x,
QtCore.SIGNAL("valueChanged(double)"),
self.onData)
QtCore.QObject.connect(
form.y,
QtCore.SIGNAL("valueChanged(double)"),
self.onData)
QtCore.QObject.connect(
form.s,
QtCore.SIGNAL("valueChanged(double)"),
self.onData)
QtCore.QObject.connect(
Plot.getMdiArea(),
QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),
self.onMdiArea)
return False
def getMainWindow(self):
"returns the main window"
# using QtGui.qApp.activeWindow() isn't very reliable because if another
# widget than the mainwindow is active (e.g. a dialog) the wrong widget is
# returned
toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow":
return i
raise Exception("No main window found")
def getMainWindow(self):
toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow":
return i
raise Exception("No main window found")
def retranslateUi(self):
""" Set user interface locale strings.
"""
self.form.setWindowTitle(QtGui.QApplication.translate("plot_positions", "Set positions and sizes",
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "posLabel").setText(QtGui.QApplication.translate("plot_positions", "Position",
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "sizeLabel").setText(QtGui.QApplication.translate("plot_positions", "Size",
None,QtGui.QApplication.UnicodeUTF8))
self.form.items.setToolTip(QtGui.QApplication.translate("plot_positions", "List of modificable items",
None,QtGui.QApplication.UnicodeUTF8))
self.form.x.setToolTip(QtGui.QApplication.translate("plot_positions", "X item position",
None,QtGui.QApplication.UnicodeUTF8))
self.form.y.setToolTip(QtGui.QApplication.translate("plot_positions", "Y item position",
None,QtGui.QApplication.UnicodeUTF8))
self.form.s.setToolTip(QtGui.QApplication.translate("plot_positions", "Item size",
None,QtGui.QApplication.UnicodeUTF8))
def widget(self, class_id, name):
"""Return the selected widget.
def onItem(self, row):
""" Executed when selected item is modified. """
# Get selected item
self.item = row
# Call to update
self.updateUI()
Keyword arguments:
class_id -- Class identifier
name -- Name of the widget
"""
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
return form.findChild(class_id, name)
def onData(self, value):
""" Executed when selected item data is modified. """
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
if not self.skip:
self.skip = True
name = self.names[self.item]
obj = self.objs[self.item]
x = self.form.x.value()
y = self.form.y.value()
s = self.form.s.value()
# x/y labels only have one position control
if name.find('x label') >= 0:
self.form.y.setValue(x)
elif name.find('y label') >= 0:
self.form.x.setValue(y)
# title and labels only have one size control
if name.find('title') >= 0 or name.find('label') >= 0:
obj.set_position((x,y))
obj.set_size(s)
# legend have all controls
else:
Plot.legend(plt.legend, (x,y), s)
plt.update()
self.skip = False
def retranslateUi(self):
"""Set the user interface locale strings."""
self.form.setWindowTitle(QtGui.QApplication.translate(
"plot_positions",
"Set positions and sizes",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "posLabel").setText(
QtGui.QApplication.translate(
"plot_positions",
"Position",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "sizeLabel").setText(
QtGui.QApplication.translate(
"plot_positions",
"Size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QListWidget, "items").setToolTip(
QtGui.QApplication.translate(
"plot_positions",
"List of modificable items",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "x").setToolTip(
QtGui.QApplication.translate(
"plot_positions",
"X item position",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "y").setToolTip(
QtGui.QApplication.translate(
"plot_positions",
"Y item position",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "size").setToolTip(
QtGui.QApplication.translate(
"plot_positions",
"Item size",
None,
QtGui.QApplication.UnicodeUTF8))
def onMdiArea(self, subWin):
""" Executed when window is selected on mdi area.
@param subWin Selected window.
"""
plt = Plot.getPlot()
if plt != subWin:
self.updateUI()
def onItem(self, row):
""" Executed when selected item is modified. """
self.item = row
self.updateUI()
def updateUI(self):
""" Setup UI controls values if possible """
plt = Plot.getPlot()
self.form.items.setEnabled(bool(plt))
self.form.x.setEnabled(bool(plt))
self.form.y.setEnabled(bool(plt))
self.form.s.setEnabled(bool(plt))
if not plt:
self.plt = plt
self.form.items.clear()
return
# Refill items list only if Plot instance have been changed
if self.plt != plt:
self.plt = plt
self.plt.update() # Update plot in order to put legend in correct place
self.setList()
# Get data for controls
name = self.names[self.item]
obj = self.objs[self.item]
if name.find('title') >= 0 or name.find('label') >= 0:
p = obj.get_position()
x = p[0]
y = p[1]
s = obj.get_size()
if name.find('x label') >= 0:
self.form.y.setEnabled(False)
self.form.y.setValue(x)
elif name.find('y label') >= 0:
self.form.x.setEnabled(False)
self.form.x.setValue(y)
else:
x = plt.legPos[0]
y = plt.legPos[1]
s = obj.get_texts()[-1].get_fontsize()
# Send it to controls
self.form.x.setValue(x)
self.form.y.setValue(y)
self.form.s.setValue(s)
def onData(self, value):
""" Executed when selected item data is modified. """
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.x = self.widget(QtGui.QDoubleSpinBox, "x")
form.y = self.widget(QtGui.QDoubleSpinBox, "y")
form.s = self.widget(QtGui.QDoubleSpinBox, "size")
if not self.skip:
self.skip = True
name = self.names[self.item]
obj = self.objs[self.item]
x = form.x.value()
y = form.y.value()
s = form.s.value()
# x/y labels only have one position control
if name.find('x label') >= 0:
form.y.setValue(x)
elif name.find('y label') >= 0:
form.x.setValue(y)
# title and labels only have one size control
if name.find('title') >= 0 or name.find('label') >= 0:
obj.set_position((x, y))
obj.set_size(s)
# legend have all controls
else:
Plot.legend(plt.legend, (x, y), s)
plt.update()
self.skip = False
def onMdiArea(self, subWin):
"""Executed when a new window is selected on the mdi area.
Keyword arguments:
subWin -- Selected window.
"""
plt = Plot.getPlot()
if plt != subWin:
self.updateUI()
def updateUI(self):
"""Setup the UI control values if it is possible."""
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.x = self.widget(QtGui.QDoubleSpinBox, "x")
form.y = self.widget(QtGui.QDoubleSpinBox, "y")
form.s = self.widget(QtGui.QDoubleSpinBox, "size")
plt = Plot.getPlot()
form.items.setEnabled(bool(plt))
form.x.setEnabled(bool(plt))
form.y.setEnabled(bool(plt))
form.s.setEnabled(bool(plt))
if not plt:
self.plt = plt
form.items.clear()
return
# Refill items list only if Plot instance have been changed
if self.plt != plt:
self.plt = plt
self.plt.update()
self.setList()
# Get data for controls
name = self.names[self.item]
obj = self.objs[self.item]
if name.find('title') >= 0 or name.find('label') >= 0:
p = obj.get_position()
x = p[0]
y = p[1]
s = obj.get_size()
if name.find('x label') >= 0:
form.y.setEnabled(False)
form.y.setValue(x)
elif name.find('y label') >= 0:
form.x.setEnabled(False)
form.x.setValue(y)
else:
x = plt.legPos[0]
y = plt.legPos[1]
s = obj.get_texts()[-1].get_fontsize()
# Send it to controls
form.x.setValue(x)
form.y.setValue(y)
form.s.setValue(s)
def setList(self):
""" Setup UI controls values if possible """
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.x = self.widget(QtGui.QDoubleSpinBox, "x")
form.y = self.widget(QtGui.QDoubleSpinBox, "y")
form.s = self.widget(QtGui.QDoubleSpinBox, "size")
# Clear lists
self.names = []
self.objs = []
# Fill lists with available objects
if self.plt:
# Axes data
for i in range(0, len(self.plt.axesList)):
ax = self.plt.axesList[i]
# Each axes have title, xaxis and yaxis
self.names.append('title (axes {})'.format(i))
self.objs.append(ax.title)
self.names.append('x label (axes {})'.format(i))
self.objs.append(ax.xaxis.get_label())
self.names.append('y label (axes {})'.format(i))
self.objs.append(ax.yaxis.get_label())
# Legend if exist
ax = self.plt.axesList[-1]
if ax.legend_:
self.names.append('legend')
self.objs.append(ax.legend_)
# Send list to widget
form.items.clear()
for name in self.names:
form.items.addItem(name)
# Ensure that selected item is correct
if self.item >= len(self.names):
self.item = len(self.names) - 1
form.items.setCurrentIndex(self.item)
def setList(self):
""" Setup UI controls values if possible """
# Clear lists
self.names = []
self.objs = []
# Fill lists with available objects
if self.plt:
# Axes data
for i in range(0,len(self.plt.axesList)):
ax = self.plt.axesList[i]
# Each axes have title, xaxis and yaxis
self.names.append('title (axes %d)' % (i))
self.objs.append(ax.title)
self.names.append('x label (axes %d)' % (i))
self.objs.append(ax.xaxis.get_label())
self.names.append('y label (axes %d)' % (i))
self.objs.append(ax.yaxis.get_label())
# Legend if exist
ax = self.plt.axesList[-1]
if ax.legend_:
self.names.append('legend')
self.objs.append(ax.legend_)
# Send list to widget
self.form.items.clear()
for name in self.names:
self.form.items.addItem(name)
# Ensure that selected item is correct
if self.item >= len(self.names):
self.item = len(self.names)-1
self.form.items.setCurrentIndex(self.item)
def createTask():
panel = TaskPanel()
Gui.Control.showDialog(panel)
if panel.setupUi():
Gui.Control.closeDialog(panel)
return None
return panel
panel = TaskPanel()
Gui.Control.showDialog(panel)
if panel.setupUi():
Gui.Control.closeDialog(panel)
return None
return panel

View File

@ -1,7 +1,7 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
@ -21,16 +21,9 @@
#* *
#***************************************************************************
# FreeCAD modules
import FreeCAD
import FreeCADGui
# Qt libraries
from PyQt4 import QtGui,QtCore
# Main object
import TaskPanel
def load():
""" Loads the tool """
TaskPanel.createTask()
"""Load the tool"""
TaskPanel.createTask()

View File

@ -1,163 +1,235 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#* USA *
#* *
#***************************************************************************
import os
# FreeCAD modules
import FreeCAD as App
import FreeCADGui as Gui
# Qt library
from PyQt4 import QtGui,QtCore
# Module
from PySide import QtGui, QtCore
import Plot
from plotUtils import Paths
class TaskPanel:
def __init__(self):
self.ui = Paths.modulePath() + "/plotSave/TaskPanel.ui"
def __init__(self):
self.ui = Paths.modulePath() + "/plotSave/TaskPanel.ui"
def accept(self):
plt = Plot.getPlot()
if not plt:
msg = QtGui.QApplication.translate("plot_console", "Plot document must be selected in order to save it",
None,QtGui.QApplication.UnicodeUTF8)
App.Console.PrintError(msg+"\n")
return False
path = unicode(self.form.path.text())
size = (self.form.sizeX.value(), self.form.sizeY.value())
dpi = self.form.dpi.value()
Plot.save(path, size, dpi)
return True
def accept(self):
plt = Plot.getPlot()
if not plt:
msg = QtGui.QApplication.translate(
"plot_console",
"Plot document must be selected in order to save it",
None,
QtGui.QApplication.UnicodeUTF8)
App.Console.PrintError(msg + "\n")
return False
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.path = self.widget(QtGui.QLineEdit, "path")
form.sizeX = self.widget(QtGui.QDoubleSpinBox, "sizeX")
form.sizeY = self.widget(QtGui.QDoubleSpinBox, "sizeY")
form.dpi = self.widget(QtGui.QSpinBox, "dpi")
path = unicode(form.path.text())
size = (form.sizeX.value(), form.sizeY.value())
dpi = form.dpi.value()
Plot.save(path, size, dpi)
return True
def reject(self):
return True
def reject(self):
return True
def clicked(self, index):
pass
def clicked(self, index):
pass
def open(self):
pass
def open(self):
pass
def needsFullSpace(self):
return True
def needsFullSpace(self):
return True
def isAllowedAlterSelection(self):
return False
def isAllowedAlterSelection(self):
return False
def isAllowedAlterView(self):
return True
def isAllowedAlterView(self):
return True
def isAllowedAlterDocument(self):
return False
def isAllowedAlterDocument(self):
return False
def helpRequested(self):
pass
def helpRequested(self):
pass
def setupUi(self):
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.path = form.findChild(QtGui.QLineEdit, "path")
form.pathButton = form.findChild(QtGui.QPushButton, "pathButton")
form.sizeX = form.findChild(QtGui.QDoubleSpinBox, "sizeX")
form.sizeY = form.findChild(QtGui.QDoubleSpinBox, "sizeY")
form.dpi = form.findChild(QtGui.QSpinBox, "dpi")
self.form = form
self.retranslateUi()
QtCore.QObject.connect(form.pathButton,QtCore.SIGNAL("pressed()"),self.onPathButton)
QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea)
home = os.getenv('USERPROFILE') or os.getenv('HOME')
form.path.setText(os.path.join(home,"plot.png"))
self.updateUI()
return False
def setupUi(self):
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.path = self.widget(QtGui.QLineEdit, "path")
form.pathButton = self.widget(QtGui.QPushButton, "pathButton")
form.sizeX = self.widget(QtGui.QDoubleSpinBox, "sizeX")
form.sizeY = self.widget(QtGui.QDoubleSpinBox, "sizeY")
form.dpi = self.widget(QtGui.QSpinBox, "dpi")
self.form = form
self.retranslateUi()
QtCore.QObject.connect(
form.pathButton,
QtCore.SIGNAL("pressed()"),
self.onPathButton)
QtCore.QObject.connect(
Plot.getMdiArea(),
QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),
self.onMdiArea)
home = os.getenv('USERPROFILE') or os.getenv('HOME')
form.path.setText(os.path.join(home, "plot.png"))
self.updateUI()
return False
def getMainWindow(self):
"returns the main window"
# using QtGui.qApp.activeWindow() isn't very reliable because if another
# widget than the mainwindow is active (e.g. a dialog) the wrong widget is
# returned
toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow":
return i
raise Exception("No main window found")
def getMainWindow(self):
toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow":
return i
raise Exception("No main window found")
def retranslateUi(self):
""" Set user interface locale strings.
"""
self.form.setWindowTitle(QtGui.QApplication.translate("plot_save", "Save figure",
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "sizeLabel").setText(QtGui.QApplication.translate("plot_save", "Inches",
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "dpiLabel").setText(QtGui.QApplication.translate("plot_save", "Dots per Inch",
None,QtGui.QApplication.UnicodeUTF8))
self.form.path.setToolTip(QtGui.QApplication.translate("plot_save", "Output image file path",
None,QtGui.QApplication.UnicodeUTF8))
self.form.pathButton.setToolTip(QtGui.QApplication.translate("plot_save", "Show a file selection dialog",
None,QtGui.QApplication.UnicodeUTF8))
self.form.sizeX.setToolTip(QtGui.QApplication.translate("plot_save", "X image size",
None,QtGui.QApplication.UnicodeUTF8))
self.form.sizeY.setToolTip(QtGui.QApplication.translate("plot_save", "Y image size",
None,QtGui.QApplication.UnicodeUTF8))
self.form.dpi.setToolTip(QtGui.QApplication.translate("plot_save", "Dots per point, with size will define output image resolution",
None,QtGui.QApplication.UnicodeUTF8))
def widget(self, class_id, name):
"""Return the selected widget.
def updateUI(self):
""" Setup UI controls values if possible """
plt = Plot.getPlot()
self.form.path.setEnabled(bool(plt))
self.form.pathButton.setEnabled(bool(plt))
self.form.sizeX.setEnabled(bool(plt))
self.form.sizeY.setEnabled(bool(plt))
self.form.dpi.setEnabled(bool(plt))
if not plt:
return
fig = plt.fig
size = fig.get_size_inches()
dpi = fig.get_dpi()
self.form.sizeX.setValue(size[0])
self.form.sizeY.setValue(size[1])
self.form.dpi.setValue(dpi)
Keyword arguments:
class_id -- Class identifier
name -- Name of the widget
"""
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
return form.findChild(class_id, name)
def onPathButton(self):
""" Executed when path button is pressed.
"""
path = self.form.path.text()
file_choices = "Portable Network Graphics (*.png)|*.png;;Portable Document Format (*.pdf)|*.pdf;;PostScript (*.ps)|*.ps;;Encapsulated PostScript (*.eps)|*.eps"
path = QtGui.QFileDialog.getSaveFileName(None, 'Save figure', path, file_choices)
if path:
self.form.path.setText(path)
def retranslateUi(self):
"""Set the user interface locale strings."""
self.form.setWindowTitle(QtGui.QApplication.translate(
"plot_save",
"Save figure",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "sizeLabel").setText(
QtGui.QApplication.translate(
"plot_save",
"Inches",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "dpiLabel").setText(
QtGui.QApplication.translate(
"plot_save",
"Dots per Inch",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLineEdit, "path").setToolTip(
QtGui.QApplication.translate(
"plot_save",
"Output image file path",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QPushButton, "pathButton").setToolTip(
QtGui.QApplication.translate(
"plot_save",
"Show a file selection dialog",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "sizeX").setToolTip(
QtGui.QApplication.translate(
"plot_save",
"X image size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "sizeY").setToolTip(
QtGui.QApplication.translate(
"plot_save",
"Y image size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "dpi").setToolTip(
QtGui.QApplication.translate(
"plot_save",
"Dots per point, with size will define output image"
" resolution",
None,
QtGui.QApplication.UnicodeUTF8))
def updateUI(self):
""" Setup UI controls values if possible """
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.path = self.widget(QtGui.QLineEdit, "path")
form.pathButton = self.widget(QtGui.QPushButton, "pathButton")
form.sizeX = self.widget(QtGui.QDoubleSpinBox, "sizeX")
form.sizeY = self.widget(QtGui.QDoubleSpinBox, "sizeY")
form.dpi = self.widget(QtGui.QSpinBox, "dpi")
plt = Plot.getPlot()
form.path.setEnabled(bool(plt))
form.pathButton.setEnabled(bool(plt))
form.sizeX.setEnabled(bool(plt))
form.sizeY.setEnabled(bool(plt))
form.dpi.setEnabled(bool(plt))
if not plt:
return
fig = plt.fig
size = fig.get_size_inches()
dpi = fig.get_dpi()
form.sizeX.setValue(size[0])
form.sizeY.setValue(size[1])
form.dpi.setValue(dpi)
def onPathButton(self):
"""Executed when the path selection button is pressed."""
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.path = self.widget(QtGui.QLineEdit, "path")
path = form.path.text()
file_choices = ("Portable Network Graphics (*.png)|*.png;;"
"Portable Document Format (*.pdf)|*.pdf;;"
"PostScript (*.ps)|*.ps;;"
"Encapsulated PostScript (*.eps)|*.eps")
path = QtGui.QFileDialog.getSaveFileName(None,
'Save figure',
path,
file_choices)
if path:
form.path.setText(path)
def onMdiArea(self, subWin):
"""Executed when a new window is selected on the mdi area.
Keyword arguments:
subWin -- Selected window.
"""
plt = Plot.getPlot()
if plt != subWin:
self.updateUI()
def onMdiArea(self, subWin):
""" Executed when window is selected on mdi area.
@param subWin Selected window.
"""
plt = Plot.getPlot()
if plt != subWin:
self.updateUI()
def createTask():
panel = TaskPanel()
Gui.Control.showDialog(panel)
if panel.setupUi():
Gui.Control.closeDialog(panel)
return None
return panel
panel = TaskPanel()
Gui.Control.showDialog(panel)
if panel.setupUi():
Gui.Control.closeDialog(panel)
return None
return panel

View File

@ -1,7 +1,7 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
@ -21,16 +21,9 @@
#* *
#***************************************************************************
# FreeCAD modules
import FreeCAD
import FreeCADGui
# Qt libraries
from PyQt4 import QtGui,QtCore
# Main object
import TaskPanel
def load():
""" Loads the tool """
TaskPanel.createTask()
"""Load the tool"""
TaskPanel.createTask()

View File

@ -1,332 +1,462 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
#* as published by the Free Software Foundation; either version 2 of *
#* the License, or (at your option) any later version. *
#* for detail see the LICENCE text file. *
#* *
#* This program is distributed in the hope that it will be useful, *
#* but WITHOUT ANY WARRANTY; without even the implied warranty of *
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
#* GNU Library General Public License for more details. *
#* *
#* You should have received a copy of the GNU Library General Public *
#* License along with this program; if not, write to the Free Software *
#* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
#* USA *
#* *
#* USA *
#* *
#***************************************************************************
# FreeCAD modules
import FreeCAD as App
import FreeCADGui as Gui
# Qt library
from PyQt4 import QtGui,QtCore
# Module
from PySide import QtGui, QtCore
import Plot
from plotUtils import Paths
# matplotlib
import matplotlib
from matplotlib.lines import Line2D
import matplotlib.colors as Colors
class TaskPanel:
def __init__(self):
self.ui = Paths.modulePath() + "/plotSeries/TaskPanel.ui"
self.skip = False
self.item = 0
self.plt = None
def __init__(self):
self.ui = Paths.modulePath() + "/plotSeries/TaskPanel.ui"
self.skip = False
self.item = 0
self.plt = None
def accept(self):
return True
def accept(self):
return True
def reject(self):
return True
def reject(self):
return True
def clicked(self, index):
pass
def clicked(self, index):
pass
def open(self):
pass
def open(self):
pass
def needsFullSpace(self):
return True
def needsFullSpace(self):
return True
def isAllowedAlterSelection(self):
return False
def isAllowedAlterSelection(self):
return False
def isAllowedAlterView(self):
return True
def isAllowedAlterView(self):
return True
def isAllowedAlterDocument(self):
return False
def isAllowedAlterDocument(self):
return False
def helpRequested(self):
pass
def helpRequested(self):
pass
def setupUi(self):
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = form.findChild(QtGui.QListWidget, "items")
form.label = form.findChild(QtGui.QLineEdit, "label")
form.isLabel = form.findChild(QtGui.QCheckBox, "isLabel")
form.style = form.findChild(QtGui.QComboBox, "lineStyle")
form.marker = form.findChild(QtGui.QComboBox, "markers")
form.width = form.findChild(QtGui.QDoubleSpinBox, "lineWidth")
form.size = form.findChild(QtGui.QSpinBox, "markerSize")
form.color = form.findChild(QtGui.QPushButton, "color")
form.remove = form.findChild(QtGui.QPushButton, "remove")
self.form = form
self.retranslateUi()
self.fillStyles()
self.updateUI()
QtCore.QObject.connect(form.items, QtCore.SIGNAL("currentRowChanged(int)"),self.onItem)
QtCore.QObject.connect(form.label, QtCore.SIGNAL("editingFinished()"),self.onData)
QtCore.QObject.connect(form.isLabel,QtCore.SIGNAL("stateChanged(int)"),self.onData)
QtCore.QObject.connect(form.style, QtCore.SIGNAL("currentIndexChanged(int)"),self.onData)
QtCore.QObject.connect(form.marker, QtCore.SIGNAL("currentIndexChanged(int)"),self.onData)
QtCore.QObject.connect(form.width, QtCore.SIGNAL("valueChanged(double)"),self.onData)
QtCore.QObject.connect(form.size, QtCore.SIGNAL("valueChanged(int)"),self.onData)
QtCore.QObject.connect(form.color, QtCore.SIGNAL("pressed()"),self.onColor)
QtCore.QObject.connect(form.remove, QtCore.SIGNAL("pressed()"),self.onRemove)
QtCore.QObject.connect(Plot.getMdiArea(),QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),self.onMdiArea)
return False
def setupUi(self):
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.label = self.widget(QtGui.QLineEdit, "label")
form.isLabel = self.widget(QtGui.QCheckBox, "isLabel")
form.style = self.widget(QtGui.QComboBox, "lineStyle")
form.marker = self.widget(QtGui.QComboBox, "markers")
form.width = self.widget(QtGui.QDoubleSpinBox, "lineWidth")
form.size = self.widget(QtGui.QSpinBox, "markerSize")
form.color = self.widget(QtGui.QPushButton, "color")
form.remove = self.widget(QtGui.QPushButton, "remove")
self.form = form
self.retranslateUi()
self.fillStyles()
self.updateUI()
QtCore.QObject.connect(
form.items,
QtCore.SIGNAL("currentRowChanged(int)"),
self.onItem)
QtCore.QObject.connect(
form.label,
QtCore.SIGNAL("editingFinished()"),
self.onData)
QtCore.QObject.connect(
form.isLabel,
QtCore.SIGNAL("stateChanged(int)"),
self.onData)
QtCore.QObject.connect(
form.style,
QtCore.SIGNAL("currentIndexChanged(int)"),
self.onData)
QtCore.QObject.connect(
form.marker,
QtCore.SIGNAL("currentIndexChanged(int)"),
self.onData)
QtCore.QObject.connect(
form.width,
QtCore.SIGNAL("valueChanged(double)"),
self.onData)
QtCore.QObject.connect(
form.size,
QtCore.SIGNAL("valueChanged(int)"),
self.onData)
QtCore.QObject.connect(
form.color,
QtCore.SIGNAL("pressed()"),
self.onColor)
QtCore.QObject.connect(
form.remove,
QtCore.SIGNAL("pressed()"),
self.onRemove)
QtCore.QObject.connect(
Plot.getMdiArea(),
QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"),
self.onMdiArea)
return False
def getMainWindow(self):
"returns the main window"
# using QtGui.qApp.activeWindow() isn't very reliable because if another
# widget than the mainwindow is active (e.g. a dialog) the wrong widget is
# returned
toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow":
return i
raise Exception("No main window found")
def getMainWindow(self):
toplevel = QtGui.qApp.topLevelWidgets()
for i in toplevel:
if i.metaObject().className() == "Gui::MainWindow":
return i
raise Exception("No main window found")
def retranslateUi(self):
""" Set user interface locale strings.
"""
self.form.setWindowTitle(QtGui.QApplication.translate("plot_series", "Configure series",
None,QtGui.QApplication.UnicodeUTF8))
self.form.isLabel.setText(QtGui.QApplication.translate("plot_series", "No label",
None,QtGui.QApplication.UnicodeUTF8))
self.form.remove.setText(QtGui.QApplication.translate("plot_series", "Remove serie",
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "styleLabel").setText(QtGui.QApplication.translate("plot_series", "Line style",
None,QtGui.QApplication.UnicodeUTF8))
self.form.findChild(QtGui.QLabel, "markerLabel").setText(QtGui.QApplication.translate("plot_series", "Marker",
None,QtGui.QApplication.UnicodeUTF8))
self.form.items.setToolTip(QtGui.QApplication.translate("plot_series", "List of available series",
None,QtGui.QApplication.UnicodeUTF8))
self.form.label.setToolTip(QtGui.QApplication.translate("plot_series", "Line title",
None,QtGui.QApplication.UnicodeUTF8))
self.form.isLabel.setToolTip(QtGui.QApplication.translate("plot_series", "If checked serie will not be considered for legend",
None,QtGui.QApplication.UnicodeUTF8))
self.form.style.setToolTip(QtGui.QApplication.translate("plot_series", "Line style",
None,QtGui.QApplication.UnicodeUTF8))
self.form.marker.setToolTip(QtGui.QApplication.translate("plot_series", "Marker style",
None,QtGui.QApplication.UnicodeUTF8))
self.form.width.setToolTip(QtGui.QApplication.translate("plot_series", "Line width",
None,QtGui.QApplication.UnicodeUTF8))
self.form.size.setToolTip(QtGui.QApplication.translate("plot_series", "Marker size",
None,QtGui.QApplication.UnicodeUTF8))
self.form.color.setToolTip(QtGui.QApplication.translate("plot_series", "Line and marker color",
None,QtGui.QApplication.UnicodeUTF8))
self.form.remove.setToolTip(QtGui.QApplication.translate("plot_series", "Removes this serie",
None,QtGui.QApplication.UnicodeUTF8))
def widget(self, class_id, name):
"""Return the selected widget.
def fillStyles(self):
""" Fill style combo boxes. """
# Line styles
linestyles = Line2D.lineStyles.keys()
for i in range(0,len(linestyles)):
style = linestyles[i]
string = "\'" + str(style) + "\' (" + Line2D.lineStyles[style] + ")"
self.form.style.addItem(string)
# Markers
markers = Line2D.markers.keys()
for i in range(0,len(markers)):
marker = markers[i]
string = "\'" + str(marker) + "\' (" + Line2D.markers[marker] + ")"
self.form.marker.addItem(string)
Keyword arguments:
class_id -- Class identifier
name -- Name of the widget
"""
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
return form.findChild(class_id, name)
def onItem(self, row):
""" Executed when selected item is modified. """
if not self.skip:
self.skip = True
# Get selected item
self.item = row
# Call to update
self.updateUI()
self.skip = False
def retranslateUi(self):
"""Set the user interface locale strings."""
self.form.setWindowTitle(QtGui.QApplication.translate(
"plot_series",
"Configure series",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QCheckBox, "isLabel").setText(
QtGui.QApplication.translate(
"plot_series",
"No label",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QPushButton, "remove").setText(
QtGui.QApplication.translate(
"plot_series",
"Remove serie",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "styleLabel").setText(
QtGui.QApplication.translate(
"plot_series",
"Line style",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLabel, "markerLabel").setText(
QtGui.QApplication.translate(
"plot_series",
"Marker",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QListWidget, "items").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"List of available series",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QLineEdit, "label").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Line title",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QCheckBox, "isLabel").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"If checked serie will not be considered for legend",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QComboBox, "lineStyle").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Line style",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QComboBox, "markers").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Marker style",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QDoubleSpinBox, "lineWidth").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Line width",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QSpinBox, "markerSize").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Marker size",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QPushButton, "color").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Line and marker color",
None,
QtGui.QApplication.UnicodeUTF8))
self.widget(QtGui.QPushButton, "remove").setToolTip(
QtGui.QApplication.translate(
"plot_series",
"Removes this serie",
None,
QtGui.QApplication.UnicodeUTF8))
def onData(self):
""" Executed when selected item data is modified. """
if not self.skip:
self.skip = True
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
# Ensure that selected serie exist
if self.item >= len(Plot.series()):
self.updateUI()
return
# Set label
serie = Plot.series()[self.item]
if(self.form.isLabel.isChecked()):
serie.name = None
self.form.label.setEnabled(False)
else:
serie.name = self.form.label.text()
self.form.label.setEnabled(True)
# Set line style and marker
style = self.form.style.currentIndex()
linestyles = Line2D.lineStyles.keys()
serie.line.set_linestyle(linestyles[style])
marker = self.form.marker.currentIndex()
markers = Line2D.markers.keys()
serie.line.set_marker(markers[marker])
# Set line width and marker size
serie.line.set_linewidth(self.form.width.value())
serie.line.set_markersize(self.form.size.value())
plt.update()
# Regenerate series labels
self.setList()
self.skip = False
def fillStyles(self):
"""Fill the style combo boxes with the availabel ones."""
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.style = self.widget(QtGui.QComboBox, "lineStyle")
form.marker = self.widget(QtGui.QComboBox, "markers")
# Line styles
linestyles = Line2D.lineStyles.keys()
for i in range(0, len(linestyles)):
style = linestyles[i]
string = "\'" + str(style) + "\'"
string += " (" + Line2D.lineStyles[style] + ")"
form.style.addItem(string)
# Markers
markers = Line2D.markers.keys()
for i in range(0, len(markers)):
marker = markers[i]
string = "\'" + str(marker) + "\'"
string += " (" + Line2D.markers[marker] + ")"
form.marker.addItem(string)
def onColor(self):
""" Executed when color pallete is requested. """
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
# Ensure that selected serie exist
if self.item >= len(Plot.series()):
self.updateUI()
return
# Show widget to select color
col = QtGui.QColorDialog.getColor()
# Send color to widget and serie
if col.isValid():
serie = plt.series[self.item]
self.form.color.setStyleSheet("background-color: rgb(%d, %d, %d);" % (col.red(),
col.green(), col.blue()))
serie.line.set_color((col.redF(), col.greenF(), col.blueF()))
plt.update()
def onItem(self, row):
"""Executed when the selected item is modified."""
if not self.skip:
self.skip = True
def onRemove(self):
""" Executed when data serie must be removed. """
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
# Ensure that selected serie exist
if self.item >= len(Plot.series()):
self.updateUI()
return
# Remove serie
Plot.removeSerie(self.item)
self.setList()
self.updateUI()
plt.update()
self.item = row
def onMdiArea(self, subWin):
""" Executed when window is selected on mdi area.
@param subWin Selected window.
"""
plt = Plot.getPlot()
if plt != subWin:
self.updateUI()
self.updateUI()
self.skip = False
def updateUI(self):
""" Setup UI controls values if possible """
plt = Plot.getPlot()
self.form.items.setEnabled(bool(plt))
self.form.label.setEnabled(bool(plt))
self.form.isLabel.setEnabled(bool(plt))
self.form.style.setEnabled(bool(plt))
self.form.marker.setEnabled(bool(plt))
self.form.width.setEnabled(bool(plt))
self.form.size.setEnabled(bool(plt))
self.form.color.setEnabled(bool(plt))
self.form.remove.setEnabled(bool(plt))
if not plt:
self.plt = plt
self.form.items.clear()
return
self.skip = True
# Refill list
if self.plt != plt or len(Plot.series()) != self.form.items.count():
self.plt = plt
self.setList()
# Ensure that have series
if not len(Plot.series()):
self.form.label.setEnabled(False)
self.form.isLabel.setEnabled(False)
self.form.style.setEnabled(False)
self.form.marker.setEnabled(False)
self.form.width.setEnabled(False)
self.form.size.setEnabled(False)
self.form.color.setEnabled(False)
self.form.remove.setEnabled(False)
return
# Set label
serie = Plot.series()[self.item]
if serie.name == None:
self.form.isLabel.setChecked(True)
self.form.label.setEnabled(False)
self.form.label.setText("")
else:
self.form.isLabel.setChecked(False)
self.form.label.setText(serie.name)
# Set line style and marker
self.form.style.setCurrentIndex(0)
linestyles = Line2D.lineStyles.keys()
for i in range(0,len(linestyles)):
style = linestyles[i]
if style == serie.line.get_linestyle():
self.form.style.setCurrentIndex(i)
self.form.marker.setCurrentIndex(0)
markers = Line2D.markers.keys()
for i in range(0,len(markers)):
marker = markers[i]
if marker == serie.line.get_marker():
self.form.marker.setCurrentIndex(i)
# Set line width and marker size
self.form.width.setValue(serie.line.get_linewidth())
self.form.size.setValue(serie.line.get_markersize())
# Set color
color = Colors.colorConverter.to_rgb(serie.line.get_color())
self.form.color.setStyleSheet("background-color: rgb(%d, %d, %d);" % (int(color[0]*255),
int(color[1]*255), int(color[2]*255)))
self.skip = False
def onData(self):
"""Executed when the selected item data is modified."""
if not self.skip:
self.skip = True
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.label = self.widget(QtGui.QLineEdit, "label")
form.isLabel = self.widget(QtGui.QCheckBox, "isLabel")
form.style = self.widget(QtGui.QComboBox, "lineStyle")
form.marker = self.widget(QtGui.QComboBox, "markers")
form.width = self.widget(QtGui.QDoubleSpinBox, "lineWidth")
form.size = self.widget(QtGui.QSpinBox, "markerSize")
# Ensure that selected serie exist
if self.item >= len(Plot.series()):
self.updateUI()
return
# Set label
serie = Plot.series()[self.item]
if(form.isLabel.isChecked()):
serie.name = None
form.label.setEnabled(False)
else:
serie.name = form.label.text()
form.label.setEnabled(True)
# Set line style and marker
style = form.style.currentIndex()
linestyles = Line2D.lineStyles.keys()
serie.line.set_linestyle(linestyles[style])
marker = form.marker.currentIndex()
markers = Line2D.markers.keys()
serie.line.set_marker(markers[marker])
# Set line width and marker size
serie.line.set_linewidth(form.width.value())
serie.line.set_markersize(form.size.value())
plt.update()
# Regenerate series labels
self.setList()
self.skip = False
def onColor(self):
""" Executed when color pallete is requested. """
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.color = self.widget(QtGui.QPushButton, "color")
# Ensure that selected serie exist
if self.item >= len(Plot.series()):
self.updateUI()
return
# Show widget to select color
col = QtGui.QColorDialog.getColor()
# Send color to widget and serie
if col.isValid():
serie = plt.series[self.item]
form.color.setStyleSheet(
"background-color: rgb({}, {}, {});".format(col.red(),
col.green(),
col.blue()))
serie.line.set_color((col.redF(), col.greenF(), col.blueF()))
plt.update()
def onRemove(self):
"""Executed when the data serie must be removed."""
plt = Plot.getPlot()
if not plt:
self.updateUI()
return
# Ensure that selected serie exist
if self.item >= len(Plot.series()):
self.updateUI()
return
# Remove serie
Plot.removeSerie(self.item)
self.setList()
self.updateUI()
plt.update()
def onMdiArea(self, subWin):
"""Executed when a new window is selected on the mdi area.
Keyword arguments:
subWin -- Selected window.
"""
plt = Plot.getPlot()
if plt != subWin:
self.updateUI()
def updateUI(self):
""" Setup UI controls values if possible """
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.label = self.widget(QtGui.QLineEdit, "label")
form.isLabel = self.widget(QtGui.QCheckBox, "isLabel")
form.style = self.widget(QtGui.QComboBox, "lineStyle")
form.marker = self.widget(QtGui.QComboBox, "markers")
form.width = self.widget(QtGui.QDoubleSpinBox, "lineWidth")
form.size = self.widget(QtGui.QSpinBox, "markerSize")
form.color = self.widget(QtGui.QPushButton, "color")
form.remove = self.widget(QtGui.QPushButton, "remove")
plt = Plot.getPlot()
form.items.setEnabled(bool(plt))
form.label.setEnabled(bool(plt))
form.isLabel.setEnabled(bool(plt))
form.style.setEnabled(bool(plt))
form.marker.setEnabled(bool(plt))
form.width.setEnabled(bool(plt))
form.size.setEnabled(bool(plt))
form.color.setEnabled(bool(plt))
form.remove.setEnabled(bool(plt))
if not plt:
self.plt = plt
form.items.clear()
return
self.skip = True
# Refill list
if self.plt != plt or len(Plot.series()) != form.items.count():
self.plt = plt
self.setList()
# Ensure that have series
if not len(Plot.series()):
form.label.setEnabled(False)
form.isLabel.setEnabled(False)
form.style.setEnabled(False)
form.marker.setEnabled(False)
form.width.setEnabled(False)
form.size.setEnabled(False)
form.color.setEnabled(False)
form.remove.setEnabled(False)
return
# Set label
serie = Plot.series()[self.item]
if serie.name is None:
form.isLabel.setChecked(True)
form.label.setEnabled(False)
form.label.setText("")
else:
form.isLabel.setChecked(False)
form.label.setText(serie.name)
# Set line style and marker
form.style.setCurrentIndex(0)
linestyles = Line2D.lineStyles.keys()
for i in range(0, len(linestyles)):
style = linestyles[i]
if style == serie.line.get_linestyle():
form.style.setCurrentIndex(i)
form.marker.setCurrentIndex(0)
markers = Line2D.markers.keys()
for i in range(0, len(markers)):
marker = markers[i]
if marker == serie.line.get_marker():
form.marker.setCurrentIndex(i)
# Set line width and marker size
form.width.setValue(serie.line.get_linewidth())
form.size.setValue(serie.line.get_markersize())
# Set color
color = Colors.colorConverter.to_rgb(serie.line.get_color())
form.color.setStyleSheet("background-color: rgb({}, {}, {});".format(
int(color[0] * 255),
int(color[1] * 255),
int(color[2] * 255)))
self.skip = False
def setList(self):
"""Setup the UI control values if it is possible."""
mw = self.getMainWindow()
form = mw.findChild(QtGui.QWidget, "TaskPanel")
form.items = self.widget(QtGui.QListWidget, "items")
form.items.clear()
series = Plot.series()
for i in range(0, len(series)):
serie = series[i]
string = 'serie ' + str(i) + ': '
if serie.name is None:
string = string + '\"No label\"'
else:
string = string + serie.name
form.items.addItem(string)
# Ensure that selected item is correct
if len(series) and self.item >= len(series):
self.item = len(series) - 1
form.items.setCurrentIndex(self.item)
def setList(self):
""" Setup UI controls values if possible """
self.form.items.clear()
series = Plot.series()
for i in range(0,len(series)):
serie = series[i]
string = 'serie ' + str(i) + ': '
if serie.name == None:
string = string + '\"No label\"'
else:
string = string + serie.name
self.form.items.addItem(string)
# Ensure that selected item is correct
if len(series) and self.item >= len(series):
self.item = len(series)-1
self.form.items.setCurrentIndex(self.item)
def createTask():
panel = TaskPanel()
Gui.Control.showDialog(panel)
if panel.setupUi():
Gui.Control.closeDialog(panel)
return None
return panel
panel = TaskPanel()
Gui.Control.showDialog(panel)
if panel.setupUi():
Gui.Control.closeDialog(panel)
return None
return panel

View File

@ -1,7 +1,7 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
@ -21,16 +21,9 @@
#* *
#***************************************************************************
# FreeCAD modules
import FreeCAD
import FreeCADGui
# Qt libraries
from PyQt4 import QtGui,QtCore
# Main object
import TaskPanel
def load():
""" Loads the tool """
TaskPanel.createTask()
"""Load the tool"""
TaskPanel.createTask()

View File

@ -1,7 +1,7 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
@ -21,11 +21,13 @@
#* *
#***************************************************************************
import FreeCAD, FreeCADGui, os
import FreeCAD
import FreeCADGui
import os
def modulePath():
"""returns the current Plot module path
@return Module path"""
"""returns the current Plot module path."""
path1 = FreeCAD.ConfigGet("AppHomePath") + "Mod/Plot"
path2 = FreeCAD.ConfigGet("UserAppData") + "Mod/Plot"
if os.path.exists(path2):
@ -33,29 +35,14 @@ def modulePath():
else:
return path1
def iconsPath():
"""returns the current Plot module icons path
@return Icons path"""
"""returns the current Plot module icons path."""
path = modulePath() + "/resources/icons"
return path
def translationsPath():
"""returns the current Plot module translations path
@return Icons path"""
"""returns the current Plot module translations path."""
path = modulePath() + "/resources/translations"
return path
def getPathFromFile(fileName):
""" Gets the directory path from a file name
@param fileName Name of the file
@return Directory path.
"""
if not fileName:
return ''
i = 1
try:
while 1:
i = fileName.index("/", i+1)
except ValueError:
pass
return fileName[0:i+1]

View File

@ -1,7 +1,7 @@
#***************************************************************************
#* *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* Copyright (c) 2011, 2012 *
#* Jose Luis Cercos Pita <jlcercos@gmail.com> *
#* *
#* This program is free software; you can redistribute it and/or modify *
#* it under the terms of the GNU Lesser General Public License (LGPL) *
@ -20,6 +20,3 @@
#* USA *
#* *
#***************************************************************************
# Empty file to treat the folder as a package