Make first real commit: copy of CaRMetal 4.2.8

This commit is contained in:
Glen Whitney 2018-09-04 22:51:42 -04:00
parent 002acfc88e
commit c312811084
1120 changed files with 226843 additions and 1 deletions

View file

@ -0,0 +1,68 @@
/*
Copyright 2006 Eric Hakenholz
This file is part of C.a.R. software.
C.a.R. is a free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
C.a.R. 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eric.macros;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import javax.swing.tree.TreePath;
/**
* This represents a TreePath (a node in a JTree) that can be transferred
* between a drag source and a drop target.
*/
class CTransferableTreePath implements Transferable {
// The type of DnD object being dragged...
public static final DataFlavor TREEPATH_FLAVOR = new DataFlavor(
DataFlavor.javaJVMLocalObjectMimeType, "TreePath");
private final TreePath _path;
private final DataFlavor[] _flavors = { TREEPATH_FLAVOR };
/**
* Constructs a transferrable tree path object for the specified path.
*/
public CTransferableTreePath(final TreePath path) {
_path = path;
}
// Transferable interface methods...
public DataFlavor[] getTransferDataFlavors() {
return _flavors;
}
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return java.util.Arrays.asList(_flavors).contains(flavor);
}
public synchronized Object getTransferData(final DataFlavor flavor)
throws UnsupportedFlavorException {
if (flavor.isMimeTypeEqual(TREEPATH_FLAVOR.getMimeType())) // DataFlavor.javaJVMLocalObjectMimeType))
return _path;
else
throw new UnsupportedFlavorException(flavor);
}
}

663
eric/macros/CTree.java Normal file
View file

@ -0,0 +1,663 @@
/*
Copyright 2006 Eric Hakenholz
This file is part of C.a.R. software.
C.a.R. is a free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
C.a.R. 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eric.macros;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.SystemColor;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.Autoscroll;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.dnd.InvalidDnDOperationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.Timer;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;
public class CTree extends JTree implements DragSourceListener,
DragGestureListener, Autoscroll, TreeSelectionListener, MouseListener {
// Constants...
/**
*
*/
private static final long serialVersionUID = 1L;
// Fields...
private TreePath _pathSource; // The path being dragged
private BufferedImage _imgGhost; // The 'drag image'
private final Point _ptOffset = new Point(); // Where, in the drag image,
// the mouse was clicked
private boolean dropped = false;
public MacrosList JML;
public NodePopupMenu nodepopup;
// Constructors...
public CTree(final MacrosList jml) // Use the default JTree constructor so
// that we get a sample TreeModel built
// for us
{
JML = jml;
putClientProperty("JTree.lineStyle", "none");
// this.addTreeSelectionListener(this);
// this.getModel().addTreeModelListener(this);
this.addMouseListener(this);
// Make this JTree a drag source
final DragSource dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE, this);
// Also, make this JTree a drag target
final DropTarget dropTarget = new DropTarget(this,
new CDropTargetListener());
dropTarget.setDefaultActions(DnDConstants.ACTION_COPY_OR_MOVE);
nodepopup = new NodePopupMenu(this);
}
private DefaultMutableTreeNode cloneAll(final DefaultMutableTreeNode Ndfrom) {
final DefaultMutableTreeNode Ndto = (DefaultMutableTreeNode) Ndfrom
.clone();
if (!(Ndfrom.isLeaf())) {
for (int i = 0; i < Ndfrom.getChildCount(); i++) {
final DefaultMutableTreeNode mynode = cloneAll((DefaultMutableTreeNode) Ndfrom
.getChildAt(i));
Ndto.add(mynode);
}
}
return Ndto;
}
// Interface: DragGestureListener
public void dragGestureRecognized(final DragGestureEvent e) {
final Point ptDragOrigin = e.getDragOrigin();
final TreePath path = getPathForLocation(ptDragOrigin.x, ptDragOrigin.y);
if (path == null)
return;
if (isRootPath(path))
return; // Ignore user trying to drag the root node
// Work out the offset of the drag point from the TreePath bounding
// rectangle origin
final Rectangle raPath = getPathBounds(path);
_ptOffset.setLocation(ptDragOrigin.x - raPath.x, ptDragOrigin.y
- raPath.y);
// Get the cell renderer (which is a JLabel) for the path being dragged
final JLabel lbl = (JLabel) getCellRenderer()
.getTreeCellRendererComponent(this, // tree
path.getLastPathComponent(), // value
false, // isSelected (dont want a colored background)
isExpanded(path), // isExpanded
getModel().isLeaf(path.getLastPathComponent()), // isLeaf
0, // row (not important for rendering)
false // hasFocus (dont want a focus rectangle)
);
lbl.setSize((int) raPath.getWidth(), (int) raPath.getHeight()); // <--
// The
// layout
// manager
// would
// normally
// do
// this
// Get a buffered image of the selection for dragging a ghost image
_imgGhost = new BufferedImage((int) raPath.getWidth(), (int) raPath
.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
final Graphics2D g2 = _imgGhost.createGraphics();
// Ask the cell renderer to paint itself into the BufferedImage
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.5f)); // Make
// the
// image
// ghostlike
lbl.paint(g2);
// Now paint a gradient UNDER the ghosted JLabel text (but not under the
// icon if any)
// Note: this will need tweaking if your icon is not positioned to the
// left of the text
final Icon icon = lbl.getIcon();
final int nStartOfText = (icon == null) ? 0 : icon.getIconWidth()
+ lbl.getIconTextGap();
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_OVER,
0.5f)); // Make the gradient ghostlike
g2.setPaint(new GradientPaint(nStartOfText, 0,
SystemColor.controlShadow, getWidth(), 0, new Color(255, 255,
255, 0)));
g2.fillRect(nStartOfText, 0, getWidth(), _imgGhost.getHeight());
g2.dispose();
setSelectionPath(path); // Select this path in the tree
// System.out.println("DRAGGING: "+path.getLastPathComponent());
// DefaultMutableTreeNode
// mynode=(DefaultMutableTreeNode)path.getLastPathComponent();
// Transferable transferable = (Transferable) mynode.getUserObject();
// Wrap the path being transferred into a Transferable object
final Transferable transferable = new CTransferableTreePath(path);
// Remember the path being dragged (because if it is being moved, we
// will have to delete it later)
_pathSource = path;
// We pass our drag image just in case it IS supported by the platform
try {
this.setEditable(false);
// e.startDrag(new Cursor(Cursor.HAND_CURSOR),transferable,this);
e.startDrag(null, _imgGhost, new Point(5, 5), transferable, this);
} catch (final InvalidDnDOperationException dnde) {
// JOptionPane.showMessageDialog(null, "coucou2");
}
// e.startDrag(null, _imgGhost, new Point(5,5), transferable, this);
}
// Interface: DragSourceListener
public void dragEnter(final DragSourceDragEvent e) {
}
public void dragOver(final DragSourceDragEvent e) {
}
public void dragExit(final DragSourceEvent e) {
}
public void dropActionChanged(final DragSourceDragEvent e) {
}
public void dragDropEnd(final DragSourceDropEvent e) {
if (e.getDropSuccess()) {
final int nAction = e.getDropAction();
if (nAction == DnDConstants.ACTION_MOVE) { // The dragged item
// (_pathSource) has
// been inserted at the
// target selected by
// the user.
// Now it is time to delete it from its original location.
// System.out.println("REMOVING: " +
// _pathSource.getLastPathComponent());
if (dropped) {
final DefaultTreeModel model = (DefaultTreeModel) getModel();
final MutableTreeNode node = (MutableTreeNode) _pathSource
.getLastPathComponent();
MutableTreeNode parent = (MutableTreeNode) node.getParent();
model.removeNodeFromParent(node);
while (parent.isLeaf()) {
final MutableTreeNode grandparent = (MutableTreeNode) parent
.getParent();
model.removeNodeFromParent(parent);
parent = grandparent;
}
dropped = false;
}
_pathSource = null;
}
}
}
// DropTargetListener interface object...
class CDropTargetListener implements DropTargetListener {
// Fields...
private TreePath _pathLast = null;
private final Rectangle2D _raCueLine = new Rectangle2D.Float();
private Rectangle2D _raGhost = new Rectangle2D.Float();
private final Color _colorCueLine;
private Point _ptLast = new Point();
private final Timer _timerHover;
private int _nLeftRight = 0; // Cumulative left/right mouse movement
// Constructor...
public CDropTargetListener() {
_colorCueLine = new Color(SystemColor.controlShadow.getRed(),
SystemColor.controlShadow.getGreen(),
SystemColor.controlShadow.getBlue(), 64);
// Set up a hover timer, so that a node will be automatically
// expanded or collapsed
// if the user lingers on it for more than a short time
_timerHover = new Timer(1000, new ActionListener() {
public void actionPerformed(final ActionEvent e) {
_nLeftRight = 0; // Reset left/right movement trend
if (isRootPath(_pathLast))
return; // Do nothing if we are hovering over the root
// node
if (isExpanded(_pathLast))
collapsePath(_pathLast);
else
expandPath(_pathLast);
}
});
_timerHover.setRepeats(false); // Set timer to one-shot mode
}
// DropTargetListener interface
public void dragEnter(final DropTargetDragEvent e) {
if (!isDragAcceptable(e))
e.rejectDrag();
else
e.acceptDrag(e.getDropAction());
}
public void dragExit(final DropTargetEvent e) {
if (!DragSource.isDragImageSupported()) {
repaint(_raGhost.getBounds());
}
}
/**
* This is where the ghost image is drawn
*/
public void dragOver(final DropTargetDragEvent e) {
// Even if the mouse is not moving, this method is still invoked 10
// times per second
final Point pt = e.getLocation();
if (pt.equals(_ptLast))
return;
// Try to determine whether the user is flicking the cursor right or
// left
final int nDeltaLeftRight = pt.x - _ptLast.x;
if ((_nLeftRight > 0 && nDeltaLeftRight < 0)
|| (_nLeftRight < 0 && nDeltaLeftRight > 0))
_nLeftRight = 0;
_nLeftRight += nDeltaLeftRight;
_ptLast = pt;
final Graphics2D g2 = (Graphics2D) getGraphics();
// If a drag image is not supported by the platform, then draw my
// own drag image
if (!DragSource.isDragImageSupported()) {
paintImmediately(_raGhost.getBounds()); // Rub out the last
// ghost image and cue
// line
// And remember where we are about to draw the new ghost image
_raGhost.setRect(pt.x - _ptOffset.x, pt.y - _ptOffset.y,
_imgGhost.getWidth(), _imgGhost.getHeight());
g2.drawImage(_imgGhost, AffineTransform.getTranslateInstance(
_raGhost.getX(), _raGhost.getY()), null);
} else
// Just rub out the last cue line
paintImmediately(_raCueLine.getBounds());
final TreePath path = getClosestPathForLocation(pt.x, pt.y);
if (!(path == _pathLast)) {
_nLeftRight = 0; // We've moved up or down, so reset left/right
// movement trend
_pathLast = path;
_timerHover.restart();
}
// In any case draw (over the ghost image if necessary) a cue line
// indicating where a drop will occur
final Rectangle raPath = getPathBounds(path);
_raCueLine.setRect(0, raPath.y + (int) raPath.getHeight(),
getWidth(), 2);
g2.setColor(_colorCueLine);
g2.fill(_raCueLine);
// Now superimpose the left/right movement indicator if necessary
if (_nLeftRight > 20) {
} else if (_nLeftRight < -20) {
} else {
}
// And include the cue line in the area to be rubbed out next time
_raGhost = _raGhost.createUnion(_raCueLine);
/*
* // Do this if you want to prohibit dropping onto the drag source
* if (path.equals(_pathSource)) e.rejectDrag(); else
* e.acceptDrag(e.getDropAction());
*/
}
public void dropActionChanged(final DropTargetDragEvent e) {
if (!isDragAcceptable(e))
e.rejectDrag();
else
e.acceptDrag(e.getDropAction());
}
public void drop(final DropTargetDropEvent e) {
_timerHover.stop(); // Prevent hover timer from doing an unwanted
// expandPath or collapsePath
if (!isDropAcceptable(e)) {
e.rejectDrop();
return;
}
e.acceptDrop(e.getDropAction());
final Transferable transferable = e.getTransferable();
final DataFlavor[] flavors = transferable.getTransferDataFlavors();
for (final DataFlavor flavor : flavors) {
if (flavor
.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType)) {
try {
final Point pt = e.getLocation();
final TreePath pathTarget = getClosestPathForLocation(
pt.x, pt.y);
final TreePath pathSource = (TreePath) transferable
.getTransferData(flavor);
// System.out.println("DROPPING: "+pathSource.getLastPathComponent());
// TreeModel model = getModel();
final DefaultTreeModel model = (DefaultTreeModel) getModel();
final TreePath pathNewChild = null;
final DefaultMutableTreeNode nodeorg = (DefaultMutableTreeNode) pathSource
.getLastPathComponent();
DefaultMutableTreeNode nodeto = (DefaultMutableTreeNode) pathTarget
.getLastPathComponent();
// avoid a folder to be drag inside its own hierarchy
dropped = true;
if (!(nodeorg.isLeaf())) {
DefaultMutableTreeNode parent = nodeto;
while (parent != null) {
if (parent.equals(nodeorg)) {
dropped = false;
JML.repaint();
return;
}
parent = (DefaultMutableTreeNode) parent
.getParent();
}
}
if (dropped) {
DefaultMutableTreeNode nodeparentto = (nodeto
.isLeaf()) ? (DefaultMutableTreeNode) pathTarget
.getParentPath().getLastPathComponent()
: nodeto;
final TreePath tp = new TreePath(nodeparentto
.getPath());
if (!(isExpanded(tp))) {
nodeto = nodeparentto;
nodeparentto = (DefaultMutableTreeNode) nodeto
.getParent();
}
int h = 0;
for (h = 0; h < nodeparentto.getChildCount(); h++) {
if (nodeparentto.getChildAt(h).equals(nodeto))
break;
}
if (h == nodeparentto.getChildCount())
h = -1;
model.insertNodeInto(cloneAll(nodeorg),
nodeparentto, h + 1);
}
// model.insertNodeInto()
// .
// .. Add your code here to ask your TreeModel to copy
// the node and act on the mouse gestures...
// .
// For example:
// If pathTarget is an expanded BRANCH,
// then insert source UNDER it (before the first child
// if any)
// If pathTarget is a collapsed BRANCH (or a LEAF),
// then insert source AFTER it
// Note: a leaf node is always marked as collapsed
// You ask the model to do the copying...
// ...and you supply the copyNode method in the model as
// well of course.
// if (_nShift == 0)
// pathNewChild = model.copyNode(pathSource, pathTarget,
// isExpanded(pathTarget));
// else if (_nShift > 0) // The mouse is being flicked
// to the right (so move the node right)
// pathNewChild = model.copyNodeRight(pathSource,
// pathTarget);
// else // The mouse is being flicked to the left (so
// move the node left)
// pathNewChild = model.copyNodeLeft(pathSource);
if (pathNewChild != null)
setSelectionPath(pathNewChild); // Mark this as the
// selected path in
// the tree
break; // No need to check remaining flavors
} catch (final UnsupportedFlavorException ufe) {
// System.out.println(ufe);
e.dropComplete(false);
return;
} catch (final IOException ioe) {
// System.out.println(ioe);
e.dropComplete(false);
return;
}
}
}
e.dropComplete(true);
}
// Helpers...
public boolean isDragAcceptable(final DropTargetDragEvent e) {
// Only accept COPY or MOVE gestures (ie LINK is not supported)
if ((e.getDropAction() & DnDConstants.ACTION_COPY_OR_MOVE) == 0)
return false;
// Only accept this particular flavor
if (!e.isDataFlavorSupported(CTransferableTreePath.TREEPATH_FLAVOR))
return false;
/*
* // Do this if you want to prohibit dropping onto the drag
* source... Point pt = e.getLocation(); TreePath path =
* getClosestPathForLocation(pt.x, pt.y); if
* (path.equals(_pathSource)) return false;
*/
/*
* // Do this if you want to select the best flavor on offer...
* DataFlavor[] flavors = e.getCurrentDataFlavors(); for (int i = 0;
* i < flavors.length; i++ ) { DataFlavor flavor = flavors[i]; if
* (flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType))
* return true; }
*/
return true;
}
public boolean isDropAcceptable(final DropTargetDropEvent e) {
// Only accept COPY or MOVE gestures (ie LINK is not supported)
if ((e.getDropAction() & DnDConstants.ACTION_COPY_OR_MOVE) == 0)
return false;
// Only accept this particular flavor
if (!e.isDataFlavorSupported(CTransferableTreePath.TREEPATH_FLAVOR))
return false;
/*
* // Do this if you want to prohibit dropping onto the drag
* source... Point pt = e.getLocation(); TreePath path =
* getClosestPathForLocation(pt.x, pt.y); if
* (path.equals(_pathSource)) return false;
*/
/*
* // Do this if you want to select the best flavor on offer...
* DataFlavor[] flavors = e.getCurrentDataFlavors(); for (int i = 0;
* i < flavors.length; i++ ) { DataFlavor flavor = flavors[i]; if
* (flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType))
* return true; }
*/
return true;
}
}
// Autoscroll Interface...
// The following code was borrowed from the book:
// Java Swing
// By Robert Eckstein, Marc Loy & Dave Wood
// Paperback - 1221 pages 1 Ed edition (September 1998)
// O'Reilly & Associates; ISBN: 156592455X
//
// The relevant chapter of which can be found at:
// http://www.oreilly.com/catalog/jswing/chapter/dnd.beta.pdf
private static final int AUTOSCROLL_MARGIN = 12;
// Ok, weíve been told to scroll because the mouse cursor is in our
// scroll zone.
public void autoscroll(final Point pt) {
// Figure out which row weíre on.
int nRow = getRowForLocation(pt.x, pt.y);
// If we are not on a row then ignore this autoscroll request
if (nRow < 0)
return;
final Rectangle raOuter = getBounds();
// Now decide if the row is at the top of the screen or at the
// bottom. We do this to make the previous row (or the next
// row) visible as appropriate. If weíre at the absolute top or
// bottom, just return the first or last row respectively.
nRow = (pt.y + raOuter.y <= AUTOSCROLL_MARGIN) // Is row at top of
// screen?
? (nRow <= 0 ? 0 : nRow - 1) // Yes, scroll up one row
: (nRow < getRowCount() - 1 ? nRow + 1 : nRow); // No, scroll
// down one row
scrollRowToVisible(nRow);
}
// Calculate the insets for the *JTREE*, not the viewport
// the tree is in. This makes it a bit messy.
public Insets getAutoscrollInsets() {
final Rectangle raOuter = getBounds();
final Rectangle raInner = getParent().getBounds();
return new Insets(raInner.y - raOuter.y + AUTOSCROLL_MARGIN, raInner.x
- raOuter.x + AUTOSCROLL_MARGIN, raOuter.height
- raInner.height - raInner.y + raOuter.y + AUTOSCROLL_MARGIN,
raOuter.width - raInner.width - raInner.x + raOuter.x
+ AUTOSCROLL_MARGIN);
}
/*
* // Use this method if you want to see the boundaries of the // autoscroll
* active region. Toss it out, otherwise. public void
* paintComponent(Graphics g) { super.paintComponent(g); Rectangle raOuter =
* getBounds(); Rectangle raInner = getParent().getBounds();
* g.setColor(Color.red); g.drawRect(-raOuter.x + 12, -raOuter.y + 12,
* raInner.width - 24, raInner.height - 24); }
*/
private boolean isRootPath(final TreePath path) {
return isRootVisible() && getRowForPath(path) == 0;
}
// Ready to go : execute macro on click
public void valueChanged(final TreeSelectionEvent e) {
// JDefaultMutableTreeNode node =
// (JDefaultMutableTreeNode)this.getLastSelectedPathComponent();
// if (node.isLeaf()) {
// node.runZmacro();
// };
}
// MouseListener interface
public void mouseClicked(final MouseEvent e) {
nodepopup.handleMouseClick(e);
}
public void mousePressed(final MouseEvent e) {
nodepopup.actualiseproperties();
nodepopup.handlePopup(e);
}
public void mouseReleased(final MouseEvent e) {
nodepopup.handlePopup(e);
}
public void mouseEntered(final MouseEvent e) {
// ShowToolTip(e);
}
public void mouseExited(final MouseEvent e) {
// HideToolTip();
}
}

View file

@ -0,0 +1,154 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eric.macros;
import eric.GUI.palette.PaletteManager;
import eric.GUI.pipe_tools;
import eric.GUI.themes;
import eric.JZirkelCanvas;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JMenuItem;
import eric.JEricPanel;
import rene.zirkel.ZirkelCanvas;
/**
*
* @author erichake
*/
public class CreateMacroDialog extends JDialog implements MouseListener, MouseMotionListener, TopDialog {
private static CreateMacroDialog MD;
private static int content_height=50, content_width=205;
private static int locmargin=50;
private CreateMacroPanel CMP;
private MacrosList MI;
private MouseEvent pressed;
private Point location;
public CreateMacroDialog(MacrosList mi) {
MD=this;
MI=mi;
CreateMacroDialogContentPane c=new CreateMacroDialogContentPane();
setContentPane(c);
c.addMouseListener(this);
c.addMouseMotionListener(this);
DialogTitleBar title=new DialogTitleBar(this, content_width);
c.add(title);
CMP=new CreateMacroPanel(this, MI, content_width, content_height);
c.add(CMP);
setUndecorated(true);
setSize(content_width, content_height+DialogTitleBar.getTitleHeight());
if (!pipe_tools.isApplet()) {
setAlwaysOnTop(true);
} else {
addWindowListener(new WindowAdapter() {
public void windowDeactivated(WindowEvent e) {
toFront();
}
});
}
setResizable(false);
ZirkelCanvas zc=JZirkelCanvas.getCurrentZC();
if (zc!=null) {
this.setLocation(zc.getLocationOnScreen().x+locmargin, zc.getLocationOnScreen().y+locmargin);
}
pipe_tools.setMacroPanelKeyInputs();
setVisible(true);
}
public static int getContentWidth() {
return content_width;
}
public static void quit() {
if (MD!=null) {
MD.exit();
}
}
public void exit() {
setVisible(false);
pipe_tools.removeMacroPanelKeyInputs();
dispose();
MD=null;
}
public class CreateMacroDialogContentPane extends JEricPanel {
@Override
public void paintComponent(final java.awt.Graphics g) {
super.paintComponent(g);
final java.awt.Dimension d=this.getSize();
g.drawImage(themes.getImage("MCreateDlogBackground.gif"), 0, 0, d.width,
d.height, this);
}
public CreateMacroDialogContentPane() {
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
}
}
public class myJMenuItem extends JMenuItem implements ActionListener {
public void action() {
}
public myJMenuItem(String s) {
super(s);
addActionListener(this);
setFont(themes.TabMenusFont);
}
public void actionPerformed(ActionEvent e) {
action();
}
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent me) {
pressed=me;
}
public void mouseDragged(MouseEvent me) {
location=getLocation(location);
int x=location.x-pressed.getX()+me.getX();
int y=location.y-pressed.getY()+me.getY();
setLocation(x, y);
Toolkit.getDefaultToolkit().sync();
}
public void mouseMoved(MouseEvent e) {
}
}

View file

@ -0,0 +1,326 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eric.macros;
import eric.GUI.palette.PaletteManager;
import eric.GUI.pipe_tools;
import eric.GUI.themes;
import eric.JZirkelCanvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import eric.JEricPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import rene.gui.Global;
import rene.zirkel.ZirkelCanvas;
import rene.zirkel.ZirkelFrame;
import rene.zirkel.construction.Construction;
import rene.zirkel.construction.ConstructionException;
import rene.zirkel.macro.Macro;
import rene.zirkel.objects.ConstructionObject;
/**
*
* @author erichake
*/
/**************************************************************************************
*** N'oublions pas que JMacrosList est un JPanel qui contient d'autres
* JPanels La class Jcreatemacro contient les éléments UI qui gèrent
* l'enregistrement des macros
***************************************************************************************/
public class CreateMacroPanel extends JEricPanel {
private JButton nextbtn;
private static int stepnum;
private boolean visible=false;
private static stepcomments steps;
private static MacrosList ML;
private static CreateMacroDialog CMD;
private static CreateMacroPanel CMP;
public CreateMacroPanel(CreateMacroDialog md, MacrosList ml, int w, int h) {
CMP=this;
ML=ml;
CMD=md;
final ZirkelFrame zf=JZirkelCanvas.getCurrentZF();
if (zf!=null) {
this.setLayout(new javax.swing.BoxLayout(this,
javax.swing.BoxLayout.X_AXIS));
this.setAlignmentX(0F);
setOpaque(false);
setFocusable(false);
stepnum=1;
zf.settool(ZirkelFrame.NParameters);
this.visible=true;
PaletteManager.fixsize(this, w, h);
steps=new stepcomments();
nextbtn=new JButton(themes.getIcon("Mnext.png"));
nextbtn.setOpaque(false);
nextbtn.setContentAreaFilled(false);
nextbtn.setEnabled(true);
nextbtn.setBorder(BorderFactory.createEmptyBorder());
nextbtn.setAlignmentY(0.5F);
nextbtn.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent e) {
nextStep();
}
});
this.add(margin(10));
this.add(steps);
this.add(margin(10));
this.add(nextbtn);
ML.validate();
ML.repaint();
}
}
static public void nextStep() {
ZirkelFrame zf=JZirkelCanvas.getCurrentZF();
if (zf==null) {
return;
}
// if parameters are selected :
if (zf.ZC.getConstruction().Parameters.size()>0) {
switch (stepnum) {
case 1:
if ((zf.ZC.isDP())&&(!zf.ZC.isEuclidian())) {
Construction c=zf.ZC.getConstruction();
ConstructionObject hz=c.getHZ();
hz.setMainParameter(true);
c.insertParameter(hz, 0);
hz.setSpecialParameter(true);
}
steps.mycomment.setText("2/3 - "+Global.Loc("macros.finals"));
steps.myparams.setText("");
zf.settool(ZirkelFrame.NTargets);
break;
case 2:
steps.mycomment.setText("3/3 - "+Global.Loc("macros.name"));
steps.myparams.setEditable(true);
steps.myparams.setFocusable(true);
steps.myparams.setHorizontalAlignment(SwingConstants.CENTER);
steps.myparams.setText(Global.Loc("macros.untitledmacro"));
steps.myparams.selectAll();
steps.myparams.requestFocus();
pipe_tools.removeMacroPanelKeyInputs();
break;
case 3:
valid();
break;
}
stepnum++;
} else {
zf.settool(ZirkelFrame.NParameters);
setParametersComments();
}
}
static public void setParametersComments() {
if (CMD!=null) {
ZirkelCanvas zc=JZirkelCanvas.getCurrentZC();
if (zc!=null) {
String p="";
Vector v=zc.getConstruction().getParameters();
for (int i=0; i<v.size(); i++) {
ConstructionObject o=(ConstructionObject) v.get(i);
p+=","+o.getName();
}
if (p.startsWith(",")) {
p=p.substring(1);
}
if (p.equals("")) {
CMP.steps.myparams.setHorizontalAlignment(SwingConstants.CENTER);
p=Global.Loc("macros.pleaseselect");
} else {
CMP.steps.myparams.setHorizontalAlignment(SwingConstants.RIGHT);
}
CMP.steps.myparams.setText(p);
}
}
}
static public void setTargetsComments() {
if (CMD!=null) {
ZirkelCanvas zc=JZirkelCanvas.getCurrentZC();
if (zc!=null) {
String p="";
Vector v=zc.getConstruction().getTargets();
for (int i=0; i<v.size(); i++) {
ConstructionObject o=(ConstructionObject) v.get(i);
p+=","+o.getName();
}
if (p.startsWith(",")) {
p=p.substring(1);
}
CMP.steps.myparams.setHorizontalAlignment(SwingConstants.RIGHT);
CMP.steps.myparams.setText(p);
}
}
}
static JEricPanel margin(int w) {
JEricPanel mypan=new JEricPanel();
PaletteManager.fixsize(mypan, w, 1);
mypan.setLayout(new javax.swing.BoxLayout(mypan, javax.swing.BoxLayout.X_AXIS));
mypan.setAlignmentX(0F);
mypan.setAlignmentY(0F);
mypan.setOpaque(false);
mypan.setFocusable(false);
return mypan;
}
public JLabel getComment() {
return steps.getComment();
}
public static void valid() {
final TreePath tp=createmacro();
pipe_tools.actualiseLeftPanels();
PaletteManager.selectGeomIcon();
CreateMacroDialog.quit();
}
public static TreePath createmacro() {
JDefaultMutableTreeNode root;
ZirkelCanvas zc=JZirkelCanvas.getCurrentZC();
if (zc==null) {
return null;
}
final Vector V=zc.getConstruction().Parameters;
final String s[]=new String[V.size()];
for (int i=0; i<V.size(); i++) {
final ConstructionObject o=(ConstructionObject) V.elementAt(i);
if (o.isSpecialParameter()) {
s[i]="="+o.getName();
}else{
s[i]=o.getName();
}
}
String txt=CMP.steps.myparams.getText();
if (txt.equals("")) {
txt=Global.Loc("macros.untitledmacro");
}
// final Macro m=new Macro(zc, Global.Loc("macros.untitledmacro"), "", s);
final Macro m=new Macro(zc, txt, "", s);
try {
zc.defineMacro(zc.getConstruction(), m, (zc.getConstruction().countTargets()>0), true, s, false);
} catch (final ConstructionException e) {
}
m.hideDuplicates(false);
zc.storeMacro(m, false);
final JDefaultMutableTreeNode node=new JDefaultMutableTreeNode(JZirkelCanvas.getCurrentZF(), m);
final TreePath[] paths=ML.getMacrosTree().getSelectionPaths();
if (((paths)!=null)&&(paths.length>0)) {
root=(JDefaultMutableTreeNode) paths[0].getLastPathComponent();
if (root.isLeaf()) {
// if the first selected node is a leaf :
final DefaultMutableTreeNode father=(DefaultMutableTreeNode) root.getParent();
final int i=father.getIndex(root)+1;
((DefaultTreeModel) ML.getMacrosTree().getModel()).insertNodeInto(
node, father, i);
} else {
// if the first selected node is a folder :
((DefaultTreeModel) ML.getMacrosTree().getModel()).insertNodeInto(
node, root, root.getChildCount());
}
} else {
// There is no selected node :
((DefaultTreeModel) ML.getMacrosTree().getModel()).insertNodeInto(node,
ML.getTopNode(), ML.getTopNode().getChildCount());
}
final TreePath tp=new TreePath(node.getPath());
node.ActualisePath();
return tp;
}
private class stepcomments extends JEricPanel {
/**
*
*/
private JLabel mycomment=new JLabel();
private JTextField myparams=new JTextField();
@Override
public void paintComponent(final java.awt.Graphics g) {
super.paintComponent(g);
final java.awt.Dimension d=this.getSize();
g.drawImage(themes.getImage("Mcomments.png"), 0, 0, d.width,
d.height, this);
}
public JLabel getComment() {
return mycomment;
}
private stepcomments() {
this.setLayout(new javax.swing.BoxLayout(this,
javax.swing.BoxLayout.Y_AXIS));
this.setAlignmentY(0.5F);
final ImageIcon backIcon=themes.getIcon("Mcomments.png");
PaletteManager.fixsize(this, backIcon.getIconWidth(), backIcon.getIconHeight());
this.setOpaque(false);
mycomment.setText("1/3 - "+Global.Loc("macros.initials"));
mycomment.setFont(new Font("Verdana", 0, 10));
PaletteManager.fixsize(mycomment, backIcon.getIconWidth(), backIcon.getIconHeight()/2);
mycomment.setHorizontalAlignment(SwingConstants.CENTER);
mycomment.setVerticalAlignment(SwingConstants.CENTER);
mycomment.setAlignmentX(0.5f);
mycomment.setAlignmentY(0.5f);
this.add(mycomment);
myparams.setText(Global.Loc("macros.pleaseselect"));
myparams.setFont(new Font("Verdana", 0, 10));
myparams.setForeground(Color.blue);
myparams.setOpaque(false);
myparams.setBorder(null);
myparams.setFocusable(false);
PaletteManager.fixsize(myparams, backIcon.getIconWidth()-10, backIcon.getIconHeight()/2);
myparams.setHorizontalAlignment(SwingConstants.CENTER);
// myparams.setVerticalAlignment(SwingConstants.CENTER);
myparams.setAlignmentX(0.5f);
myparams.setAlignmentY(0.5f);
myparams.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(final KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER) {
valid();
}
}
});
this.add(myparams);
}
}
}

View file

@ -0,0 +1,128 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eric.macros;
import eric.GUI.palette.PaletteManager;
import eric.GUI.themes;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JLabel;
import eric.JEricPanel;
import javax.swing.SwingConstants;
import rene.gui.Global;
/**
*
* @author erichake
*/
/**
* Title bar class
*/
public class DialogTitleBar extends JEricPanel {
private static int title_height=17;
private static int close_width=themes.getIcon("tab_close.png").getIconWidth();
private static int close_height=themes.getIcon("tab_close.png").getIconHeight();
private static int close_marginRight=3;
private int title_width;
private Image img=themes.getImage("PaletteTitleBarN.png");
private JLabel title=new JLabel();
private TopDialog DLOG;
public void paintComponent(Graphics g) {
if (DLOG instanceof CreateMacroDialog) {
return;
}
Dimension d=getSize();
g.drawImage(img, 0, 0, d.width, d.height, this);
}
public DialogTitleBar(TopDialog d, int w) {
DLOG=d;
title_width=w;
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentX(0.0f);
setOpaque(false);
setFocusable(false);
PaletteManager.fixsize(this, title_width, title_height);
title.setText(Global.Loc("macro.creationdlog.title"));
title.setFont(new java.awt.Font(Global.GlobalFont, 0, 11));
title.setForeground(new Color(100, 100, 100));
title.setHorizontalAlignment(SwingConstants.LEFT);
PaletteManager.fixsize(title, title_width-close_width-close_marginRight, title_height);
title.setHorizontalAlignment(JLabel.CENTER);
title.setVerticalAlignment(JLabel.CENTER);
title.setAlignmentY(0.5f);
add(title);
add(new CreateMacroDialogCloseBtn());
addMouseListener((MouseListener) DLOG);
addMouseMotionListener((MouseMotionListener) DLOG);
}
public static int getTitleHeight() {
return title_height;
}
class CreateMacroDialogCloseBtn extends JEricPanel implements MouseListener {
private boolean over=false;
@Override
public void paintComponent(Graphics g) {
Dimension d=getSize();
if (over) {
g.drawImage(themes.getImage("tab_close_over.png"), 0, 0, d.width, d.height,
this);
} else {
g.drawImage(themes.getImage("tab_close.png"), 0, 0, d.width, d.height,
this);
}
}
public CreateMacroDialogCloseBtn() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
setAlignmentY(0.5f);
setOpaque(false);
PaletteManager.fixsize(this, close_width, close_height);
addMouseListener(this);
}
@Override
public void mousePressed(MouseEvent e) {
over=false;
if (DLOG!=null) {
DLOG.exit();
}
}
public void mouseEntered(MouseEvent e) {
over=true;
repaint();
}
public void mouseExited(MouseEvent e) {
over=false;
repaint();
}
public void mouseClicked(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
}
}

View file

@ -0,0 +1,138 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eric.macros;
/**
*
* @author erichake
*/
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragGestureRecognizer;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import javax.swing.DefaultListModel;
import javax.swing.DropMode;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.TransferHandler;
public class DragDropList extends JList {
DefaultListModel model;
public DragDropList() {
super(new DefaultListModel());
model = (DefaultListModel) getModel();
setDragEnabled(true);
setDropMode(DropMode.INSERT);
setTransferHandler(new MyListDropHandler(this));
new MyDragListener(this);
model.addElement("a");
model.addElement("b");
model.addElement("c");
model.addElement(new JLabel("coucou"));
}
public static void main(String[] a){
JFrame f = new JFrame();
f.add(new JScrollPane(new DragDropList()));
f.setSize(300,300);
f.setVisible(true);
}
}
class MyDragListener implements DragSourceListener, DragGestureListener {
DragDropList list;
DragSource ds = new DragSource();
public MyDragListener(DragDropList list) {
this.list = list;
DragGestureRecognizer dgr = ds.createDefaultDragGestureRecognizer(list,
DnDConstants.ACTION_MOVE, this);
}
public void dragGestureRecognized(DragGestureEvent dge) {
StringSelection transferable = new StringSelection(Integer.toString(list.getSelectedIndex()));
ds.startDrag(dge, DragSource.DefaultCopyDrop, transferable, this);
}
public void dragEnter(DragSourceDragEvent dsde) {
}
public void dragExit(DragSourceEvent dse) {
}
public void dragOver(DragSourceDragEvent dsde) {
}
public void dragDropEnd(DragSourceDropEvent dsde) {
if (dsde.getDropSuccess()) {
System.out.println("Succeeded");
} else {
System.out.println("Failed");
}
}
public void dropActionChanged(DragSourceDragEvent dsde) {
}
}
class MyListDropHandler extends TransferHandler {
DragDropList list;
public MyListDropHandler(DragDropList list) {
this.list = list;
}
public boolean canImport(TransferHandler.TransferSupport support) {
if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
if (dl.getIndex() == -1) {
return false;
} else {
return true;
}
}
public boolean importData(TransferHandler.TransferSupport support) {
if (!canImport(support)) {
return false;
}
Transferable transferable = support.getTransferable();
String indexString;
try {
indexString = (String) transferable.getTransferData(DataFlavor.stringFlavor);
} catch (Exception e) {
return false;
}
int index = Integer.parseInt(indexString);
JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
int dropTargetIndex = dl.getIndex();
System.out.println(dropTargetIndex + " : ");
System.out.println("inserted");
return true;
}
}

View file

@ -0,0 +1,106 @@
/*
Copyright 2006 Eric Hakenholz
This file is part of C.a.R. software.
C.a.R. is a free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
C.a.R. 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eric.macros;
import eric.GUI.palette.PaletteManager;
import eric.GUI.pipe_tools;
import javax.swing.JMenuItem;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import rene.gui.MyMenuItem;
import rene.zirkel.ZirkelFrame;
import rene.zirkel.macro.Macro;
public class JDefaultMutableTreeNode extends DefaultMutableTreeNode {
/**
*
*/
MyMenuItem PMmenuitem;
JMenuItem MainMenuItem;
ZirkelFrame ZF;
String name = "";
Macro m;
int macrotype;// 0: library macro 2 : file macro
public JDefaultMutableTreeNode(final String s) {
super(s);
macrotype = MacroTools.FILE_MACRO;
}
public JDefaultMutableTreeNode(final ZirkelFrame zf, final Macro mcr) {
super();
ZF = zf;
macrotype = (mcr.isProtected()) ? MacroTools.LIBRARY_MACRO : MacroTools.FILE_MACRO;
name = mcr.getName();
m = mcr;
final String[] mytab = mcr.getName().split(("/"));
MainMenuItem = new JMenuItem(mytab[mytab.length - 1]);
MainMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menuaction();
}
});
MainMenuItem.setFont(new java.awt.Font("System", 0, 13));
PMmenuitem = new MyMenuItem(mytab[mytab.length - 1]);
PMmenuitem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(final java.awt.event.ActionEvent evt) {
menuaction();
}
});
this.setUserObject(mytab[mytab.length - 1]);
}
public void menuaction() {
PaletteManager.deselectgeomgroup();
pipe_tools.setMacroHelp(m);
ZF.runMacro(m);
}
public void runZmacro() {
ZF.runMacro(m);
}
public void setType(final int newtype) {
macrotype=newtype;
m.setProtected(macrotype==MacroTools.LIBRARY_MACRO);
}
public void ActualisePath() {
if (this.isLeaf()) {
final TreeNode[] mypath = this.getPath();
name = "";
for (int i = 1; i < mypath.length - 1; i++) {
name += mypath[i].toString() + "/";
}
name += mypath[mypath.length - 1].toString();
ZF.ZC.renameMacro(m, name);
PMmenuitem.setLabel(mypath[mypath.length - 1].toString());
MainMenuItem.setText(mypath[mypath.length - 1].toString());
}
}
}

View file

@ -0,0 +1,182 @@
/*
Copyright 2006 Eric Hakenholz
This file is part of C.a.R. software.
C.a.R. is a free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
C.a.R. 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eric.macros;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import eric.JEricPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import rene.gui.Global;
public class JMacrosFProperties extends JEricPanel {
/**
*
*/
private final JTable table;
private final DefaultTableModel model;
private final JMacrosInspector JMI;
public JMacrosFProperties(final JMacrosInspector jmi) {
super(new GridLayout(1, 0));
JMI = jmi;
this.setFocusable(false);
model = new DefaultTableModel() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public Class getColumnClass(final int columnIndex) {
if ((columnIndex == 2) || (columnIndex == 3)) {
return Integer.class;
} else {
return super.getColumnClass(columnIndex);
}
}
};
table = new JTable(model) {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(final int row, final int col) {
return false;
}
@Override
public boolean isCellSelected(final int row, final int col) {
return false;
}
@Override
public TableCellRenderer getCellRenderer(final int row,
final int column) {
final Object value = getValueAt(row, column);
if (value != null) {
return getDefaultRenderer(value.getClass());
}
return getDefaultRenderer(String.class);
}
};
table.setCellSelectionEnabled(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setShowGrid(true);
table.setGridColor(Color.lightGray);
table.setRowHeight(20);
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, false), "none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "none");
model.addColumn(Global.Loc("mi.tab.type"));
model.addColumn(Global.Loc("mi.tab.name"));
model.addColumn("Construction index"); // Dibs : Construction index -> ExecuteMacro
model.addColumn("Click index"); // Click index -> ExecuteMacroAsBuilt
// model.addRow(new Object[]{new String(""),new String(""),new
// String(""),new Boolean(false), new Boolean(false)});
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(45);
table.getColumnModel().getColumn(1).setPreferredWidth(45);
table.getColumnModel().getColumn(2).setPreferredWidth(112);
table.getColumnModel().getColumn(3).setPreferredWidth(80);
final JScrollPane scrollPane = new JScrollPane(table);
scrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scrollPane);
}
public int getRowCount() {
return model.getRowCount();
}
public Object getValueAt(final int i, final int j) {
return model.getValueAt(i, j);
}
public void stopCellEditing() {
final TableCellEditor editor = table.getCellEditor();
if (editor != null) {
editor.stopCellEditing();
}
}
public String getOType(final int row) {
return (String) model.getValueAt(row, 0);
}
public String getOName(final int row) {
return (String) model.getValueAt(row, 1);
}
public String getOFIndex(final int row) {
return (String) model.getValueAt(row, 2);
}
public String getOFIndex2(final int row) {
return (String) model.getValueAt(row, 3);
}
public void setOType(final String what, final int row) {
model.setValueAt(new String(what), row, 0);
}
public void setOName(final String what, final int row) {
model.setValueAt(new String(what), row, 1);
}
public void addRow(final String type, final String name,
final int index, final int index2) {
model.addRow(new Object[] { new String(type), new String(name),
new String(String.valueOf(index)), new String(String.valueOf(index2)) });
}
public void removeAllRows() {
while (model.getRowCount() > 0)
model.removeRow(0);
}
}

View file

@ -0,0 +1,653 @@
/*
Copyright 2006 Eric Hakenholz
This file is part of C.a.R. software.
C.a.R. is a free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
C.a.R. 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eric.macros;
import eric.GUI.pipe_tools;
import eric.GUI.themes;
import eric.JZirkelCanvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import eric.JEricPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import rene.gui.Global;
import rene.zirkel.ZirkelCanvas;
import rene.zirkel.ZirkelFrame;
import rene.zirkel.macro.Macro;
import rene.zirkel.objects.ConstructionObject;
/* This class represent the macro properties inspector
*/
public class JMacrosInspector extends JDialog implements MouseListener, MouseMotionListener, TopDialog {
private static Macro M=null;
private int PW=315; // Palette width
private int PH=516; //395
private static JDefaultMutableTreeNode node;
private IContent content;
private MouseEvent pressed;
private Point location;
private static JMacrosInspector me;
public JMacrosInspector(JDefaultMutableTreeNode mymacro) {
setFocusableWindowState(true);
setFocusable(false);
this.setSize(PW, PH);
setUndecorated(true);
if (!pipe_tools.isApplet()) {
setAlwaysOnTop(true);
} else {
addWindowListener(new WindowAdapter() {
public void windowDeactivated(WindowEvent e) {
toFront();
}
});
}
// content is a JPanel which represents the content of the palette
content=new IContent(this);
setContentPane(content);
DialogTitleBar title=new DialogTitleBar(this, PW);
content.add(title, 0);
ZirkelCanvas zc=JZirkelCanvas.getCurrentZC();
if (zc!=null) {
Point p=zc.getLocationOnScreen();
setLocation(p.x+10, p.y+(zc.getSize().height-PH)/2);
}
setVisible(true);
}
public static boolean isDialogVisible() {
return (me!=null);
}
public static void openInspector(JDefaultMutableTreeNode mymacro) {
if (me==null) {
me=new JMacrosInspector(mymacro);
}
changemacro(mymacro);
}
public static void changemacro(JDefaultMutableTreeNode mymacro) {
if (me!=null) {
me.setMacro(mymacro);
}
}
// set location of the palette (near the right border of the macro panel) :
public void setStandardLocation() {
}
public void clearPalette() {
if (M!=null) {
content.changemacro();
}
node=null;
M=null;
content.clearfields();
}
// method called each time the user ask properties or select another macro
// in the tree
public void setMacro(final JDefaultMutableTreeNode mynode) {
node=mynode;
M=node.m;
content.fillfields();
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent me) {
pressed=me;
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent me) {
location=getLocation(location);
int x=location.x-pressed.getX()+me.getX();
int y=location.y-pressed.getY()+me.getY();
setLocation(x, y);
Toolkit.getDefaultToolkit().sync();
}
public void mouseMoved(MouseEvent e) {
}
public static void quit() {
if (me!=null) {
me.exit();
}
}
public void exit() {
content.changemacro();
node=null;
me=null;
dispose();
}
public void fixObject(int i, boolean b) {
content.fixObject(i, b);
}
public void askObject(int i, boolean b) {
content.askObject(i, b);
}
// this embedded class represents the content of the palette :
public class IContent extends JEricPanel {
/**
*
*/
JMacrosInspector JMI;
JLabel name;
JTextArea comment;
JMacrosProperties props;
JMacrosFProperties propTs;
JCheckBox hideDuplicates;
private JEricPanel margin(final int w) {
final JEricPanel mypan=new JEricPanel();
fixsize(mypan, w, 1);
mypan.setOpaque(false);
return mypan;
}
public IContent(final JMacrosInspector jmi) {
JMI=jmi;
setLayout(new javax.swing.BoxLayout(this,
javax.swing.BoxLayout.Y_AXIS));
this.setFocusable(false);
name=new JLabel();
comment=new JTextArea();
props=new JMacrosProperties(JMI);
propTs=new JMacrosFProperties(JMI);
hideDuplicates=new JCheckBox(Global.Loc("mi.hideduplicates"));
newnameline();
this.add(new mySep(1));
newcommentline();
this.add(new mySep(1));
newproperties();
this.add(new mySep(1));
newTproperties();
this.add(new mySep(1));
newhideproperties();
this.add(new mySep(1));
newcontrolline();
fixsize(this, PW, PH);
}
// set sizes of a palette's JComponent :
private void fixsize(final JComponent cp, final int w, final int h) {
final Dimension d=new Dimension(w, h);
cp.setMaximumSize(d);
cp.setMinimumSize(d);
cp.setPreferredSize(d);
cp.setSize(d);
}
// add the "name" topic of the palette :
public void newnameline() {
final JEricPanel rub=new myRub();
final JEricPanel myline1=new ContentLine(25);
fixsize(name, PW-10, 18);
myline1.add(margin(5));
myline1.add(name);
rub.add(myline1);
this.add(rub);
}
// add the "comment" topic of the palette :
public void newcommentline() {
final JEricPanel rub=new myRub();
final JScrollPane jScroll=new JScrollPane();
final JEricPanel myline1=new ContentLine(22);
final JLabel namelabel=new JLabel(Global.Loc("mi.comment"));
fixsize(namelabel, PW-10, 14);
myline1.add(margin(5));
myline1.add(namelabel);
final JEricPanel myline2=new ContentLine(100);
comment.setLineWrap(true);
jScroll.setViewportView(comment);
jScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
fixsize(jScroll, PW-10, 80);
myline2.add(margin(5));
myline2.add(jScroll);
rub.add(myline1);
rub.add(myline2);
this.add(rub);
}
// add the "target properties" topic of the palette :
public void newhideproperties() {
final JEricPanel rub=new myRub();
rub.setLayout(new javax.swing.BoxLayout(rub,
javax.swing.BoxLayout.Y_AXIS));
//final JEricPanel myline1=new ContentLine(22); // Dibs : on a ajouté une parie pour les finaux
//final JLabel namelabel=new JLabel(Global.Loc("mi.hideproperties"));
//fixsize(namelabel, PW-10, 14);
//myline1.add(margin(5));
//myline1.add(namelabel);
final JEricPanel mylineC3=new ContentLine(27);
hideDuplicates.setOpaque(false);
mylineC3.add(margin(10));
mylineC3.add(hideDuplicates);
//rub.add(myline1);
rub.add(mylineC3);
this.add(rub);
}
// add the apply button to the bottom of the palette :
public void newcontrolline() {
final JEricPanel rub=new myRub();
final JEricPanel myline=new ContentLine(25);
final JButton applybtn=new JButton("Apply");
applybtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
changemacro();
// It's important to refresh the inspector because
// parameters position may have change :
fillfields();
}
});
// applybtn.setBorder(BorderFactory.createRaisedBevelBorder());
// applybtn.setBorder(BorderFactory.createEmptyBorder());
fixsize(applybtn, 90, 18);
applybtn.setFont(new Font("System", Font.BOLD, 11));
final JEricPanel sep=new JEricPanel();
sep.setOpaque(false);
myline.add(sep);
// JButton jb=new JButton("Aaaa");
// fixsize(jb,90,18);
myline.add(applybtn);
myline.add(margin(5));
rub.add(myline);
this.add(rub);
}
// add the parameters properties to the palette :
public void newproperties() {
final JEricPanel rub=new myRub();
final JEricPanel myline1=new ContentLine(22);
final JLabel namelabel=new JLabel(Global.Loc("mi.properties"));
myline1.add(margin(5));
myline1.add(namelabel);
fixsize(namelabel, PW-10, 14);
final JEricPanel myline2=new ContentLine(130);
fixsize(props, PW-10, 100);
myline2.add(margin(5));
myline2.add(props);
rub.add(myline1);
rub.add(myline2);
this.add(rub);
}
public void newTproperties() {
final JEricPanel rub=new myRub();
final JEricPanel myline1=new ContentLine(22);
final JLabel namelabel=new JLabel(Global.Loc("mi.hideproperties"));
myline1.add(margin(5));
myline1.add(namelabel);
fixsize(namelabel, PW-10, 14);
final JEricPanel myline2=new ContentLine(120);
fixsize(propTs, PW-10, 100);
myline2.add(margin(5));
myline2.add(propTs);
rub.add(myline1);
rub.add(myline2);
this.add(rub);
}
/*************************************************
* this is the tricky method : it reads the inspector changes and then
* store the new values in the macro m. A macro contains two types of
* parameters : 1) normal parameters (the one you shows at the first
* step of macro's creation ). They are inside the m.Params array for
* ConstructionObjects and m.Prompts array for prompts 2) numerical
* input parameters (it's possible to make macros with numerical inputs
* ). Name of Objects are in the PromptFor array and prompts in the
* PromptName array
*************************************************/
public void changemacro() {
ConstructionObject[] params;
final Vector newparams=new Vector();
final Vector newprompts=new Vector();
final Vector newpromptFor=new Vector();
final Vector newpromptName=new Vector();
props.stopCellEditing();
if (M==null) {
return;
}
if (isError()) {
return;
}
M.setComment(comment.getText());
params=M.getParams();
// read "normal" parameters and store them in :
// newparams and newprompts if "ask" is not checked (stays "normal")
// newPromptFor and newPromptName if "ask" is not checked (becomes
// "numerical input")
for (int i=0; i<params.length; i++) {
params[i].setName(props.getOName(i));
if (props.getOAsk(i)) {
newpromptFor.add(props.getOName(i));
newpromptName.add(props.getOPrompt(i));
params[i].setHidden(true);
params[i].clearParameter();
} else {
newparams.add(params[i]);
if (props.getOFix(i)) {
newprompts.add("="+props.getOName(i));
} else {
newprompts.add(props.getOPrompt(i));
}
}
}
int rang=0;
// read "numerical input" parameters and store them in :
// newparams and newprompts if "ask" is not checked (stays "normal")
// newPromptFor and newPromptName if "ask" is not checked (becomes
// "numerical input")
for (int i=params.length; i<props.getRowCount(); i++) {
ConstructionObject E=null;
// looking for the expression with the name
// m.PromptFor[i-params.length]
for (int j=0; j<M.V.size(); j++) {
// sure it's going to find one :
if (((ConstructionObject) M.V.get(j)).getName().equals(
M.PromptFor[i-params.length])) {
E=(ConstructionObject) M.V.get(j);
break;
}
}
E.setName(props.getOName(i));
if (props.getOAsk(i)) {
newpromptFor.add(props.getOName(i));
newpromptName.add(props.getOPrompt(i));
} else {
newparams.add(rang, E);
if (props.getOFix(i)) {
newprompts.add(rang, "="+props.getOName(i));
} else {
newprompts.add(rang, props.getOPrompt(i));
}
rang++;
}
}
int ln=newparams.size();
// Clear and prepare the Params, Prompts and LastParams arrays :
M.Params=new ConstructionObject[ln];
M.Prompts=new String[ln];
M.LastParams=new String[ln];
// Store the newparams and newprompts in the macro :
for (int i=0; i<ln; i++) {
M.Params[i]=(ConstructionObject) newparams.get(i);
M.Prompts[i]=(String) newprompts.get(i);
M.LastParams[i]=null;
M.Params[i].setHidden(false);
M.Params[i].setMainParameter(true);
M.Params[i].setParameter(true);
}
ln=newpromptFor.size();
// Clear and prepare the PromptFor, PromptName arrays :
M.PromptFor=new String[ln];
M.PromptName=new String[ln];
// Store the newpromptFor and newpromptName in the macro :
for (int i=0; i<ln; i++) {
M.PromptFor[i]=(String) newpromptFor.get(i);
M.PromptName[i]=(String) newpromptName.get(i);
}
// Conform the macro's hideduplicate property to the checkbox value
// :
M.hideDuplicates(hideDuplicates.isSelected());
}
// this method is called by the JMacroProperties object
// each time a user check/uncheck a "fix" JCheckBox :
public void fixObject(final int i, final boolean fix) {
final String newprompt=(fix)?"":props.getOName(i);
props.setOPrompt(newprompt, i);
if (fix) {
props.setOAsk(false, i);
}
}
// this method is called by the JMacroProperties object
// each time a user check/uncheck a "ask" JCheckBox :
public void askObject(final int i, final boolean ask) {
if ((ask)&&props.getOFix(i)) {
props.setOFix(false, i);
fixObject(i, false);
}
}
public void clearfields() {
name.setText(Global.Loc("mi.name"));
comment.setText("");
props.removeAllRows();
hideDuplicates.setSelected(false);
}
public boolean isError() {
final boolean isErr=false;
// first see if at least one row contains no selected checkbox :
final int ln=props.getRowCount();
boolean err=true;
for (int i=0; i<ln; i++) {
err=(err)&&((props.getOFix(i))||(props.getOAsk(i)));
}
if (err) {
JOptionPane.showMessageDialog(null,
Global.Loc("mi.error.initial"));
return true;
}
return isErr;
}
// read the params, prompts, PromptFor, PromptName arrays of
// the macro and fill the inspector fields :
public void fillfields() {
ConstructionObject[] params;
String[] prompts;
Vector paramFs;
if (M==null) {
return;
}
name.setText(Global.Loc("mi.name")+" "
+(String) node.getUserObject());
comment.setText(M.Comment);
props.removeAllRows();
params=M.getParams();
paramFs=M.getTargets();
prompts=M.getPrompts();
String pr="";
// fill JTable first lines with "normal" parameters :
for (int i=0; i<params.length; i++) {
pr="="+params[i].getName();
String tpe="";
String classtpes[]=params[i].getClass().getName().split("\\.");
try {
tpe=Global.Loc(params[i].getClass().getName());
} catch (final Exception e) {
tpe=classtpes[classtpes.length-1];
}
if (tpe==null) {
tpe=classtpes[classtpes.length-1];
}
final boolean withask=params[i].getClass().getName().endsWith("ExpressionObject");
// withask=(withask)||(params[i].getClass().getName().endsWith("FixedAngleObject"));
// withask=(withask)||(params[i].getClass().getName().endsWith("PrimitiveCircleObject"));
if (withask) {
props.addRow(tpe, params[i].getName(), prompts[i],
prompts[i].equals(pr), false);
} else {
props.addRow(tpe,
params[i].getName(),
prompts[i],
prompts[i].equals(pr));
}
}
// fill the rest of JTable with PromptFor Expressions, if any :
for (int i=0; i<M.PromptFor.length; i++) {
final String tpe=Global.Loc("rene.zirkel.objects.ExpressionObject");
props.addRow(tpe, M.PromptFor[i], M.PromptName[i], false, true);
}
propTs.removeAllRows();
for (int i=0; i<paramFs.size(); i++) {
if (paramFs.get(i)!=null) {
ConstructionObject nemo = (ConstructionObject) paramFs.get(i);
String tpe="";
String classtpes[]=nemo.getClass().getName().split("\\.");
try {
tpe=Global.Loc(nemo.getClass().getName());
} catch (final Exception e) {
tpe=classtpes[classtpes.length-1];
}
if (tpe==null) {
tpe=classtpes[classtpes.length-1];
}
if (tpe.contains("Intersection")||tpe.contains("point")) tpe="Pt";
if (tpe.contains("Plumb")||tpe.contains("Line")||tpe.contains("Parallel")) tpe="Line";
if (tpe.contains("Circle")) tpe="Circle";
propTs.addRow(tpe, nemo.getName(), i, nemo.getMacroFinalIndex());
}
}
hideDuplicates.setSelected(M.hideDuplicates());
}
class myRub extends JEricPanel {
/**
*
*/
@Override
public void paintComponent(final java.awt.Graphics g) {
super.paintComponent(g);
final java.awt.Dimension d=this.getSize();
g.drawImage(themes.getImage("palbackground2.gif"), 0, 0,
d.width, d.height, this);
}
public myRub() {
this.setLayout(new javax.swing.BoxLayout(this,
javax.swing.BoxLayout.Y_AXIS));
this.setAlignmentX(0F);
}
}
class ContentLine extends JEricPanel {
/**
*
*/
public ContentLine(final int height) {
this.setLayout(new javax.swing.BoxLayout(this,
javax.swing.BoxLayout.X_AXIS));
this.setAlignmentX(0F);
this.setMaximumSize(new java.awt.Dimension(PW, height));
this.setMinimumSize(new java.awt.Dimension(PW, height));
this.setPreferredSize(new java.awt.Dimension(PW, height));
this.setSize(PW, height);
this.setOpaque(false);
}
}
class mySep extends JEricPanel {
/**
*
*/
public mySep(final int height) {
this.setLayout(new javax.swing.BoxLayout(this,
javax.swing.BoxLayout.X_AXIS));
this.setAlignmentX(0F);
this.setMaximumSize(new java.awt.Dimension(PW, height));
this.setMinimumSize(new java.awt.Dimension(PW, height));
this.setPreferredSize(new java.awt.Dimension(PW, height));
this.setSize(PW, height);
this.setBackground(new Color(200, 200, 200));
}
}
}
}

View file

@ -0,0 +1,227 @@
/*
Copyright 2006 Eric Hakenholz
This file is part of C.a.R. software.
C.a.R. is a free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
C.a.R. 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eric.macros;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import eric.JEricPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import rene.gui.Global;
public class JMacrosProperties extends JEricPanel {
/**
*
*/
private final JTable table;
private final DefaultTableModel model;
private final JMacrosInspector JMI;
public JMacrosProperties(final JMacrosInspector jmi) {
super(new GridLayout(1, 0));
JMI = jmi;
this.setFocusable(false);
model = new DefaultTableModel() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public Class getColumnClass(final int columnIndex) {
if ((columnIndex == 3) || (columnIndex == 4)) {
return Boolean.class;
} else {
return super.getColumnClass(columnIndex);
}
}
};
table = new JTable(model) {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(final int row, final int col) {
if (col == 0)
return false;
if ((col == 2)
&& (String.valueOf(getValueAt(row, 3)).equals("true")))
return false;
return (getValueAt(row, col) != null);
}
@Override
public boolean isCellSelected(final int row, final int col) {
return false;
}
@Override
public void setValueAt(final Object o, final int row, final int col) {
getModel().setValueAt(o, row, col);
if (col == 3)
JMI.fixObject(row, String.valueOf(
getModel().getValueAt(row, col)).equals("true"));
if (col == 4)
JMI.askObject(row, String.valueOf(
getModel().getValueAt(row, col)).equals("true"));
}
@Override
public TableCellRenderer getCellRenderer(final int row,
final int column) {
final Object value = getValueAt(row, column);
if (value != null) {
return getDefaultRenderer(value.getClass());
}
return getDefaultRenderer(String.class);
}
};
table.setCellSelectionEnabled(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setShowGrid(true);
table.setGridColor(Color.lightGray);
table.setRowHeight(20);
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, false), "none");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false), "none");
model.addColumn(Global.Loc("mi.tab.type"));
model.addColumn(Global.Loc("mi.tab.name"));
model.addColumn(Global.Loc("mi.tab.prompt"));
model.addColumn(Global.Loc("mi.tab.fix"));
model.addColumn(Global.Loc("mi.tab.ask"));
// model.addRow(new Object[]{new String(""),new String(""),new
// String(""),new Boolean(false), new Boolean(false)});
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(45);
table.getColumnModel().getColumn(1).setPreferredWidth(45);
table.getColumnModel().getColumn(2).setPreferredWidth(125);
table.getColumnModel().getColumn(3).setPreferredWidth(37);
table.getColumnModel().getColumn(4).setPreferredWidth(35);
final JScrollPane scrollPane = new JScrollPane(table);
scrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scrollPane);
}
public int getRowCount() {
return model.getRowCount();
}
public Object getValueAt(final int i, final int j) {
return model.getValueAt(i, j);
}
public void stopCellEditing() {
final TableCellEditor editor = table.getCellEditor();
if (editor != null) {
editor.stopCellEditing();
}
}
public String getOType(final int row) {
return (String) model.getValueAt(row, 0);
}
public String getOName(final int row) {
return (String) model.getValueAt(row, 1);
}
public String getOPrompt(final int row) {
return (String) model.getValueAt(row, 2);
}
public boolean getOFix(final int row) {
return String.valueOf(model.getValueAt(row, 3)).equals("true");
}
public boolean getOAsk(final int row) {
if (model.getValueAt(row, 4) == null)
return false;
return String.valueOf(table.getModel().getValueAt(row, 4)).equals(
"true");
}
public void setOType(final String what, final int row) {
model.setValueAt(new String(what), row, 0);
}
public void setOName(final String what, final int row) {
model.setValueAt(new String(what), row, 1);
}
public void setOPrompt(final String what, final int row) {
model.setValueAt(new String(what), row, 2);
}
public void setOAsk(final boolean what, final int row) {
if (model.getValueAt(row, 4) != null)
model.setValueAt(new Boolean(what), row, 4);
}
public void setOFix(final boolean what, final int row) {
model.setValueAt(new Boolean(what), row, 3);
}
public void addRow(final String type, final String name,
final String prompt, final boolean fix) {
final String newprompt = (fix) ? "" : prompt;
model.addRow(new Object[] { new String(type), new String(name),
new String(newprompt), new Boolean(fix), null });
}
public void addRow(final String type, final String name,
final String prompt, final boolean fix, final boolean ask) {
final String newprompt = (fix) ? "" : prompt;
model.addRow(new Object[] { new String(type), new String(name),
new String(newprompt), new Boolean(fix), new Boolean(ask) });
}
public void removeAllRows() {
while (model.getRowCount() > 0)
model.removeRow(0);
}
}

570
eric/macros/MacroTools.java Normal file
View file

@ -0,0 +1,570 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eric.macros;
import eric.GUI.pipe_tools;
import eric.GUI.themes;
import eric.GUI.windowComponent;
import eric.JZirkelCanvas;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Vector;
import rene.gui.Global;
import rene.util.xml.XmlReader;
import rene.util.xml.XmlTag;
import rene.util.xml.XmlTagPI;
import rene.util.xml.XmlTree;
import rene.zirkel.ZirkelCanvas;
import rene.zirkel.ZirkelFrame;
import rene.zirkel.construction.ConstructionException;
import rene.zirkel.construction.Count;
import rene.zirkel.macro.Macro;
import rene.zirkel.macro.MacroItem;
import rene.zirkel.macro.MacroRunner;
import rene.zirkel.objects.ConstructionObject;
import rene.zirkel.objects.TextObject;
/**
*
* @author erichake
*/
public class MacroTools {
static public final int LIBRARY_MACRO=0;
static public final int FILE_MACRO=2;
static private Vector librarymacros=new Vector();
static public Vector builtinmacros=new Vector();
static public String MacrosLibraryFileName="";
static public String MacrosBackupLibraryFileName="";
public static void createLocalDirectory() {
// Setting (if necessary) home directory name and home library macros
// file name :
final String mypath=Global.AppPath();
// Place the help files in the local directory :
if ((Global.isNewVersion())||(!(new File(Global.getHomeDirectory()+"docs").exists()))) {
try {
Global.copyFiles(new File(mypath+"docs"), new File(
Global.getHomeDirectory()+"docs"));
} catch (final IOException ex) {
System.out.println("bug : createLocalDirectory()");
}
}
// Place the javascript files in the local directory :
if ((Global.isNewVersion())||(!(new File(Global.getHomeDirectory()+"scripts").exists()))) {
try {
Global.copyFiles(new File(mypath+"scripts"), new File(
Global.getHomeDirectory()+"scripts"));
} catch (final IOException ex) {
System.out.println("bug : createLocalDirectory()");
}
}
String Filename="library.mcr";
if (new File(mypath+Global.name("language", "")+"library.mcr").exists()) {
Filename=Global.name("language", "")+"library.mcr";
} else if (new File(Global.getHomeDirectory()+Global.name("language", "")+"library.mcr").exists()) {
Filename=Global.name("language", "")+"library.mcr";
}
MacrosLibraryFileName=Global.getHomeDirectory()+Filename;
// is there a library in home folder ?
if (new File(MacrosLibraryFileName).exists()) {
// Is it a new version at this startup ?
if (Global.isNewVersion()) {
MacrosBackupLibraryFileName=Global.getHomeDirectory()+"library_backup.mcr";
Global.copyFile(MacrosLibraryFileName, MacrosBackupLibraryFileName);
Global.copyFile(mypath+Filename, MacrosLibraryFileName);
}
} else {
new File(Global.getHomeDirectory()).mkdirs();
Global.copyFile(mypath+Filename, MacrosLibraryFileName);
}
Global.makeWindowConfigFolderInvisible();
}
public static Vector getBuiltinMacros() {
return builtinmacros;
}
public static Vector getLibraryMacros() {
return librarymacros;
}
public static void clearLibraryMacros() {
librarymacros.removeAllElements();
}
public static void addToLibraryMacros(MacroItem mi) {
librarymacros.add(mi);
}
public static void updateLibraryMacros() {
ZirkelCanvas zc=JZirkelCanvas.getCurrentZC();
if ((!(zc==null))) {
librarymacros.clear();
final Vector V=zc.getMacros();
for (int i=0; i<V.size(); i++) {
final MacroItem mi=(MacroItem) V.get(i);
if (mi.M.isProtected()) {
if (!(mi.M.Name.startsWith("@builtin@"))) {
librarymacros.add(V.get(i));
}
}
}
}
}
public static boolean isDPMacro(String genericName){
for (int i=0; i<builtinmacros.size(); i++) {
Macro m=((MacroItem) builtinmacros.elementAt(i)).M;
if (m.getName().equals("@builtin@/DP_"+genericName)) {
return true;
}
}
return false;
}
public static void runDPMacro(String genericName){
runBuiltinMacro("@builtin@/DP_"+genericName);
}
public static void runBuiltinMacro(final String macroname) {
Vector<?> mc;
Macro m;
TextObject t;
ZirkelFrame ZF=JZirkelCanvas.getCurrentZF();
if (ZF==null) {
return;
}
mc=builtinmacros;
for (int i=0; i<mc.size(); i++) {
m=((MacroItem) mc.elementAt(i)).M;
if (m.getName().equals(macroname)) {
if (m.getName().equals("@builtin@/DP_line")) {
m.Prompts[1]=Global.Loc("macro.DP_line.1");
m.Prompts[2]=Global.Loc("macro.DP_line.2");
m.createDPObjects=ConstructionObject.DP_LINE;
}
else if (m.getName().equals("@builtin@/DP_midpoint")) {
m.Prompts[1]=Global.Loc("macro.DP_midpoint.1");
m.Prompts[2]=Global.Loc("macro.DP_midpoint.2");
}
else if (m.getName().equals("@builtin@/DP_bi_syma")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_syma.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_syma.2");
}
else if (m.getName().equals("@builtin@/DP_bi_symc")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_symc.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_symc.2");
} else if (m.getName().equals("@builtin@/DP_plumb")) {
m.Prompts[1]=Global.Loc("macro.DP_plumb.1");
m.Prompts[2]=Global.Loc("macro.DP_plumb.2");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_bi_med")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_med.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_med.2");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_bi_biss")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_biss.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_biss.2");
m.Prompts[3]=Global.Loc("macro.DP_bi_biss.3");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_angle")) {
m.Prompts[1]=Global.Loc("macro.DP_angle.1");
m.Prompts[2]=Global.Loc("macro.DP_angle.2");
m.Prompts[3]=Global.Loc("macro.DP_angle.3");
} else if (m.getName().equals("@builtin@/DP_segment")) {
m.Prompts[1]=Global.Loc("macro.DP_segment.1");
m.Prompts[2]=Global.Loc("macro.DP_segment.2");
m.createDPObjects=ConstructionObject.DP_SEGMENT;
}else if (m.getName().equals("@builtin@/DP_ray")) {
m.Prompts[1]=Global.Loc("macro.DP_ray.1");
m.Prompts[2]=Global.Loc("macro.DP_ray.2");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_circle")) {
m.Prompts[1]=Global.Loc("macro.DP_circle.1");
m.Prompts[2]=Global.Loc("macro.DP_circle.2");
m.createDPObjects=ConstructionObject.DP_CIRCLE;
} else if (m.getName().equals("@builtin@/DP_bi_distance")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_distance.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_distance.2");
m.Prompts[3]=Global.Loc("macro.DP_bi_distance.3");
} else if (m.getName().equals("@builtin@/DP_bi_perp_common")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_perp_common.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_perp_common.2");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_bi_pinceau1")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_pinceau1.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_pinceau1.2");
m.Prompts[3]=Global.Loc("macro.DP_bi_pinceau1.3");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_bi_pinceau3")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_pinceau3.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_pinceau3.2");
m.Prompts[3]=Global.Loc("macro.DP_bi_pinceau3.3");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_bi_pinceauinter")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_pinceauinter.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_pinceauinter.2");
m.Prompts[3]=Global.Loc("macro.DP_bi_pinceauinter.3");
m.Prompts[4]=Global.Loc("macro.DP_bi_pinceauinter.4");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_bi_pinceauhauteur")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_pinceauhauteur.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_pinceauhauteur.2");
m.Prompts[3]=Global.Loc("macro.DP_bi_pinceauhauteur.3");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_bi_pinceaucycle")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_pinceaucycle.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_pinceaucycle.2");
m.Prompts[3]=Global.Loc("macro.DP_bi_pinceaucycle.3");
m.createDPObjects=ConstructionObject.DP_CIRCLE;
} else if (m.getName().equals("@builtin@/DP_bi_pinceaubiss")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_pinceaubiss.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_pinceaubiss.2");
m.Prompts[3]=Global.Loc("macro.DP_bi_pinceaubiss.3");
m.Prompts[4]=Global.Loc("macro.DP_bi_pinceaubiss.4");
m.Prompts[5]=Global.Loc("macro.DP_bi_pinceaubiss.5");
m.Prompts[6]=Global.Loc("macro.DP_bi_pinceaubiss.6");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_bi_lineIP")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_lineIP.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_lineIP.2");
m.createDPObjects=ConstructionObject.DP_LINE;
} else if (m.getName().equals("@builtin@/DP_bi_horocycle")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_horocycle.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_horocycle.2");
m.createDPObjects=ConstructionObject.DP_CIRCLE;
} else if (m.getName().equals("@builtin@/DP_bi_equidistante")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_equidistante.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_equidistante.2");
m.createDPObjects=ConstructionObject.DP_CIRCLE;
} else if (m.getName().equals("@builtin@/DP_fixedangle")) {
m.Prompts[1]=Global.Loc("macro.DP_fixedangle.1");
m.Prompts[2]=Global.Loc("macro.DP_fixedangle.2");
m.Prompts[3]=Global.Loc("macro.DP_fixedangle.3");
} else if (m.getName().equals("@builtin@/DP_bi_circ")) {
m.Prompts[1]=Global.Loc("macro.DP_bi_circ.1");
m.Prompts[2]=Global.Loc("macro.DP_bi_circ.2");
m.Prompts[3]=Global.Loc("macro.DP_bi_circ.3");
m.createDPObjects=ConstructionObject.DP_CIRCLE;
}
else if (m.getName().equals("@builtin@/syma")) {
m.Prompts[0]=Global.Loc("macro.bi_syma.0");
m.Prompts[1]=Global.Loc("macro.bi_syma.1");
} else if (m.getName().equals("@builtin@/symc")) {
m.Prompts[0]=Global.Loc("macro.bi_symc.0");
m.Prompts[1]=Global.Loc("macro.bi_symc.1");
} else if (m.getName().equals("@builtin@/trans")) {
m.Prompts[0]=Global.Loc("macro.bi_trans.0");
m.Prompts[1]=Global.Loc("macro.bi_trans.1");
m.Prompts[2]=Global.Loc("macro.bi_trans.2");
} else if (m.getName().equals("@builtin@/med")) {
m.Prompts[0]=Global.Loc("macro.bi_med.0");
m.Prompts[1]=Global.Loc("macro.bi_med.1");
} else if (m.getName().equals("@builtin@/biss")) {
m.Prompts[0]=Global.Loc("macro.bi_biss.0");
m.Prompts[1]=Global.Loc("macro.bi_biss.1");
m.Prompts[2]=Global.Loc("macro.bi_biss.2");
} else if (m.getName().equals("@builtin@/circ")) {
m.Prompts[0]=Global.Loc("macro.bi_circ.0");
m.Prompts[1]=Global.Loc("macro.bi_circ.1");
m.Prompts[2]=Global.Loc("macro.bi_circ.2");
} else if (m.getName().equals("@builtin@/arc")) {
m.Prompts[0]=Global.Loc("macro.bi_circ.0");
m.Prompts[1]=Global.Loc("macro.bi_circ.1");
m.Prompts[2]=Global.Loc("macro.bi_circ.2");
} else if (m.getName().equals("@builtin@/function_u")) {
m.Prompts[0]=Global.Loc("macro.bi_expression.0");
} else if (m.getName().equals("@builtin@/t_align")) {
m.Prompts[0]=Global.Loc("macro.bi_circ.0");
m.Prompts[1]=Global.Loc("macro.bi_circ.1");
m.Prompts[2]=Global.Loc("macro.bi_circ.2");
t=(TextObject) m.getTargets().get(
m.getTargets().size()-1);
t.setLines(Global.Loc("macro.bi_t_align.text1"));
t=(TextObject) m.getTargets().get(
m.getTargets().size()-2);
t.setLines(Global.Loc("macro.bi_t_align.text0"));
} else if (m.getName().equals("@builtin@/t_para")) {
m.Prompts[0]=Global.Loc("macro.bi_t_para.0");
m.Prompts[1]=Global.Loc("macro.bi_t_para.1");
t=(TextObject) m.getTargets().get(
m.getTargets().size()-1);
t.setLines(Global.Loc("macro.bi_t_para.text0"));
t=(TextObject) m.getTargets().get(
m.getTargets().size()-2);
t.setLines(Global.Loc("macro.bi_t_para.text1"));
} else if (m.getName().equals("@builtin@/t_perp")) {
m.Prompts[0]=Global.Loc("macro.bi_t_para.0");
m.Prompts[1]=Global.Loc("macro.bi_t_para.1");
t=(TextObject) m.getTargets().get(
m.getTargets().size()-2);
t.setLines(Global.Loc("macro.bi_t_perp.text1"));
t=(TextObject) m.getTargets().get(
m.getTargets().size()-1);
t.setLines(Global.Loc("macro.bi_t_perp.text0"));
} else if (m.getName().equals("@builtin@/t_equi")) {
m.Prompts[0]=Global.Loc("macro.bi_t_equi.0");
m.Prompts[1]=Global.Loc("macro.bi_t_equi.1");
m.Prompts[2]=Global.Loc("macro.bi_t_equi.2");
t=(TextObject) m.getTargets().get(
m.getTargets().size()-1);
t.setLines(Global.Loc("macro.bi_t_equi.text0"));
t=(TextObject) m.getTargets().get(
m.getTargets().size()-2);
t.setLines(Global.Loc("macro.bi_t_equi.text1"));
} else if (m.getName().equals("@builtin@/t_app")) {
m.Prompts[0]=Global.Loc("macro.bi_t_app.0");
m.Prompts[1]=Global.Loc("macro.bi_t_app.1");
t=(TextObject) m.getTargets().get(
m.getTargets().size()-1);
t.setLines(Global.Loc("macro.bi_t_app.text1"));
t=(TextObject) m.getTargets().get(
m.getTargets().size()-2);
t.setLines(Global.Loc("macro.bi_t_app.text0"));
} else if (m.getName().equals("@builtin@/t_conf")) {
m.Prompts[0]=Global.Loc("macro.bi_t_conf.0");
m.Prompts[1]=Global.Loc("macro.bi_t_conf.1");
t=(TextObject) m.getTargets().get(
m.getTargets().size()-1);
t.setLines(Global.Loc("macro.bi_t_conf.text1"));
t=(TextObject) m.getTargets().get(
m.getTargets().size()-2);
t.setLines(Global.Loc("macro.bi_t_conf.text0"));
} else if (m.getName().equals("@builtin@/3Dcoords")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dcoords.0");
} else if (m.getName().equals("@builtin@/3Dcube")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dcube.0");
} else if (m.getName().equals("@builtin@/3Darete")) {
m.Prompts[0]=Global.Loc("macro.bi_3Darete.0");
m.Prompts[1]=Global.Loc("macro.bi_3Darete.1");
m.Prompts[2]=Global.Loc("macro.bi_3Darete.2");
m.Prompts[3]=Global.Loc("macro.bi_3Darete.3");
} else if (m.getName().equals("@builtin@/3Dtetra")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dtetra.0");
} else if (m.getName().equals("@builtin@/3Docta")) {
m.Prompts[4]=Global.Loc("macro.bi_3Docta.0");
} else if (m.getName().equals("@builtin@/3Disoc")) {
m.Prompts[4]=Global.Loc("macro.bi_3Disoc.0");
} else if (m.getName().equals("@builtin@/3Ddode")) {
m.Prompts[4]=Global.Loc("macro.bi_3Ddode.0");
} else if (m.getName().equals("@builtin@/3Dsymp")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dsymp.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dsymp.1");
m.Prompts[6]=Global.Loc("macro.bi_3Dsymp.2");
m.Prompts[7]=Global.Loc("macro.bi_3Dsymp.3");
} else if (m.getName().equals("@builtin@/3Dproj")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dproj.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dproj.1");
m.Prompts[6]=Global.Loc("macro.bi_3Dproj.2");
m.Prompts[7]=Global.Loc("macro.bi_3Dproj.3");
} else if (m.getName().equals("@builtin@/3Dsymc")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dsymc.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dsymc.1");
} else if (m.getName().equals("@builtin@/3Dtrans")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dtrans.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dtrans.1");
m.Prompts[6]=Global.Loc("macro.bi_3Dtrans.2");
} else if (m.getName().equals("@builtin@/3Dcircle1")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dcircle1.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dcircle1.1");
} else if (m.getName().equals("@builtin@/3Dcircle2")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dcircle2.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dcircle2.1");
m.Prompts[6]=Global.Loc("macro.bi_3Dcircle2.2");
} else if (m.getName().equals("@builtin@/3Dcircle3pts")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dcircle3pts.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dcircle3pts.1");
m.Prompts[6]=Global.Loc("macro.bi_3Dcircle3pts.2");
} else if (m.getName().equals("@builtin@/3Dplandroite")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dplandroite.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dplandroite.1");
m.Prompts[6]=Global.Loc("macro.bi_3Dplandroite.2");
m.Prompts[7]=Global.Loc("macro.bi_3Dplandroite.3");
} else if (m.getName().equals("@builtin@/3Dplanplan")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dplanplan.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dplanplan.1");
m.Prompts[6]=Global.Loc("macro.bi_3Dplanplan.2");
m.Prompts[7]=Global.Loc("macro.bi_3Dplanplan.3");
m.Prompts[8]=Global.Loc("macro.bi_3Dplanplan.4");
m.Prompts[9]=Global.Loc("macro.bi_3Dplanplan.5");
} else if (m.getName().equals("@builtin@/3Dsphererayon")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dsphererayon.0");
} else if (m.getName().equals("@builtin@/3Dspherepoint")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dspherepoint.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dspherepoint.1");
} else if (m.getName().equals("@builtin@/3Dspheredroite")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dspheredroite.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dspheredroite.1");
} else if (m.getName().equals("@builtin@/3Dsphereplan")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dsphereplan.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dsphereplan.1");
m.Prompts[6]=Global.Loc("macro.bi_3Dsphereplan.2");
m.Prompts[7]=Global.Loc("macro.bi_3Dsphereplan.3");
} else if (m.getName().equals("@builtin@/3Dspheresphere")) {
m.Prompts[4]=Global.Loc("macro.bi_3Dspheresphere.0");
m.Prompts[5]=Global.Loc("macro.bi_3Dspheresphere.1");
}
ZF.runMacro(m);
}
}
}
private static void LoadMacros(final InputStream in, final Vector Macros)
throws Exception {
Macro m;
try {
final XmlReader xml=new XmlReader();
xml.init(in);
XmlTree tree=xml.scan();
if (tree==null) {
throw new ConstructionException("XML file not recognized");
}
Enumeration e=tree.getContent();
while (e.hasMoreElements()) {
tree=(XmlTree) e.nextElement();
if (tree.getTag() instanceof XmlTagPI) {
continue;
}
if (!tree.getTag().name().equals("CaR")) {
throw new ConstructionException("CaR tag not found");
} else {
break;
}
}
e=tree.getContent();
while (e.hasMoreElements()) {
tree=(XmlTree) e.nextElement();
final XmlTag tag=tree.getTag();
if (tag.name().equals("Macro")) {
try {
Count.setAllAlternate(true);
m=new Macro(null, tree);
int i=0;
for (i=0; i<Macros.size(); i++) {
if (((MacroItem) Macros.elementAt(i)).M.getName().equals(m.getName())) {
break;
}
}
if (i>=Macros.size()) {
m.setProtected(true);
final MacroItem mi=new MacroItem(m, null);
Macros.addElement(mi);
}
} catch (final ConstructionException ex) {
Count.setAllAlternate(false);
throw ex;
}
Count.setAllAlternate(false);
} else {
throw new ConstructionException("Construction not found");
}
}
} catch (final Exception e) {
throw e;
}
}
public static void LoadDefaultMacrosAtStartup() {
// Loading builtin macros (for some icons in palette, like symetry)
try {
final InputStream o=MacroTools.class.getResourceAsStream("/builtin.mcr");
LoadMacros(o, builtinmacros);
o.close();
} catch (final Exception e) {
System.out.println("builtinmacros bug");
}
if ((!themes.isApplet())&&(new File(MacrosLibraryFileName).exists())) {
try {
final InputStream o=new FileInputStream(MacrosLibraryFileName);
LoadMacros(o, librarymacros);
o.close();
if (!MacrosBackupLibraryFileName.equals("")) {
final InputStream o2=new FileInputStream(
MacrosBackupLibraryFileName);
LoadMacros(o2, librarymacros);
o2.close();
final File f=new File(MacrosBackupLibraryFileName);
f.delete();
}
return;
} catch (final Exception e) {
System.out.println("librarymacros bug");
}
}
try {
final InputStream o=MacroTools.class.getResourceAsStream("/default.mcr");
LoadMacros(o, librarymacros);
o.close();
return;
} catch (final Exception e) {
System.out.println("default macros bug");
}
}
public static void saveLibraryToDisk() {
if (JZirkelCanvas.getCurrentZF()!=null) {
ZirkelFrame ZF=new ZirkelFrame(pipe_tools.isApplet());
ZF.dosave(MacrosLibraryFileName, false, true, true, false, librarymacros);
}
}
/* If user changes macro type in the tree (e.g. "add to library") from one figure,
* library macros vector is changed, so we must transmit all changes to
* others figures :
*/
public static void populateMacrosTypeChanges() {
int max=JZirkelCanvas.getZCsSize();
for (int i=0; i<max; i++) {
ZirkelCanvas zc=JZirkelCanvas.getZC(i);
setDefaultMacros(zc);
}
}
// Called by the JZirkelCanvas constructor :
public static void setDefaultMacros(ZirkelCanvas zc) {
if (builtinmacros.size()==0) {
LoadDefaultMacrosAtStartup();
}
if (!(zc==null)) {
int i=0;
final Vector F=new Vector();
final Vector V=zc.getMacros();
for (i=0; i<V.size(); i++) {
final MacroItem mi=(MacroItem) V.get(i);
if (!(mi.M.isProtected())) {
F.add(V.get(i));
}
}
V.clear();
for (i=0; i<librarymacros.size(); i++) {
zc.appendMacro(((MacroItem) librarymacros.get(i)).M);
}
for (i=0; i<F.size(); i++) {
zc.appendMacro(((MacroItem) F.get(i)).M);
}
}
}
}

583
eric/macros/MacrosList.java Normal file
View file

@ -0,0 +1,583 @@
/*
Copyright 2006 Eric Hakenholz
This file is part of C.a.R. software.
C.a.R. is a free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
C.a.R. 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eric.macros;
import eric.GUI.themes;
import eric.JGeneralMenuBar;
import eric.JZirkelCanvas;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenu;
import eric.JEricPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import rene.gui.Global;
import rene.gui.MyMenu;
import rene.zirkel.ZirkelFrame;
import rene.zirkel.macro.Macro;
import rene.zirkel.macro.MacroItem;
// Toute ce qui touche à l'arbre de macros et à sa gestion :
public class MacrosList extends JEricPanel {
private final int CONTROLHEIGHT=25;
private final ImageIcon JTreefoldclosed;
private final ImageIcon JTreefoldopened;
private final ImageIcon[] JTreeleaf;
private CTree MacrosTree;
private JDefaultMutableTreeNode MacroTreeTopNode=new JDefaultMutableTreeNode("Macros");
private ZirkelFrame ZF;
private JScrollPane jscrolls;
private JControls controls;
// private Jcreatemacro createmacropanel;
public MacrosList(ZirkelFrame zf) {
ZF=zf;
JTreefoldclosed=themes.getIcon("JTreefoldclosed.gif");
JTreefoldopened=themes.getIcon("JTreefoldopened.gif");
JTreeleaf=new ImageIcon[4];
JTreeleaf[0]=themes.getIcon("JTreeleaf_0.gif");
JTreeleaf[1]=themes.getIcon("JTreeleaf_1.gif");
JTreeleaf[2]=themes.getIcon("JTreeleaf_2.gif");
JTreeleaf[3]=themes.getIcon("JTreeleaf_3.gif");
this.setLayout(new javax.swing.BoxLayout(this,
javax.swing.BoxLayout.Y_AXIS));
// uncomment this line to obtain gray conection lines between leaves :
// UIManager.put("Tree.hash",new ColorUIResource(Color.lightGray));
MacroTreeTopNode=new JDefaultMutableTreeNode("Macros");
MacrosTree=new CTree(this) {
/**
*
*/
@Override
public void paint(final Graphics g) {
final ImageIcon backimage=themes.getIcon("macrospanelback.gif");
g.drawImage(backimage.getImage(), 0, 0, this.getSize().width,
backimage.getIconHeight(), this);
super.paint(g);
}
};
MacrosTree.setFocusable(false);
MacrosTree.setModel(new MyTreeModel(MacroTreeTopNode));
MacrosTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
final MyCellRenderer renderer=new MyCellRenderer();
MacrosTree.setCellRenderer(renderer);
MacrosTree.setCellEditor(new MyDefaultCellEditor());
MacrosTree.setOpaque(false);
MacrosTree.setFont(new Font(Global.GlobalFont, 0, 12));
MacrosTree.setForeground(new Color(70, 70, 70));
MacrosTree.setDragEnabled(false);
MacrosTree.setEditable(false);
jscrolls=new JScrollPane(MacrosTree);
jscrolls.setAlignmentX(0F);
jscrolls.setBorder(BorderFactory.createEmptyBorder());
this.add(jscrolls);
controls=new JControls(this);
this.add(controls);
// createmacropanel=new Jcreatemacro(this);
// this.add(createmacropanel);
}
public JDefaultMutableTreeNode getTopNode() {
return MacroTreeTopNode;
}
public CTree getMacrosTree() {
return MacrosTree;
}
// Utilise le Vector de macros pour initialiser l'arbre :
public void initTreeFromZCMacros() {
Vector mc;
// JMacrosTools.setDefaultMacros();
MacroTreeTopNode.removeAllChildren();
// removeAll();
// MacroTreeTopNode=new JDefaultMutableTreeNode("Macros");
mc=ZF.ZC.getMacros();
for (int i=0; i<mc.size(); i++) {
// if (((MacroItem) mc.elementAt(i)).M!=null) {
Macro m=((MacroItem) mc.elementAt(i)).M;
if ((ZF.ZC.isLibraryMacrosVisible())||(!m.isProtected())) {
AddMacroToTree(m);
}
// AddMacroToTree(((MacroItem) mc.elementAt(i)).M);
// }
}
MacrosTree.setModel(new MyTreeModel(MacroTreeTopNode));
MacrosTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
final MyCellRenderer renderer=new MyCellRenderer();
MacrosTree.setCellRenderer(renderer);
MacrosTree.setCellEditor(new MyDefaultCellEditor());
ActualiseMacroPopupMenu();
}
// Only called by LeftPanelContent init method :
public void fixPanelSize(int w, int h) {
fixsize(this, w, h);
fixsize(jscrolls, w, h-CONTROLHEIGHT);
jscrolls.revalidate();
//fixsize(MacrosTree,w,h-CONTROLHEIGHT);
fixsize(controls,w,CONTROLHEIGHT);
controls.revalidate();
}
private static void fixsize(final JComponent cp, final int w, final int h) {
final Dimension d=new Dimension(w, h);
cp.setMaximumSize(d);
cp.setMinimumSize(d);
cp.setPreferredSize(d);
cp.setSize(d);
}
class MyDefaultCellEditor extends DefaultCellEditor {
/**
*
*/
JTextField jtf;
public MyDefaultCellEditor() {
super(new JTextField());
jtf=(JTextField) this.getComponent();
jtf.setFocusTraversalKeysEnabled(false);
jtf.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jtf.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(final KeyEvent e) {
adjust(e.getKeyChar());
}
@Override
public void keyPressed(final KeyEvent e) {
if ((e.getKeyCode()==KeyEvent.VK_ESCAPE)
||(e.getKeyCode()==KeyEvent.VK_TAB)) {
fireEditingStopped();
}
}
});
}
private void adjust(final char ad) {
final FontMetrics fm=getFontMetrics(jtf.getFont());
jtf.setSize(fm.stringWidth(jtf.getText()+ad)+5, jtf.getHeight());
}
@Override
protected void fireEditingCanceled() {
super.fireEditingStopped();
}
@Override
protected void fireEditingStopped() {
super.fireEditingStopped();
}
@Override
public Object getCellEditorValue() {
return super.getCellEditorValue();
}
@Override
public Component getTableCellEditorComponent(final JTable table,
final Object value, final boolean isSelected, final int row,
final int column) {
return super.getTableCellEditorComponent(table, value, isSelected,
row, column);
}
}
public void AddMacroToTree(final Macro m) {
if (m.getName().startsWith("@builtin@")) {
return;
}
String[] mypath;
mypath=m.getName().split("/");
JDefaultMutableTreeNode mother=MacroTreeTopNode;
for (int i=0; i<mypath.length-1; i++) {
mother=getFolder(mother, mypath[i]);
}
final JDefaultMutableTreeNode node=new JDefaultMutableTreeNode(ZF, m);
mother.add(node);
}
private JDefaultMutableTreeNode getFolder(
final JDefaultMutableTreeNode father, final String name) {
for (int i=0; i<father.getChildCount(); i++) {
if (name.equals((String) ((JDefaultMutableTreeNode) father.getChildAt(i)).getUserObject())) {
return ((JDefaultMutableTreeNode) father.getChildAt(i));
}
}
final JDefaultMutableTreeNode node=new JDefaultMutableTreeNode(name);
father.add(node);
return node;
}
// Actualisation du PopupMenu de macro, du menu principal "Macros", et du vector librarymacros
// Appelée à chaque modification de l'arbre (Drag and Drop, Rename, ...)
// appelée aussi à la fin de initMacrosTreeFromPopup :
public void ActualiseMacroPopupMenu() {
final MyMenu pm=new MyMenu("root");
final JMenu jm=new JMenu("root");
if (MacroTreeTopNode.getChildCount()>0) {
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
ParseMacroTree(pm, jm, MacroTreeTopNode, "root");
ZF.ZC.PM.removeAll();
JGeneralMenuBar.s_InitMacrosMenu();
final JMenu jmroot=(JMenu) jm.getItem(0);
final MyMenu pmroot=(MyMenu) pm.getItem(0);
while (pmroot.getItemCount()>0) {
ZF.ZC.PM.add(pmroot.getItem(0));
JGeneralMenuBar.addMacrosMenu(jmroot.getItem(0));
// if (ZF.ZC.isLibraryMacrosVisible()) {
// ZF.ZC.PM.add(pmroot.getItem(0));
// JGeneralMenuBar.addMacrosMenu(jmroot.getItem(0));
// } else {
// pmroot.remove(0);
// jmroot.remove(0);
//
// }
}
} else {
ZF.ZC.PM.removeAll();
JGeneralMenuBar.s_InitMacrosMenu();
}
MacroTools.updateLibraryMacros();
}
// Procédure recursive appelée uniquement par ActualiseMacroPopupMenu.
// Parcours de l'arbre de macros :
private void ParseMacroTree(final MyMenu PMmenu, final JMenu JMmenu,
final JDefaultMutableTreeNode node, final String path) {
final String mypath=path;
if (!(node.isLeaf())) {
final MyMenu mymenu=new MyMenu((String) node.getUserObject());
final JMenu myjmenu=new JMenu((String) node.getUserObject());
myjmenu.setFont(new java.awt.Font("System", 0, 13));
for (int i=0; i<node.getChildCount(); i++) {
ParseMacroTree(mymenu, myjmenu, (JDefaultMutableTreeNode) node.getChildAt(i), mypath+"/"+mymenu.getLabel());
}
PMmenu.add(mymenu);
JMmenu.add(myjmenu);
} else {
final String myname=(String) node.getUserObject();
if (!(myname.startsWith("-- "))) {
node.ActualisePath();
PMmenu.add(node.PMmenuitem);
JMmenu.add(node.MainMenuItem);
} else {
if (node.getParent().getChildCount()>1) {
((DefaultTreeModel) MacrosTree.getModel()).removeNodeFromParent(node);
}
}
}
}
// Les noeuds de l'arbre sont considérés comme des JLabels
// Cette classe se charge de leurs look :
class MyCellRenderer extends JLabel implements TreeCellRenderer {
/**
*
*/
public MyCellRenderer() {
setOpaque(false);
setBackground(null);
}
public Component getTreeCellRendererComponent(final JTree tree,
final Object value, final boolean sel, final boolean expanded,
final boolean leaf, final int row, final boolean hasFocus) {
final String stringValue=tree.convertValueToText(value, sel,
expanded, leaf, row, hasFocus);
setText(stringValue);
setEnabled(tree.isEnabled());
setFont(tree.getFont());
setForeground(Color.black);
setOpaque(sel);
// Couleur de sélection :
setBackground(Color.lightGray);
final JDefaultMutableTreeNode mynode=(JDefaultMutableTreeNode) value;
if (leaf) {
setIcon((stringValue.startsWith(("-- ")))?null
:JTreeleaf[mynode.macrotype]);
if (mynode.macrotype==0) {
setForeground(new Color(68, 84, 131));
}
} else {
setIcon((expanded)?JTreefoldopened:JTreefoldclosed);
}
return this;
}
}
// Le modèle sur lequel est basé l'arbre
// Se charge de l'édition des noeuds et contient les TreeModelListeners :
class MyTreeModel extends DefaultTreeModel implements TreeModelListener {
/**
*
*/
public MyTreeModel(final TreeNode node) {
super(node);
this.addTreeModelListener(this);
}
@Override
public void valueForPathChanged(final TreePath path,
final Object newValue) {
final JDefaultMutableTreeNode tn=(JDefaultMutableTreeNode) path.getLastPathComponent();
super.valueForPathChanged(path, newValue);
tn.ActualisePath();
}
public void treeNodesChanged(final TreeModelEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ActualiseMacroPopupMenu();
}
});
}
public void treeNodesInserted(final TreeModelEvent e) {
// System.out.println("treeNodesInserted");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ActualiseMacroPopupMenu();
}
});
}
public void treeNodesRemoved(final TreeModelEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ActualiseMacroPopupMenu();
}
});
}
public void treeStructureChanged(final TreeModelEvent e) {
// System.out.println("treeStructureChanged");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ActualiseMacroPopupMenu();
}
});
}
}
/**************************************************************************************
*** N'oublions pas que JMacrosList est un JPanel qui contient d'autres
* JPanels La class Jcontrols contient les boutons d'édition de l'arbre et
* leurs listeners
***************************************************************************************/
class JControls extends JEricPanel {
/**
*
*/
private JButton addbtn;
private JButton delbtn;
private JButton renbtn;
private JButton createbtn;
private String message="";
private MacrosList MI;
@Override
public void paintComponent(final java.awt.Graphics g) {
super.paintComponent(g);
final java.awt.Dimension d=this.getSize();
g.drawImage(themes.getImage("tab_bottom.gif"), 0, 0, d.width,
d.height, this);
}
public void setButtonsIcons() {
addbtn.setIcon(themes.getIcon("addmacrofolder.png"));
addbtn.setRolloverIcon(themes.getIcon("addmacrofoldersel.png"));
delbtn.setIcon(themes.getIcon("delmacro.png"));
delbtn.setToolTipText(Global.Loc("macros.deleteselected"));
renbtn.setIcon(themes.getIcon("renamemacro.png"));
renbtn.setRolloverIcon(themes.getIcon("renamemacrosel.png"));
createbtn.setIcon(themes.getIcon("createmacro.png"));
createbtn.setRolloverIcon(themes.getIcon("createmacroover.png"));
}
public JControls(MacrosList mi) {
MI=mi;
this.setLayout(new javax.swing.BoxLayout(this,
javax.swing.BoxLayout.X_AXIS));
this.setAlignmentX(0F);
addbtn=new JButton();
addbtn.setToolTipText(Global.Loc("macros.addfolder"));
addbtn.setOpaque(false);
addbtn.setContentAreaFilled(false);
addbtn.setBorder(BorderFactory.createEmptyBorder());
addbtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
MacrosTree.nodepopup.addfolder();
}
});
delbtn=new JButton();
delbtn.setOpaque(false);
delbtn.setContentAreaFilled(false);
delbtn.setBorder(BorderFactory.createEmptyBorder());
delbtn.setRolloverIcon(themes.getIcon("delmacrosel.png"));
delbtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
// MacrosTree.nodepopup.deletenodes();
System.out.println("size="+JZirkelCanvas.getCurrentZC().getMacros().size());
}
});
renbtn=new JButton();
renbtn.setToolTipText(Global.Loc("macros.renamemacro"));
renbtn.setOpaque(false);
renbtn.setContentAreaFilled(false);
renbtn.setBorder(BorderFactory.createEmptyBorder());
renbtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
MacrosTree.nodepopup.renamenode();
}
});
createbtn=new JButton();
createbtn.setToolTipText(Global.Loc("macros.recordmacro"));
createbtn.setSelectedIcon(themes.getIcon("createmacrosel.png"));
createbtn.setBorder(BorderFactory.createEmptyBorder());
createbtn.setOpaque(false);
createbtn.setContentAreaFilled(false);
createbtn.setSelected(false);
setButtonsIcons();
createbtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(final MouseEvent e) {
// if (createbtn.isSelected()) {
// message=createmacropanel.getComment().getText();
// createmacropanel.getComment().setText(Global.Loc("macros.cancel"));
// }
}
@Override
public void mouseExited(final MouseEvent e) {
// if (createbtn.isSelected()) {
// if (message!="") {
// createmacropanel.getComment().setText(message);
// }
// }
}
@Override
public void mousePressed(final MouseEvent e) {
if (createbtn.isSelected()) {
createbtn.setSelected(false);
// createmacropanel.disappeargently();
// PaletteManager.setSelected("point", true);
} else {
createbtn.setSelected(true);
new CreateMacroDialog(MI);
// createmacropanel.appeargently();
// PaletteManager.deselectgeomgroup();
}
}
});
final JEricPanel spacer=new JEricPanel();
spacer.setOpaque(false);
this.add(addbtn);
this.add(delbtn);
this.add(renbtn);
this.add(spacer);
this.add(createbtn);
}
}
}

View file

@ -0,0 +1,428 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eric.macros;
import eric.FileTools;
import eric.GUI.palette.PaletteManager;
import eric.JZirkelCanvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.plaf.SeparatorUI;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import rene.gui.Global;
import rene.zirkel.ZirkelCanvas;
import rene.zirkel.macro.Macro;
import rene.zirkel.macro.MacroItem;
/**
*
* @author erichake
*/
public class NodePopupMenu extends JPopupMenu {
private final CTree macrostree;
private JDefaultMutableTreeNode SelectedNode;
private TreePath[] SelectedPath;
private JMenuItem runitem, renitem, delitem, tolibitem, tofileitem, saveitem, updtitem, propitem, dupitem;
public NodePopupMenu(CTree mytree) {
macrostree=mytree;
dupitem=new JMenuItem(Global.Loc("macros.popup.duplicate"));
dupitem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
duplicatenodes();
}
});
propitem=new JMenuItem(Global.Loc("macros.popup.properties"));
propitem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
showproperties();
}
});
runitem=new JMenuItem(Global.Loc("macros.popup.run"));
runitem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
// runmacro();
}
});
renitem=new JMenuItem(Global.Loc("macros.popup.rename"));
renitem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
renamenode();
}
});
delitem=new JMenuItem(Global.Loc("macros.popup.delete"));
delitem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
deletenodes();
}
});
tolibitem=new JMenuItem(Global.Loc("macros.popup.addtolibrary"));
tolibitem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
changeMacroType(0);
}
});
tofileitem=new JMenuItem(Global.Loc("macros.popup.removefromlibrary"));
tofileitem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
changeMacroType(2);
}
});
saveitem=new JMenuItem(Global.Loc("macros.popup.saveas"));
saveitem.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent event) {
saveMacros();
}
});
}
public void handleMouseClick(final MouseEvent e) {
final TreePath path=macrostree.getPathForLocation(e.getX(), e.getY());
if (path!=null) {
SelectedNode=(JDefaultMutableTreeNode) path.getLastPathComponent();
SelectedPath=macrostree.getSelectionPaths();
if ((SelectedPath.length==1)&&(SelectedNode.isLeaf())) {
if (JMacrosInspector.isDialogVisible()) {
JMacrosInspector.changemacro(SelectedNode);
} else {
PaletteManager.deselectgeomgroup();
SelectedNode.runZmacro();
}
}
}
}
void actualiseproperties() {
// throw new UnsupportedOperationException("Not yet implemented");
}
private void showproperties() {
JMacrosInspector.openInspector(SelectedNode);
// new JMacrosInspector(SelectedNode);
}
public void handlePopup(final MouseEvent e) {
if (e.isPopupTrigger()) {
final TreePath path=macrostree.getPathForLocation(e.getX(), e.getY());
if (path!=null) {
macrostree.addSelectionPath(path);
SelectedNode=(JDefaultMutableTreeNode) path.getLastPathComponent();
SelectedPath=macrostree.getSelectionPaths();
// initSelectedPath();
this.removeAll();
if (SelectedPath.length>1) {
this.add(delitem);
if (!JZirkelCanvas.isRestrictedSession()) {
this.add(createSeparator());
this.add(tolibitem);
this.add(tofileitem);
this.add(createSeparator());
this.add(saveitem);
}
} else {
if (SelectedNode.isLeaf()) {
this.add(renitem);
if (!JZirkelCanvas.isRestrictedSession()) {
this.add(delitem);
this.add(dupitem);
}
this.add(createSeparator());
if (!JZirkelCanvas.isRestrictedSession()) {
this.add(tolibitem);
this.add(tofileitem);
this.add(createSeparator());
this.add(saveitem);
this.add(createSeparator());
}
this.add(runitem);
this.add(createSeparator());
this.add(propitem);
} else {
this.add(renitem);
this.add(delitem);
this.add(createSeparator());
if (!JZirkelCanvas.isRestrictedSession()) {
this.add(tolibitem);
this.add(tofileitem);
this.add(createSeparator());
this.add(saveitem);
}
}
}
this.show(e.getComponent(), e.getX(), e.getY());
}
}
}
public void addfolder() {
JDefaultMutableTreeNode root;
final JDefaultMutableTreeNode node=new JDefaultMutableTreeNode(Global.Loc("macros.untitledfolder"));
node.add(new JDefaultMutableTreeNode(Global.Loc("macros.emptynode")));
final TreePath[] paths=macrostree.getSelectionPaths();
if ((paths)!=null) {
root=(JDefaultMutableTreeNode) paths[0].getLastPathComponent();
if (root.isLeaf()) {
// if the first selected node is a leaf :
final DefaultMutableTreeNode father=(DefaultMutableTreeNode) root.getParent();
final int i=father.getIndex(root)+1;
((DefaultTreeModel) macrostree.getModel()).insertNodeInto(node,
father, i);
} else {
// if the first selected node is a folder :
((DefaultTreeModel) macrostree.getModel()).insertNodeInto(node,
root, root.getChildCount());
}
} else {
// There is no selected node :
((DefaultTreeModel) macrostree.getModel()).insertNodeInto(node,
macrostree.JML.getTopNode(),
macrostree.JML.getTopNode().getChildCount());
}
// Transformation d'un noeud en TreePath :
final TreePath tp=new TreePath(node.getPath());
macrostree.setEditable(true);
macrostree.startEditingAtPath(tp);
}
private void updateMacrosVector(JDefaultMutableTreeNode node) {
if (node.m==null) {
return;
}
String name=node.m.Name;
if (node.m.isProtected()) {
int ZCsSize=JZirkelCanvas.getZCsSize();
// delete the macro from all the ZirkelCanvas (in different tabs) :
for (int size=0; size<ZCsSize; size++) {
Vector V=JZirkelCanvas.getZC(size).getMacros();
for (int i=0; i<V.size(); i++) {
MacroItem mi=(MacroItem) V.get(i);
if (name.equals(mi.M.Name)) {
V.remove(mi);
continue;
}
}
}
// delete the macro from the library :
Vector W=MacroTools.getLibraryMacros();
for (int i=0; i<W.size(); i++) {
MacroItem mi=(MacroItem) W.get(i);
if (name.equals(mi.M.Name)) {
W.remove(mi);
continue;
}
}
} else {
// remove macro from the current ZirkelCanvas :
Vector V=JZirkelCanvas.getCurrentZC().getMacros();
for (int i=0; i<V.size(); i++) {
MacroItem mi=(MacroItem) V.get(i);
if (name.equals(mi.M.Name)) {
V.remove(mi);
return;
}
}
}
}
private void parse_deletenodes(JDefaultMutableTreeNode node) {
if (!(node.isLeaf())) {
for (int i=0; i<node.getChildCount(); i++) {
parse_deletenodes((JDefaultMutableTreeNode) node.getChildAt(i));
}
} else {
updateMacrosVector(node);
}
}
public void deletenodes() {
final TreePath[] paths=macrostree.getSelectionPaths();
if ((paths)!=null) {
final Object[] options={"Ok", "Cancel"};
final int rep=JOptionPane.showOptionDialog(null, Global.Loc("macros.question.delete"), "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
if (rep==0) {
for (final TreePath path : paths) {
final JDefaultMutableTreeNode node=(JDefaultMutableTreeNode) path.getLastPathComponent();
parse_deletenodes(node);
JDefaultMutableTreeNode father=(JDefaultMutableTreeNode) node.getParent();
((DefaultTreeModel) macrostree.getModel()).removeNodeFromParent(node);
while (father.getChildCount()==0) {
final JDefaultMutableTreeNode grandfather=(JDefaultMutableTreeNode) father.getParent();
((DefaultTreeModel) macrostree.getModel()).removeNodeFromParent(father);
father=grandfather;
}
}
}
}
}
public static String uniqueMacroName(String base) {
ZirkelCanvas zc=JZirkelCanvas.getCurrentZC();
if (zc==null) {
return base;
}
base=base.replaceAll("[\\s0-9]+$", "");
Vector V=zc.getMacros();
int num=0;
loop:
for (int i=0; i<V.size(); i++) {
MacroItem mi=(MacroItem) V.get(i);
if (base.equals(mi.M.Name)) {
num++;
base=base.replaceAll("[\\s0-9]+$", "")+" "+num;
continue loop;
}
}
return base;
}
public void duplicatenodes() {
try {
ZirkelCanvas zc=JZirkelCanvas.getCurrentZC();
// this is a very dirty way to clone a macro :
MacroItem mi=new MacroItem((Macro) SelectedNode.m.clone(), null);
final String[] mytab=mi.M.Name.split("/");
mi.M.setName(uniqueMacroName(mytab[mytab.length-1]));
final Vector ZFMacros=new Vector();
ZFMacros.add(mi);
final ByteArrayOutputStream out=new ByteArrayOutputStream();
zc.save(out, false, true, true, false, ZFMacros, "");
zc.load(new ByteArrayInputStream(out.toByteArray()), false, true);
JZirkelCanvas.ActualiseMacroPanel();
} catch (Exception e) {
}
}
public void renamenode() {
final TreePath[] paths=macrostree.getSelectionPaths();
if ((paths)!=null) {
macrostree.setEditable(true);
macrostree.startEditingAtPath(paths[0]);
}
}
private void changeMacroType(final int newtype) {
for (final TreePath element : SelectedPath) {
SelectedNode=(JDefaultMutableTreeNode) element.getLastPathComponent();
parse_changeMacroType(SelectedNode, newtype);
}
macrostree.repaint();
MacroTools.updateLibraryMacros();
MacroTools.populateMacrosTypeChanges();
}
private void parse_changeMacroType(final JDefaultMutableTreeNode node, final int newtype) {
if (node.isLeaf()) {
node.setType(newtype);
} else {
for (int i=0; i<node.getChildCount(); i++) {
parse_changeMacroType((JDefaultMutableTreeNode) node.getChildAt(i), newtype);
}
}
}
private void saveMacros() {
Vector ZFMacros;
ZFMacros=new Vector();
for (final TreePath element : SelectedPath) {
SelectedNode=(JDefaultMutableTreeNode) element.getLastPathComponent();
parse_saveMacros(SelectedNode, ZFMacros);
}
String filename=FileTools.getSaveFile(false);
if (filename!=null) {
final String ext=(filename.endsWith(".mcr"))?"":".mcr";
JZirkelCanvas.getCurrentZF().dosave(filename+ext, false, true, true, false, ZFMacros);
}
}
private void parse_saveMacros(final JDefaultMutableTreeNode node,
final Vector ZFMacros) {
if (node.isLeaf()) {
final MacroItem mi=new MacroItem(node.m, null);
ZFMacros.add(mi);
} else {
for (int i=0; i<node.getChildCount(); i++) {
parse_saveMacros((JDefaultMutableTreeNode) node.getChildAt(i),
ZFMacros);
}
}
}
private static final JSeparator createSeparator() {
final JSeparator jsep=new JSeparator(JSeparator.HORIZONTAL);
final Dimension d=new Dimension(200, 12);
jsep.setMaximumSize(d);
jsep.setMinimumSize(d);
jsep.setPreferredSize(d);
jsep.setSize(d);
jsep.setUI(new MiddleSeparatorUI());
return jsep;
}
private static final class MiddleSeparatorUI extends SeparatorUI {
@Override
public void paint(final Graphics g, final JComponent c) {
final Dimension s=c.getSize();
final int middleHeight=(s.height-1)/2;
g.setColor(Color.lightGray);
g.drawLine(0, middleHeight, s.width, middleHeight);
g.setColor(Color.white);
g.drawLine(0, middleHeight+1, s.width, middleHeight+1);
}
}
}

View file

@ -0,0 +1,14 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eric.macros;
/**
*
* @author erichake
*/
public interface TopDialog {
public void exit();
}