file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
GraphicsInterface.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/GraphicsInterface.java
package net.sourceforge.fidocadj.graphic; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.layers.LayerDesc; /** Provides a general way to draw on the screen. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 by Davide Bucci </pre> */ public interface GraphicsInterface { /** Get the current color. @return the current color. */ ColorInterface getColor(); /** Set the current zoom factor. Currently employed for resizing the dash styles. @param z the current zoom factor (pixels for logical units). */ void setZoom(double z); /** Get the current zoom factor. Currently employed for resizing the dash styles. @return the current zoom factor (pixels for logical units). */ double getZoom(); /** Set the current color. @param c the current color. */ void setColor(ColorInterface c); /** Retrieves an object implementing an appropriate TextInterface. @return an object implementing TextInterface. */ TextInterface getTextInterface(); /** Retrieves or create a BasicStroke object having the wanted with and style and apply it to the current graphic context. @param w the width in pixel @param dashStyle the style of the stroke */ void applyStroke(float w, int dashStyle); /** Draws a rectangle on the current graphic context. @param x the x coordinate of the uppermost left corner @param y the y coordinate of the uppermost left corner @param width the width of the rectangle @param height the height of the rectangle */ void drawRect(int x, int y, int width, int height); /** Fill a rectangle on the current graphic context. @param x the x coordinate of the uppermost left corner @param y the y coordinate of the uppermost left corner @param width the width of the rectangle @param height the height of the rectangle */ void fillRect(int x, int y, int width, int height); /** Fill a rounded rectangle on the current graphic context. @param x the x coordinate of the uppermost left corner. @param y the y coordinate of the uppermost left corner. @param width the width of the rectangle. @param height the height of the rectangle. @param arcWidth the width of the arc of the round corners. @param arcHeight the height of the arc of the round corners. */ void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight); /** Check whether the rectangle specified falls in a region which need to be updated because it is "dirty" on the screen. Implementing correctly this method is very important to achieve a good redrawing speed because only "dirty" regions on the screen will be actually redrawn. @param x the x coordinate of the uppermost left corner of rectangle. @param y the y coordinate of the uppermost left corner of rectangle. @param width the width of the rectangle of the rectangle. @param height the height of the rectangle of the rectangle. @return true if the rectangle hits the dirty region. */ boolean hitClip(int x, int y, int width, int height); /** Draw a segment between two points @param x1 first coordinate x value @param y1 first coordinate y value @param x2 second coordinate x value @param y2 second coordinate y value */ void drawLine(int x1, int y1, int x2, int y2); /** Set the current font for drawing text. @param name the name of the typeface to be used. @param size the size in pixels */ void setFont(String name, double size); /** Set the current font. @param name the name of the typeface. @param size the vertical size in pixels. @param isItalic true if an italic variant should be used. @param isBold true if a bold variant should be used. */ void setFont(String name, double size, boolean isItalic, boolean isBold); /** Get the font size. @return the font size. */ double getFontSize(); /** Set the font size. @param size the font size to be set. */ void setFontSize(double size); /** Get the ascent metric of the current font. @return the value of the ascent, in pixels. */ int getFontAscent(); /** Get the descent metric of the current font. @return the value of the descent, in pixels. */ int getFontDescent(); /** Get the width of the given string with the current font. @param s the string to be used. @return the width of the string, in pixels. */ int getStringWidth(String s); /** Draw a string on the current graphic context. @param str the string to be drawn. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. */ void drawString(String str, int x, int y); /** Set the transparency (alpha) of the current color. @param alpha the transparency, between 0.0 (transparent) and 1.0 (fully opaque). */ void setAlpha(float alpha); /** Draw a completely filled oval in the current graphic context. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. @param width the width of the oval. @param height the height of the oval. */ void fillOval(int x, int y, int width, int height); /** Draw an enmpty oval in the current graphic context. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. @param width the width of the oval. @param height the height of the oval. */ void drawOval(int x, int y, int width, int height); /** Fill a given shape. @param s the shape to be filled. */ void fill(ShapeInterface s); /** Draw a given shape. @param s the shape to be drawn. */ void draw(ShapeInterface s); /** Fill a given polygon. @param p the polygon to be filled. */ void fillPolygon(PolygonInterface p); /** Draw a given polygon. @param p the polygon to be drawn. */ void drawPolygon(PolygonInterface p); /** Select the selection color (normally, green) for the current graphic context. @param l the layer whose color should be blended with the selection color (green). */ void activateSelectColor(LayerDesc l); /** Draw a string by allowing for a certain degree of flexibility in specifying how the text will be handled. @param xyfactor the text font is specified by giving its height in the setFont() method. If the text should be stretched (i.e. its width should be modified), this parameter gives the amount of stretching. @param xa the x coordinate of the point where the text will be placed. @param ya the y coordinate of the point where the rotation is calculated. @param qq the y coordinate of the point where the text will be placed. @param h the height of the text, in pixels. @param w the width of the string, in pixels. @param th the total height of the text (ascent+descents). @param needsStretching true if some stretching is needed. @param orientation orientation in degrees of the text. @param mirror true if the text is mirrored. @param txt the string to be drawn. */ void drawAdvText(double xyfactor, int xa, int ya, int qq, int h, int w, int th, boolean needsStretching, int orientation, boolean mirror, String txt); /** Draw the grid in the given graphic context. @param cs the coordinate map description. @param xmin the x (screen) coordinate of the upper left corner. @param ymin the y (screen) coordinate of the upper left corner. @param xmax the x (screen) coordinate of the bottom right corner. @param ymax the y (screen) coordinate of the bottom right corner. */ void drawGrid(MapCoordinates cs, int xmin, int ymin, int xmax, int ymax); /** Create a polygon object, compatible with the current implementation. @return a polygon object. */ PolygonInterface createPolygon(); /** Create a color object, compatible with the current implementation. @return a color object. */ ColorInterface createColor(); /** Create a shape object, compatible with the current implementation. @return a shape object. */ ShapeInterface createShape(); /** Retrieve the current screen density in dots-per-inch. @return the screen resolution (density) in dots-per-inch. */ float getScreenDensity(); }
10,254
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
RectangleG.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/RectangleG.java
package net.sourceforge.fidocadj.graphic; /** RectangleG is a class implementing a rectangle with its coordinates (integer). <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2015 by Davide Bucci </pre> */ public class RectangleG { public int x; public int y; public int height; public int width; /** Standard constructor of the rectangle. @param x the x coordinates of the leftmost side. @param y the y coordinates of the topmost side. @param width the width of the rectangle. @param height the height of the rectangle. */ public RectangleG(int x, int y, int width, int height) { this.x=x; this.y=y; this.width=width; this.height=height; } /** Standard constructor. All the coordinates and sizes are put equal to zero. */ public RectangleG() { this.x=0; this.y=0; this.width=0; this.height=0; } }
1,660
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PolygonInterface.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/PolygonInterface.java
package net.sourceforge.fidocadj.graphic; /** PolygonInterface specifies methods for handling a polygon. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 by Davide Bucci </pre> */ public interface PolygonInterface { /** Add a point to the current polygon. @param x the x coordinate of the point. @param y the y coordinate of the point. */ void addPoint(int x, int y); /** Get the current number of points in the polygon. @return the number of points. */ int getNpoints(); /** Reset the current polygon by deleting all the points. */ void reset(); /** Get a vector containing the x coordinates of the points. @return a vector containing the x coordinates of all points. */ int[] getXpoints(); /** Get a vector containing the y coordinates of the points. @return a vector containing the y coordinates of all points. */ int[] getYpoints(); /** Check if a given point is contained inside the polygon. @param x the x coordinate of the point to be checked. @param y the y coordinate of the point to be checked. @return true of the point is internal to the polygon, false otherwise. */ boolean contains(int x, int y); }
1,956
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PointG.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/PointG.java
package net.sourceforge.fidocadj.graphic; /** PointG is a class implementing a point with its coordinates (integer). P.S. why are you smirking? <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2015 by Davide Bucci </pre> */ public class PointG { public int x; public int y; /** Standard constructor. @param x the x coordinate of the point. @param y the y coordinate of the point. */ public PointG(int x, int y) { this.x=x; this.y=y; } /** Standard constructor. The x and y coordinates are put equal to zero. */ public PointG() { this.x=0; this.y=0; } }
1,352
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/nil/package-info.java
/** Draw on nothing (nil), just to calculate image size: this is not so simple with text primitives... */ package net.sourceforge.fidocadj.graphic.nil;
157
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PolygonNull.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/nil/PolygonNull.java
package net.sourceforge.fidocadj.graphic.nil; import android.graphics.*; import java.util.Vector; import net.sourceforge.fidocadj.graphic.*; /** ANDROID VERSION PolygonInterface specifies methods for handling a polygon. TODO: reduce dependency on java.awt.*; <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Davide Bucci </pre> */ public class PolygonNull implements PolygonInterface { private Path path; private int npoints; Vector<Integer> xpoints; Vector<Integer> ypoints; /** Get a Path element containing the polygon. @return the Path object. */ public Path getPath() { return path; } /** Close the current polygon. */ public void close() { path.close(); } /** Constructor */ public PolygonNull() { path=new Path(); npoints=0; xpoints = new Vector<Integer>(); ypoints = new Vector<Integer>(); } /** Add a point to the current polygon. @param x the x coordinate of the point. @param y the y coordinate of the point. */ public void addPoint(int x, int y) { if(npoints++==0) path.moveTo(x, y); else path.lineTo(x, y); xpoints.add(x); ypoints.add(y); } /** Reset the current polygon by deleting all the points. */ public void reset() { path.reset(); npoints=0; xpoints.clear(); ypoints.clear(); } /** Get the current number of points in the polygon. @return the number of points. */ public int getNpoints() { return npoints; } /** Get a vector containing the x coordinates of the points. @return a vector containing the x coordinates of all points. */ public int[] getXpoints() { // ☠ Something better??? ☠ int[] xvector= new int[npoints]; int k=0; for(Integer v : xpoints) xvector[k++]=v; return xvector; } /** Get a vector containing the y coordinates of the points. @return a vector containing the y coordinates of all points. */ public int[] getYpoints() { // ☠ Something better??? ☠ int[] yvector= new int[npoints]; int k=0; for(Integer v : ypoints) yvector[k++]=v; return yvector; } /** Check if a given point is contained inside the polygon. @param x the x coordinate of the point to be checked. @param y the y coordinate of the point to be checked. @return true of the point is internal to the polygon, false otherwise. */ public boolean contains(int x, int y) { RectF rectF = new RectF(); path.computeBounds(rectF, true); Region r = new Region(); r.setPath(path, new Region((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom)); return r.contains(x,y); } }
3,665
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ShapeNull.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/nil/ShapeNull.java
package net.sourceforge.fidocadj.graphic.nil; import android.graphics.*; import net.sourceforge.fidocadj.graphic.*; /** ANDROID VERSION ShapeNull is a wrapper around the Shape Swing class. TODO: reduce dependency on java.awt.*; <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Davide Bucci </pre> */ public class ShapeNull implements ShapeInterface { Path path; /** Obtain a Path object describing this shape. @return the Path object. */ public Path getPath() { return path; } /** Constructor. */ public ShapeNull() { path = new Path(); } /** Create a cubic curve (Bézier). @param x0 the x coord. of the starting point of the Bézier curve. @param y0 the y coord. of the starting point of the Bézier curve. @param x1 the x coord. of the first handle. @param y1 the y coord. of the first handle. @param x2 the x coord. of the second handle. @param y2 the y coord. of the second handle. @param x3 the x coord. of the ending point of the Bézier curve. @param y3 the y coord. of the ending point of the Bézier curve. */ public void createCubicCurve(int x0, int y0, int x1, int y1, int x2, int y2, int x3, int y3) { path.reset(); path.moveTo(x0,y0); path.cubicTo (x1, y1, x2, y2, x3, y3); } /** Create a general path with the given number of points. @param npoints the number of points. */ public void createGeneralPath(int npoints) { path.reset(); } /** Obtain the bounding box of the curve. @return the bounding box. */ public RectangleG getBounds() { return new RectangleG(0,0,0,0); } /** Move the current position to the given coordinates. @param x the x coordinate. @param y the y coordinate. */ public void moveTo(float x, float y) { path.moveTo(x, y); } /** Add a cubic curve from the current point. @param x0 the x coord. of the first handle. @param y0 the y coord. of the first handle @param x1 the x coord. of the second handle. @param y1 the y coord. of the second handle. @param x2 the x coord. of the ending point of the Bézier curve. @param y2 the y coord. of the ending point of the Bézier curve. */ public void curveTo(float x0, float y0, float x1, float y1, float x2, float y2) { path.cubicTo (x0, y0, x1, y1, x2, y2); } /** Close the current path. */ public void closePath() { path.close(); } }
3,307
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
GraphicsNull.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/nil/GraphicsNull.java
package net.sourceforge.fidocadj.graphic.nil; import net.sourceforge.fidocadj.graphic.*; import net.sourceforge.fidocadj.geom.*; import net.sourceforge.fidocadj.layers.*; import android.graphics.*; import android.graphics.Paint.*; /** ANDROID VERSION Null graphic class. Does nothing. Nil. Zero. :-) Except... calculate text size correctly! Yes. There is a reason for that. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Davide Bucci </pre> */ public class GraphicsNull implements GraphicsInterface { Paint paint; /** Constructor. */ public GraphicsNull() { paint = new Paint(); } /** Set the current zoom factor. Currently employed for resizing the dash styles. @param z the current zoom factor (pixels for logical units). */ public void setZoom(double z) { // Nothing to do } /** Set the current color. @param c the current color. */ public void setColor(ColorInterface c) { // Nothing to do } /** Get the current color. @return the current color. */ public ColorInterface getColor() { return new ColorNull(); } /** Retrieves or create a BasicStroke object having the wanted with and style and apply it to the current graphic context. @param w the width in pixel @param dashStyle the style of the stroke */ public void applyStroke(float w, int dashStyle) { // Nothing to do } /** Draws a rectangle on the current graphic context. @param x the x coordinate of the uppermost left corner @param y the y coordinate of the uppermost left corner @param width the width of the rectangle @param height the height of the rectangle */ public void drawRect(int x, int y, int width, int height) { // Nothing to do } /** Fills a rectangle on the current graphic context. @param x the x coordinate of the uppermost left corner @param y the y coordinate of the uppermost left corner @param width the width of the rectangle @param height the height of the rectangle */ public void fillRect(int x, int y, int width, int height) { // Nothing to do } /** Fill a rounded rectangle on the current graphic context. @param x the x coordinate of the uppermost left corner. @param y the y coordinate of the uppermost left corner. @param width the width of the rectangle. @param height the height of the rectangle. @param arcWidth the width of the arc of the round corners. @param arcHeight the height of the arc of the round corners. */ public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { // Nothing to do } /** Check whether the rectangle specified falls in a region which need to be updated because it is "dirty" on the screen. Implementing correctly this method is very important to achieve a good redrawing speed because only "dirty" regions on the screen will be actually redrawn. @param x the x coordinate of the uppermost left corner of rectangle. @param y the y coordinate of the uppermost left corner of rectangle. @param width the width of the rectangle of the rectangle. @param height the height of the rectangle of the rectangle. @return true if the rectangle hits the dirty region. */ public boolean hitClip(int x, int y, int width, int height) { return true; } /** Draw a segment between two points @param x1 first coordinate x value @param y1 first coordinate y value @param x2 second coordinate x value @param y2 second coordinate y value */ public void drawLine(int x1, int y1, int x2, int y2) { // Nothing to do } /** Set the current font. @param name the name of the typeface. @param size the vertical size in pixels. @param isItalic true if an italic variant should be used. @param isBold true if a bold variant should be used. */ public void setFont(String name, double size, boolean isItalic, boolean isBold) { int style; if(isBold && isItalic) style=Typeface.BOLD_ITALIC; else if (isBold) style=Typeface.BOLD; else if (isItalic) style=Typeface.ITALIC; else style=Typeface.NORMAL; Typeface tf = Typeface.create(name, style); paint.setTypeface(tf); paint.setTextSize((int)Math.round(size)); } /** Set the current font for drawing text. @param name the name of the typeface to be used. @param size the size in pixels */ public void setFont(String name, double size) { setFont(name, size, false, false); } /** Get the ascent metric of the current font. @return the value of the ascent, in pixels. */ public int getFontAscent() { // Note: an ascent is "going up", so it is negative // as in the FontMetrics documentation... // FidoCadJ requires a positive size, instead. return -(int)paint.getFontMetrics().ascent; } /** Get the descent metric of the current font. @return the value of the descent, in pixels. */ public int getFontDescent() { return (int)paint.getFontMetrics().descent; } /** Get the width of the given string with the current font. @param s the string to be used. @return the width of the string, in pixels. */ public int getStringWidth(String s) { return (int)paint.measureText(s); } /** Draw a string on the current graphic context. @param str the string to be drawn. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. */ public void drawString(String str, int x, int y) { // Nothing to do } /** Set the transparency (alpha) of the current color. @param alpha the transparency, between 0.0 (transparent) and 1.0 (fully opaque). */ public void setAlpha(float alpha) { // Nothing to do } /** Draw a completely filled oval in the current graphic context. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. @param width the width of the oval. @param height the height of the oval. */ public void fillOval(int x, int y, int width, int height) { // Nothing to do } /** Draw an enmpty oval in the current graphic context. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. @param width the width of the oval. @param height the height of the oval. */ public void drawOval(int x, int y, int width, int height) { // Nothing to do } /** Fill a given shape. @param s the shape to be filled. */ public void fill(ShapeInterface s) { // Nothing to do } /** Draw a given shape. @param s the shape to be drawn. */ public void draw(ShapeInterface s) { // Nothing to do } /** Fill a given polygon. @param p the polygon to be filled. */ public void fillPolygon(PolygonInterface p) { // Nothing to do } /** Draw a given polygon. @param p the polygon to be drawn. */ public void drawPolygon(PolygonInterface p) { // Nothing to do } /** Select the selection color (normally, green) for the current graphic context. @param l the layer whose color should be blended with the selection color (green). */ public void activateSelectColor(LayerDesc l) { // Nothing to do } /** Draw a string by allowing for a certain degree of flexibility in specifying how the text will be handled. @param xyfactor the text font is specified by giving its height in the setFont() method. If the text should be stretched (i.e. its width should be modified), this parameter gives the amount of stretching. @param xa the x coordinate of the point where the text will be placed. @param ya the y coordinate of the point where the rotation is calculated. @param qq the y coordinate of the point where the text will be placed. @param h the height of the text, in pixels. @param w the width of the string, in pixels. @param th the total height of the text (ascent+descents). @param needsStretching true if some stretching is needed. @param orientation orientation in degrees of the text. @param mirror true if the text is mirrored. @param txt the string to be drawn. */ public void drawAdvText(double xyfactor, int xa, int ya, int qq, int h, int w, int th, boolean needsStretching, int orientation, boolean mirror, String txt) { // Nothing to do } /** Draw the grid in the given graphic context. @param cs the coordinate map description. @param xmin the x (screen) coordinate of the upper left corner. @param ymin the y (screen) coordinate of the upper left corner. @param xmax the x (screen) coordinate of the bottom right corner. @param ymax the y (screen) coordinate of the bottom right corner. */ public void drawGrid(MapCoordinates cs, int xmin, int ymin, int xmax, int ymax) { // nothing to do } /** Create a polygon object, compatible with the current implementation. @return a polygon object. */ public PolygonInterface createPolygon() { return new PolygonNull(); } /** Create a color object, compatible with the current implementation. @return a color object. */ public ColorInterface createColor() { return new ColorNull(); } /** Create a shape object, compatible with the current implementation. @return a shape object. */ public ShapeInterface createShape() { return new ShapeNull(); } /** Retrieve the current screen density in dots-per-inch. @return the screen resolution (density) in dots-per-inch. */ public float getScreenDensity() { // The magic number should not be important in this context return 42; } }
11,923
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ColorNull.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/nil/ColorNull.java
package net.sourceforge.fidocadj.graphic.nil; import net.sourceforge.fidocadj.graphic.*; /** ANDROID VERSION Null color class. Does nothing :-) <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Davide Bucci </pre> */ public class ColorNull implements ColorInterface { /** Standard constructor */ public ColorNull() { // Does nothing. } /** Get a white color. @return a white color. */ public ColorInterface white() { return new ColorNull(); } /** Get a gray color. @return a gray color. */ public ColorInterface gray() { return new ColorNull(); } /** Get a green color. @return a green color. */ public ColorInterface green() { return new ColorNull(); } /** Get a red color. @return a red color. */ public ColorInterface red() { return new ColorNull(); } /** Get the green component of the color. @return the component. */ public ColorInterface black() { return new ColorNull(); } /** Get the red component of the color. @return the component. */ public int getRed() { return 0; } /** Get the green component of the color. @return the component. */ public int getGreen() { return 0; } /** Get the blue component of the color. @return the component. */ public int getBlue() { return 0; } /** Get the RGB components packed as an integer. @return an integer containing the RGB components. */ public int getRGB() { return 0; } /** Set the color from a RGB description packed in a int. @param rgb the packed description.. */ public void setRGB(int rgb) { // Does nothing. } }
2,538
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/android/package-info.java
/** Android classes for graphic low level drawing operations. */ package net.sourceforge.fidocadj.graphic.android;
114
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ShapeAndroid.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/android/ShapeAndroid.java
package net.sourceforge.fidocadj.graphic.android; import android.graphics.*; import net.sourceforge.fidocadj.graphic.*; /** Shape implementation for Android. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Davide Bucci </pre> */ public class ShapeAndroid implements ShapeInterface { private Path path; /** Get the current Android path object. @return the Android path object. */ public Path getPath() { return path; } /** Standard constructor. */ public ShapeAndroid() { path = new Path(); } /** Create a cubic curve (Bézier). @param x0 the x coord. of the starting point of the Bézier curve. @param y0 the y coord. of the starting point of the Bézier curve. @param x1 the x coord. of the first handle. @param y1 the y coord. of the first handle. @param x2 the x coord. of the second handle. @param y2 the y coord. of the second handle. @param x3 the x coord. of the ending point of the Bézier curve. @param y3 the y coord. of the ending point of the Bézier curve. */ public void createCubicCurve(int x0, int y0, int x1, int y1, int x2, int y2, int x3, int y3) { path.reset(); path.moveTo(x0,y0); path.cubicTo (x1, y1, x2, y2, x3, y3); } /** Create a general path with the given number of points. @param npoints the number of points. */ public void createGeneralPath(int npoints) { path.reset(); } /** Obtain the bounding box of the curve. @return the bounding box. */ public RectangleG getBounds() { RectF bounds = new RectF(); path.computeBounds(bounds, true); return new RectangleG((int)bounds.left,(int)bounds.top, (int)(bounds.right-bounds.left+1), (int)(bounds.bottom-bounds.top+1)); } /** Move the current position to the given coordinates. @param x the x coordinate @param y the y coordinate */ public void moveTo(float x, float y) { path.moveTo(x, y); } /** Add a cubic curve from the current point. @param x0 the x coord. of the first handle. @param y0 the y coord. of the first handle @param x1 the x coord. of the second handle. @param y1 the y coord. of the second handle. @param x2 the x coord. of the ending point of the Bézier curve. @param y2 the y coord. of the ending point of the Bézier curve. */ public void curveTo(float x0, float y0, float x1, float y1, float x2, float y2) { path.cubicTo (x0, y0, x1, y1, x2, y2); } /** Close the current path. */ public void closePath() { path.close(); } }
3,443
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ColorAndroid.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/android/ColorAndroid.java
package net.sourceforge.fidocadj.graphic.android; import android.graphics.*; import net.sourceforge.fidocadj.graphic.*; /** Android color class. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Davide Bucci </pre> */ public class ColorAndroid implements ColorInterface { int c; /** Standard constructor, empty. */ public ColorAndroid() { // Does nothing. } /** Constructor which creates a color from an integer where the RGB bytes are packed. @param c the integer where the color code is packed. */ public ColorAndroid(int c) { this.c=c; } /** Get the color, as an Android integer description. @return the color code as an integer packing the RGB bytes. */ public int getColorAndroid() { return c; } /** The white color. @return the white color. */ public ColorInterface white() { return new ColorAndroid(Color.WHITE); } /** The gray color. @return the gray color. */ public ColorInterface gray() { return new ColorAndroid(Color.GRAY); } /** The green color. @return the green color. */ public ColorInterface green() { return new ColorAndroid(Color.GREEN); } /** The red color. @return the red color. */ public ColorInterface red() { return new ColorAndroid(Color.RED); } /** The black color. @return the black color. */ public ColorInterface black() { return new ColorAndroid(Color.BLACK); } /** The red component. @return the red component. */ public int getRed() { return Color.red(c); } /** The green component. @return the green component. */ public int getGreen() { return Color.green(c); } /** The blue component. @return the blue component. */ public int getBlue() { return Color.blue(c); } /** The RGB components packed in an integer. @return the RGB components. */ public int getRGB() { return c; } /** Set the RGB components, packed in an integer. @param rgb the integer packing the RGB components. */ public void setRGB(int rgb) { c=rgb; } }
3,001
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
GraphicsAndroid.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/android/GraphicsAndroid.java
package net.sourceforge.fidocadj.graphic.android; import android.graphics.*; import android.graphics.Paint.*; import net.sourceforge.fidocadj.graphic.*; import net.sourceforge.fidocadj.geom.*; import net.sourceforge.fidocadj.layers.*; import net.sourceforge.fidocadj.globals.*; /** Android graphic class. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Davide Bucci </pre> */ public class GraphicsAndroid implements GraphicsInterface { private Canvas canvas; private float actual_w; private int actual_dash; private double oldZoom; private Paint gridPaint; // We keep a Style.STROKE paint here Paint paint; // We keep a Style.FILL_AND_STROKE paint here Paint filled_stroke_paint; /** Standard constructor. @param c the canvas where the drawing operations will take place. */ public GraphicsAndroid(Canvas c) { canvas=c; paint = new Paint(); paint.setColor(Color.BLUE); paint.setStyle(Style.STROKE); paint.setStrokeCap(Cap.ROUND); paint.setStrokeJoin(Join.ROUND); paint.setAntiAlias(true); filled_stroke_paint = new Paint(); filled_stroke_paint.setColor(Color.BLUE); filled_stroke_paint.setStyle(Style.FILL_AND_STROKE); filled_stroke_paint.setStrokeCap(Cap.ROUND); filled_stroke_paint.setStrokeJoin(Join.ROUND); filled_stroke_paint.setAntiAlias(true); actual_w=-1.0f; actual_dash = 0; } /** Set the current zoom factor. Currently employed for resizing the dash styles. @param z the current zoom factor (pixels for logical units). */ public void setZoom(double z) { // TODO: implement this. } /** Set the current drawing color. @param c the color to be used. It must be an instance of ColorAndroid in this context. */ public void setColor(ColorInterface c) { ColorAndroid ca = (ColorAndroid)c; paint.setColor(ca.getColorAndroid()); filled_stroke_paint.setColor(ca.getColorAndroid()); } /** Gets the color being used. @return the current color. It is an instance of ColorAndroid. */ public ColorInterface getColor() { return new ColorAndroid(paint.getColor()); } /** Retrieves or create a BasicStroke object having the wanted with and style and apply it to the current graphic context. @param w the width in pixel @param dashStyle the style of the stroke */ public void applyStroke(float w, int dashStyle) { // We check if we need to change anything. if(actual_w!=w || dashStyle!=actual_dash) { paint.setStrokeWidth(w); filled_stroke_paint.setStrokeWidth(w); if (dashStyle==0) { paint.setPathEffect(null); filled_stroke_paint.setPathEffect(null); } else { paint.setPathEffect(new DashPathEffect(Globals.dash[dashStyle], 0.0f)); filled_stroke_paint.setPathEffect( new DashPathEffect(Globals.dash[dashStyle], 0.0f)); } actual_dash = dashStyle; actual_w = w; } } /** Draws a rectangle on the current graphic context. @param x the x coordinate of the uppermost left corner @param y the y coordinate of the uppermost left corner @param width the width of the rectangle @param height the height of the rectangle */ public void drawRect(int x, int y, int width, int height) { // Dashing effects can be applied only to paths. // If this is not needed, we use the simple call drawLine // (I guess it is faster). If not, we create a path and we // draw it. // They are also interesting if the thickness is great than 1.5 pixels // because of their join and miter characteristics. if(actual_dash==0 && actual_w<1.5f) { canvas.drawRect(x, y, x+width, y+height, paint); } else { Path p = new Path(); p.moveTo(x,y); p.lineTo(x+width,y); p.lineTo(x+width,y+height); p.lineTo(x,y+height); p.lineTo(x,y); canvas.drawPath(p, paint); } } /** Fills a rectangle on the current graphic context. @param x the x coordinate of the uppermost left corner @param y the y coordinate of the uppermost left corner @param width the width of the rectangle @param height the height of the rectangle */ public void fillRect(int x, int y, int width, int height) { canvas.drawRect(x, y, x+width, y+height, filled_stroke_paint); } /** Fills a rounded rectangle on the current graphic context. @param x the x coordinate of the uppermost left corner @param y the y coordinate of the uppermost left corner @param width the width of the rectangle @param height the height of the rectangle @param arcWidth the width of the arc of the round corners @param arcHeight the height of the arc of the round corners */ public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { canvas.drawRoundRect(new RectF(x, y, x+width, y+height), (float)arcWidth/2.0f, (float)arcHeight/2.0f, filled_stroke_paint); } /** Check whether the rectangle specified falls in a region which need to be updated because it is "dirty" on the screen. Implementing correctly this method is very important to achieve a good redrawing speed because only "dirty" regions on the screen will be actually redrawn. @param x the x coordinate of the uppermost left corner of rectangle. @param y the y coordinate of the uppermost left corner of rectangle. @param width the width of the rectangle of the rectangle. @param height the height of the rectangle of the rectangle. @return true if the rectangle hits the dirty region. */ public boolean hitClip(int x, int y, int width, int height) { RectF rect=new RectF(x,y,x+width,y+height); return !canvas.quickReject (rect, Canvas.EdgeType.AA); } /** Draws a segment between two points @param x1 first coordinate x value @param y1 first coordinate y value @param x2 second coordinate x value @param y2 second coordinate y value */ public void drawLine(int x1, int y1, int x2, int y2) { // Dashing effects can be applied only to paths. // If this is not needed, we use the simple call drawLine // (I guess it is faster). If not, we create a path and we // draw it. // They are also interesting if the thickness is great than 1.5 pixels // because of their join and miter characteristics. if(actual_dash==0 && actual_w<1.5f) { canvas.drawLine(x1,y1, x2, y2, paint); } else { Path p = new Path(); p.moveTo(x1,y1); p.lineTo(x2,y2); canvas.drawPath(p, paint); } } /** Sets the current font for drawing text. @param name the name of the typeface to be used. @param size the size in pixels @param isItalic true if an italic variant should be used @param isBold true if a bold variant should be used */ public void setFont(String name, double size, boolean isItalic, boolean isBold) { int style; if(isBold && isItalic) style=Typeface.BOLD_ITALIC; else if (isBold) style=Typeface.BOLD; else if (isItalic) style=Typeface.ITALIC; else style=Typeface.NORMAL; Typeface tf = Typeface.create(name, style); paint.setTypeface(tf); paint.setTextSize((int)Math.round(size)); } /** Simple version. It sets the current font. @param name the name of the typeface @param size the vertical size in pixels */ public void setFont(String name, double size) { setFont(name, size, false, false); } /** Get the ascent metric of the current font. @return the value of the ascent, in pixels. */ public int getFontAscent() { // Note: an ascent is "going up", so it is negative // as in the FontMetrics documentation... // FidoCadJ requires a positive size, instead. return -(int)paint.getFontMetrics().ascent; } /** Get the descent metric of the current font. @return the value of the descent, in pixels. */ public int getFontDescent() { return (int)paint.getFontMetrics().descent; } /** Get the width of the given string with the current font. @param s the string to be used. @return the width of the string, in pixels. */ public int getStringWidth(String s) { return (int)paint.measureText(s); } /** Draw a string on the current graphic context @param str the string to be drawn @param x the x coordinate of the starting point @param y the y coordinate of the starting point */ public void drawString(String str, int x, int y) { applyStroke(1.0f, 0); paint.setStyle(Style.FILL); canvas.drawText (str, x, y, paint); paint.setStyle(Style.STROKE); } /** Set the transparency (alpha) of the current color. @param alpha the transparency, between 0.0 (transparent) and 1.0 (fully opaque). */ public void setAlpha(float alpha) { paint.setAlpha((int)(alpha*255)); filled_stroke_paint.setAlpha((int)(alpha*255)); } /** Draw a completely filled oval in the current graphic context. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. @param width the width of the oval. @param height the height of the oval. */ public void fillOval(int x, int y, int width, int height) { canvas.drawOval(new RectF (x, y, x+width, y+height), filled_stroke_paint); } /** Draw an enmpty oval in the current graphic context. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. @param width the width of the oval. @param height the height of the oval. */ public void drawOval(int x, int y, int width, int height) { canvas.drawOval(new RectF (x, y, x+width, y+height), paint); } /** Fill a given shape. @param s the shape to be filled. */ public void fill(ShapeInterface s) { ShapeAndroid ss = (ShapeAndroid) s; canvas.drawPath(ss.getPath(), filled_stroke_paint); } /** Draw a given shape. @param s the shape to be drawn. */ public void draw(ShapeInterface s) { ShapeAndroid ss = (ShapeAndroid) s; canvas.drawPath(ss.getPath(), paint); } /** Fill a given polygon. @param p the polygon to be filled. */ public void fillPolygon(PolygonInterface p) { PolygonAndroid pp=(PolygonAndroid) p; pp.close(); canvas.drawPath(pp.getPath(), filled_stroke_paint); } /** Draw a given polygon. @param p the polygon to be drawn. */ public void drawPolygon(PolygonInterface p) { PolygonAndroid pp=(PolygonAndroid) p; pp.close(); canvas.drawPath(pp.getPath(), paint); } /** Select a color associated to selected elements. @param l the layer to which the selected element belongs. */ public void activateSelectColor(LayerDesc l) { paint.setColor(Color.GREEN); filled_stroke_paint.setColor(Color.GREEN); } /** Draw a string by allowing for a certain degree of flexibility in specifying how the text will be handled. NOTE: TO BE REMOVED. @param xyfactor the text font is specified by giving its height in the setFont() method. If the text should be stretched (i.e. its width should be modified), this parameter gives the amount of stretching. @param xa the x coordinate of the point where the text will be placed. @param ya the y coordinate of the point where the text will be placed. @param qq not used: NOTE: TO REMOVE??? @param h the height of the text, in pixels. @param w the width of the string, in pixels. @param th the total height of the text (ascent+descents). @param needsStretching true if some stretching is needed. @param orientation orientation in degrees of the text. @param mirror true if the text is mirrored. @param txt the string to be drawn. */ public void drawAdvTextPath(double xyfactor, int xa, int ya, int qq, int h, int w, int th, boolean needsStretching, int orientation, boolean mirror, String txt) { // Note implementation using a path and drawTextOnPath (which is // buggy and probably a little slow... applyStroke(1.0f, 0); paint.setStyle(Style.FILL); Path pp=new Path(); pp.moveTo(xa,ya); if (mirror) { canvas.save(); canvas.scale(-1f, 1f, xa, ya); orientation=-orientation; } if(needsStretching) { float size=paint.getTextSize(); paint.setTextScaleX((float)(1.0f/xyfactor)); paint.setTextSize(size*(float)xyfactor); th=(int)(th*xyfactor); } else paint.setTextScaleX(1.0f); double orientationRad=-orientation/180.0*Math.PI; pp.rLineTo(1000*(float)Math.cos(orientationRad), 1000*(float)Math.sin(orientationRad)); // NOTE: there is an annoying bug in some versions of Android and // drawTextOnPath has a somewhat weird behavior while calculating the // clipping area. This is true at least when the graphics HW // acceleration is on. canvas.drawTextOnPath(txt, pp, 0,th, paint); if (mirror) { canvas.restore(); } paint.setStyle(Style.STROKE); paint.setTextScaleX(1.0f); } /** Draw a string by allowing for a certain degree of flexibility in specifying how the text will be handled. @param xyfactor the text font is specified by giving its height in the setFont() method. If the text should be stretched (i.e. its width should be modified), this parameter gives the amount of stretching. @param xa the x coordinate of the point where the text will be placed. @param ya the y coordinate of the point where the rotation is calculated. @param qq the y coordinate of the point where the text will be placed. @param h the height of the text, in pixels. @param w the width of the string, in pixels. @param th the total height of the text (ascent+descents). @param needsStretching true if some stretching is needed. @param orientation orientation in degrees of the text. @param mirror true if the text is mirrored. @param txt the string to be drawn. */ public void drawAdvText(double xyfactor, int xa, int ya, int qq, int h, int w, int th, boolean needsStretching, int orientation, boolean mirror, String txt) { applyStroke(1.0f, 0); paint.setStyle(Style.FILL); canvas.save(); if (mirror) { canvas.scale(-1f, 1f, xa, ya); orientation=-orientation; } if(needsStretching) { float size=paint.getTextSize(); paint.setTextScaleX((float)(1.0f/xyfactor)); paint.setTextSize(size*(float)xyfactor); th=(int)(th*xyfactor); } else paint.setTextScaleX(1.0f); canvas.rotate(-orientation, xa, ya); canvas.drawText(txt, xa, ya+th, paint); canvas.restore(); paint.setStyle(Style.STROKE); paint.setTextScaleX(1.0f); } /** Draw the grid in the given graphic context. @param cs the coordinate map description @param xmin the x (screen) coordinate of the upper left corner @param ymin the y (screen) coordinate of the upper left corner @param xmax the x (screen) coordinate of the bottom right corner @param ymax the y (screen) coordinate of the bottom right corner */ public void drawGrid(MapCoordinates cs, int xmin, int ymin, int xmax, int ymax) { // Drawing the grid seems easy, but it appears that setting a pixel // takes a lot of time. Basically, we create a textured brush and we // use it to paint the entire specified region. int dx=cs.getXGridStep(); int dy=cs.getYGridStep(); int mul=1; double toll=0.01; double z=cs.getYMagnitude(); double x; double y; double width; double height; Paint gridPoints = new Paint(); gridPoints.setColor(Color.LTGRAY); gridPoints.setStyle(Paint.Style.FILL_AND_STROKE); double m=1.0; // Fabricate a new image only if necessary, to save time. if(oldZoom!=z || gridPaint == null) { // It turns out that drawing the grid in an efficient way is not a // trivial problem. What it is done here is that the program tries // to calculate the minimum common integer multiple of the dot // espacement to calculate the size of an image in order to be an // integer. // The pattern filling (which is fast) is then used to replicate the // image (very fast!) over the working surface. for (double l=1; l<105; ++l) { if (Math.abs(l*z-Math.round(l*z))<toll) { mul=(int)l; break; } } gridPaint = null; double ddx=Math.abs(cs.mapXi(dx,0,false)-cs.mapXi(0,0,false)); double ddy=Math.abs(cs.mapYi(0,dy,false)-cs.mapYi(0,0,false)); float d=Math.round(getScreenDensity()/112)+1; // dot size // This code applies a correction: draws bigger points if the pitch // is very big, or draw much less points if it is too dense. if (ddx>50 || ddy>50) { d*=2; } else if (ddx<3 || ddy <3) { dx=5*cs.getXGridStep(); dy=5*cs.getYGridStep(); gridPoints.setColor(Color.parseColor("#A5EDF2")); ddx=Math.abs(cs.mapXr(dx,0)-cs.mapXr(0,0)); } width=Math.abs(cs.mapXr(mul*dx,0)-cs.mapXr(0,0)); if (width<=0) width=1; height=Math.abs(cs.mapYr(0,0)-cs.mapYr(0,mul*dy)); if (height<=0) height=1; /* Nowadays computers have generally a lot of memory, but this is not a good reason to waste it. If it turns out that the image size is utterly impratical, use the standard dot by dot grid construction. This should happen rarely, only for particular zoom sizes. */ if (width>1000 || height>1000) { drawGridSlowVersion(cs, xmin, ymin, xmax, ymax); return; } Bitmap bitmapImage; try { // Create a buffered image in which to draw bitmapImage = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.ARGB_8888); } catch (IllegalArgumentException E) { android.util.Log.e("fidocadj", "Can not create bitmap for drawing the grid."); return; } // Create a graphics contents on the buffered image Canvas cbitmap = new Canvas(bitmapImage); cbitmap.drawARGB(255, 255, 255, 255); float sx, sy; // Prepare the image with the grid. for (x=0; x<=cs.unmapXsnap((int)width); x+=dx) { for (y=0; y<=cs.unmapYsnap((int)height); y+=dy) { sx = (float)cs.mapXr(x,y); sy = (float)cs.mapYr(x,y); cbitmap.drawRect(sx-d/2, sy-d/2, sx+d/2, sy+d/2, gridPoints); } } oldZoom=z; BitmapShader fillBMPshader = new BitmapShader(bitmapImage, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT); gridPaint = new Paint(Color.GRAY); gridPaint.setStyle(Paint.Style.FILL); gridPaint.setShader(fillBMPshader); } // Textured paint :-) canvas.drawRect(xmin, ymin, xmax, ymax, gridPaint); } /** Draw a grid on the current shown drawing area. The grid shows the snapping point of the current MapCoordinates used for the drawing. This is a slower version of the drawGrid routine, used when everything else fails. The points are drawn one by one. @param cs the current MapCoordinates object used for the drawing. @param xmin the minimum x value (in pixel) of the viewport. @param ymin the minimum y value (in pixel) of the viewport. @param xmax the maximum x value (in pixel) of the viewport. @param ymax the maximum y value (in pixel) of the viewport. */ public void drawGridSlowVersion(MapCoordinates cs, int xmin, int ymin, int xmax, int ymax) { // NOTE: THIS IS AN INCREDIBLY SLOW CODE, ESPECIALLY FOR SOME ZOOM // SETTINGS! It happens the same thing with the Swing version of // this class, the best way to proceed is to use the bit blitting // properties of modern graphics using some sort of tiled painting. float dx=cs.getXGridStep(); float dy=cs.getYGridStep(); paint.setColor(Color.LTGRAY); paint.setStyle(Style.FILL_AND_STROKE); float x, y; float sx, sy; float d=Math.round(getScreenDensity()/112)+1; // dot size double ddx=Math.abs(cs.mapXi(dx,0,false)-cs.mapXi(0,0,false)); double ddy=Math.abs(cs.mapYi(0,dy,false)-cs.mapYi(0,0,false)); // This code applies a correction: draws bigger points if the pitch // is very big, or draw much less points if it is too dense. if (ddx>50 || ddy>50) { d=2*getScreenDensity()/112; } else if (ddx<3 || ddy <3) { dx=5*cs.getXGridStep(); dy=5*cs.getYGridStep(); paint.setColor(Color.parseColor("#A5EDF2")); ddx=Math.abs(cs.mapXi(dx,0,false)-cs.mapXi(0,0,false)); } for (x=cs.unmapXsnap(xmin); x<=cs.unmapXsnap(xmax); x+=dx) { for (y=cs.unmapYsnap(ymin); y<=cs.unmapYsnap(ymax); y+=dy) { sx=(float)cs.mapXr(x, y); sy=(float)cs.mapYr(x, y); canvas.drawRect(sx-d/2, sy-d/2, sx+d/2, sy+d/2, paint); } } paint.setStyle(Style.STROKE); } /** Create a polygon object, compatible with GraphicsAndroid. @return a polygon object (instance of PolygonAndroid). */ public PolygonInterface createPolygon() { return new PolygonAndroid(); } /** Create a color object, compatible with GraphicsAndroid. @return a color object (instance of ColorAndroid). */ public ColorInterface createColor() { return new ColorAndroid(); } /** Create a shape object, compatible with GraphicsAndroid. @return a shape object (instance of ShapeAndroid). */ public ShapeInterface createShape() { return new ShapeAndroid(); } /** Retrieve the current screen density in dots-per-inch. @return the screen resolution (density) in dots-per-inch. */ public float getScreenDensity() { return canvas.getDensity(); //getResources().getDisplayMetrics().densityDpi; } }
25,563
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PolygonAndroid.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/graphic/android/PolygonAndroid.java
package net.sourceforge.fidocadj.graphic.android; import java.util.Vector; import android.graphics.*; import net.sourceforge.fidocadj.graphic.*; /** PolygonInterface implementation for Android. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Davide Bucci </pre> */ public class PolygonAndroid implements PolygonInterface { private Path path; private int npoints; Vector<Integer> xpoints; Vector<Integer> ypoints; /** Standard constructor. */ public PolygonAndroid() { path=new Path(); npoints=0; xpoints = new Vector<Integer>(); ypoints = new Vector<Integer>(); } /** Get the current polygon as a path. @return the polygon as a path. */ public Path getPath() { return path; } /** Close the path. */ public void close() { path.close(); } /** Add a point to the current polygon. @param x the x coordinate of the point. @param y the y coordinate of the point. */ public void addPoint(int x, int y) { if(npoints++==0) path.moveTo(x, y); else path.lineTo(x, y); xpoints.add(x); ypoints.add(y); } /** Reset the current polygon by deleting all the points. */ public void reset() { path.reset(); npoints=0; xpoints.clear(); ypoints.clear(); } /** Get the current number of points in the polygon. @return the number of points. */ public int getNpoints() { return npoints; } /** Get a vector containing the x coordinates of the points. @return a vector containing the x coordinates of all points. */ public int[] getXpoints() { // ☠ Something better??? ☠ int[] xvector= new int[npoints]; int k=0; for(Integer v : xpoints) xvector[k++]=v; return xvector; } /** Get a vector containing the y coordinates of the points. @return a vector containing the y coordinates of all points. */ public int[] getYpoints() { // ☠ Something better??? ☠ int[] yvector= new int[npoints]; int k=0; for(Integer v : ypoints) yvector[k++]=v; return yvector; } /** Check whether the given point lies inside of the polygon @param x the x coordinate of the point @param y the y coordinate of the point @return true if the point is inside the polygon */ public boolean contains(int x, int y) { RectF rectF = new RectF(); path.computeBounds(rectF, true); Region r = new Region(); r.setPath(path, new Region((int) rectF.left, (int) rectF.top, (int) rectF.right, (int) rectF.bottom)); return r.contains(x,y); } }
3,537
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/package-info.java
/** <p> The package circuit contains the code for building a graphical editor, following a model/view/controller pattern. This package depends on other packages for implementing things such as the graphical primitives to be drawn.</p> */ package net.sourceforge.fidocadj.circuit;
284
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ImageAsCanvas.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/ImageAsCanvas.java
package net.sourceforge.fidocadj.circuit; import java.io.IOException; import net.sourceforge.fidocadj.geom.*; import net.sourceforge.fidocadj.graphic.*; /** Dummy class. One may be inspired by the corresponding class in the Swing application. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2019 by Davide Bucci </pre> */ public class ImageAsCanvas { /** Constructor. */ public ImageAsCanvas() { } /** Specify an image to attach to the current drawing. @param f the path and the filename of the image file to load and display. @throws IOException if the file is not found or can not be loaded. */ public void loadImage(String f) throws IOException { } /** Specify the resolution of the image in dots per inch. This is employed for the coordinate mapping so that the image size is correctly matched with the FidoCadJ coordinate systems. @param res image resolution in dots per inch (dpi). */ public void setResolution(double res) { } /** Get the current resolution in dpi. @return the current resolution in dots per inch. */ public double getResolution() { return 0; } /** Remove the attached image. */ public void removeImage() { } /** Get the current file name. @return the current file name */ public String getFilename() { return ""; } /** Set the coordinates of the origin corner (left topmost one). @param x the x coordinate. @param y the y coordinate. */ public void setCorner(double x, double y) { } /** Get the x coordinate of the left topmost point of the image (use FidoCadJ coordinates). @return the x coordinate. */ public double getCornerX() { return 0; } /** Track the extreme points of the image in the given coordinate systems. @param mc the coordinate systems. */ public void trackExtremePoints(MapCoordinates mc) { } /** Get the y coordinate of the left topmost point of the image (use FidoCadJ coordinates). @return the y coordinate. */ public double getCornerY() { return 0; } /** Draw the current image in the given graphic context. @param g the Graphic2D object where the image has to be drawn. @param mc the current coordinate mapping. */ public void drawCanvasImage(GraphicsInterface g, MapCoordinates mc) { } }
3,261
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
HasChangedListener.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/HasChangedListener.java
package net.sourceforge.fidocadj.circuit; /** Interface used to callback notify that something has changed <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. </pre> @version 1.0 @author Davide Bucci Copyright 2007-2023 by Davide Bucci */ public interface HasChangedListener { /** Method to be called to notify that something has changed in the drawing. */ void somethingHasChanged(); }
1,104
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/views/package-info.java
/**<p> The package circuit.views contains the views for the view/model/controller pattern to represent the contents of the model.DrawingModel class.</p> */ package net.sourceforge.fidocadj.circuit.views;
206
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
Drawing.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/views/Drawing.java
package net.sourceforge.fidocadj.circuit.views; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; import net.sourceforge.fidocadj.graphic.GraphicsInterface; /** Drawing: draws the FidoCadJ drawing. This is a view of the drawing. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2007-2023 by Davide Bucci </pre> */ public class Drawing { private final DrawingModel dmp; // True if the drawing needs holes. This implies that the redrawing // step must include a cycle at the end to draw all holes. private boolean needHoles; // *********** CACHE ************* // Here are some counters and local variables. We made them class members // to ensure that their place is reserved in memory and we do not need // some time expensive allocations, since speed is important in the draw // operation (used in draw). private double oZ; private double oX; private double oY; private double oO; private GraphicPrimitive gg; // NOPMD private int i_index; // NOPMD private int jIndex; // NOPMD /** Create a drawing view. @param pp the model to which the view will be associated. */ public Drawing (DrawingModel pp) { dmp=pp; } /** Draw the handles of all selected primitives @param gi the graphic context to be used. @param cs the coordinate mapping system to employ. */ public void drawSelectedHandles(GraphicsInterface gi, MapCoordinates cs) { for (GraphicPrimitive gp : dmp.getPrimitiveVector()) { if(gp.getSelected()) { gp.drawHandles(gi, cs); } } } /** Draw the current drawing. This code is rather critical. Do not touch it unless you know very precisely what you are doing. @param gG the graphic context in which the drawing should be drawn. @param cs the coordinate mapping to be used. */ public void draw(GraphicsInterface gG, MapCoordinates cs) { if(cs==null) { System.err.println( "DrawingModel.draw: ouch... cs not initialized :-("); return; } synchronized (this) { // At first, we check if the current view has changed. if(dmp.changed || oZ!=cs.getXMagnitude() || oX!=cs.getXCenter() || oY!=cs.getYCenter() || oO!=cs.getOrientation()) { oZ=cs.getXMagnitude(); oX=cs.getXCenter(); oY=cs.getYCenter(); oO=cs.getOrientation(); dmp.changed = false; // Here we force for a global refresh of graphic data at the // primitive level. for (GraphicPrimitive gp : dmp.getPrimitiveVector()) { gp.setChanged(true); } if (!dmp.drawOnlyPads) { cs.resetMinMax(); } } needHoles=dmp.drawOnlyPads; /* First possibility: we need to draw only one layer (for example in a macro). This is indicated by the fact that drawOnlyLayer is non negative. */ if(dmp.drawOnlyLayer>=0 && !dmp.drawOnlyPads){ // At first, we check if the layer is effectively used in the // drawing. If not, we exit directly. if(!dmp.layersUsed[dmp.drawOnlyLayer]) { return; } drawPrimitives(dmp.drawOnlyLayer, gG, cs); return; } else if (!dmp.drawOnlyPads) { // If we want to draw all layers, we need to process with order. for(jIndex=0;jIndex<LayerDesc.MAX_LAYERS; ++jIndex) { if(!dmp.layersUsed[jIndex]) { continue; } drawPrimitives(jIndex, gG,cs); } } // Draw in a second time only the PCB pads, in order to ensure that // the drills are always open. if(needHoles) { for (i_index=0; i_index<dmp.getPrimitiveVector().size(); ++i_index){ // We will process only primitive which require holes (pads // as well as macros containing pads). gg=(GraphicPrimitive)dmp.getPrimitiveVector().get(i_index); if (gg.needsHoles()) { gg.setDrawOnlyPads(true); gg.draw(gG, cs, dmp.layerV); gg.setDrawOnlyPads(false); } } } } } /** Returns true if there is the need of drawing holes in the actual drawing. @return true if holes are needed. */ public final boolean getNeedHoles() { synchronized(this) { return needHoles; } } /** Draws all the primitives and macros contained in the specified layer. This function is used mainly by the draw member. @param jIndex the layer to be considered. @param gG the graphic context in which to draw. */ private void drawPrimitives(int jIndex, GraphicsInterface graphic, MapCoordinates cs) { // Here we process all the primitives, one by one! for (GraphicPrimitive gg : dmp.getPrimitiveVector()) { // Layers are ordered. This improves the redrawing speed. if (jIndex>0 && gg.layer>jIndex) { break; } // Process a particular primitive if it is in the layer // being processed. if(gg.containsLayer(jIndex)) { gg.setDrawOnlyLayer(jIndex); gg.draw(graphic, cs, dmp.layerV); } if(gg.needsHoles()) { synchronized (this) { needHoles=true; } } } } }
6,899
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
Export.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/views/Export.java
package net.sourceforge.fidocadj.circuit.views; import java.io.*; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.DrawingSize; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.PrimitiveMacro; import net.sourceforge.fidocadj.primitives.PrimitivePCBPad; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; /** Export: export the FidoCadJ drawing. This is a view of the drawing. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2007-2023 by Davide Bucci </pre> */ public class Export { private final DrawingModel dmp; // Border to be used in the export in logical coordinates public static final int exportBorder=6; /** Creator @param pp the model containing the drawing to be exported. */ public Export(DrawingModel pp) { dmp=pp; } /** Export all primitives and macros in the current model. @param exp the export interface to be used @param mp the coordinate mapping @param exportInvisible true if invisible objects should be exported */ private void exportAllObjects(ExportInterface exp, boolean exportInvisible, MapCoordinates mp) throws IOException { GraphicPrimitive g; for (int i=0; i<dmp.getPrimitiveVector().size(); ++i) { g=(GraphicPrimitive)dmp.getPrimitiveVector().get(i); if(g.getLayer()==dmp.drawOnlyLayer && !(g instanceof PrimitiveMacro)) { if(((LayerDesc)dmp.layerV.get(g.getLayer())).isVisible|| exportInvisible) { g.export(exp, mp); } } else if(g instanceof PrimitiveMacro) { ((PrimitiveMacro)g).setDrawOnlyLayer(dmp.drawOnlyLayer); ((PrimitiveMacro)g).setExportInvisible(exportInvisible); if(((LayerDesc)dmp.layerV.get(g.getLayer())).isVisible|| exportInvisible) { g.export(exp, mp); } } } } /** Export the file header @param exp the selected exporting interface. @param mp the coordinate mapping system to adopt. @throws IOException when things goes wrong, for example because there has been a memory error or when access to files is impossible. */ public void exportHeader(ExportInterface exp, MapCoordinates mp) throws IOException { synchronized(this) { PointG o=new PointG(0,0); DimensionG d = DrawingSize.getImageSize(dmp, 1, true,o); d.width+=exportBorder; d.height+=exportBorder; // We remeber that getImageSize works only with logical // coordinates so we may trasform them: d.width *= mp.getXMagnitude(); d.height *= mp.getYMagnitude(); exp.setDashUnit(mp.getXMagnitude()); // We finally write the header exp.exportStart(d, dmp.layerV, mp.getXGridStep()); } } /** Export the file using the given interface. @param exp the selected exporting interface. @param exportInvisible specify that the primitives on invisible layers should be exported. @param mp the coordinate mapping system to adopt. @throws IOException when things goes wrong, for example because there has been a memory error or when access to files is impossible. */ public void exportDrawing(ExportInterface exp, boolean exportInvisible, MapCoordinates mp) throws IOException { synchronized(this) { if(dmp.drawOnlyLayer>=0 && !dmp.drawOnlyPads){ exportAllObjects(exp, exportInvisible, mp); } else if (!dmp.drawOnlyPads) { for(int j=0;j<dmp.layerV.size(); ++j) { dmp.setDrawOnlyLayer(j); exportAllObjects(exp, exportInvisible, mp); } dmp.setDrawOnlyLayer(-1); } // Export in a second time only the PCB pads, in order to ensure // that the drilling holes are always open. for (GraphicPrimitive g : dmp.getPrimitiveVector()) { if (g instanceof PrimitivePCBPad) { ((PrimitivePCBPad)g).setDrawOnlyPads(true); if(((LayerDesc)dmp.layerV.get(g.getLayer())).isVisible ||exportInvisible) { g.export(exp, mp); } ((PrimitivePCBPad)g).setDrawOnlyPads(false); } else if (g instanceof PrimitiveMacro) { // Uhm... not beautiful ((PrimitiveMacro)g).setExportInvisible(exportInvisible); ((PrimitiveMacro)g).setDrawOnlyPads(true); if(((LayerDesc)dmp.layerV.get(g.getLayer())).isVisible ||exportInvisible) { g.export(exp, mp); } ((PrimitiveMacro)g).setDrawOnlyPads(false); ((PrimitiveMacro)g).resetExport(); } } } } }
6,240
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ParserActions.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/ParserActions.java
package net.sourceforge.fidocadj.circuit.controllers; import java.io.*; import java.util.*; import java.net.*; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.export.ExportGraphic; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.layers.StandardLayers; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; import net.sourceforge.fidocadj.primitives.PrimitiveAdvText; import net.sourceforge.fidocadj.primitives.PrimitiveBezier; import net.sourceforge.fidocadj.primitives.PrimitiveComplexCurve; import net.sourceforge.fidocadj.primitives.PrimitiveConnection; import net.sourceforge.fidocadj.primitives.PrimitiveLine; import net.sourceforge.fidocadj.primitives.PrimitiveMacro; import net.sourceforge.fidocadj.primitives.PrimitivePCBLine; import net.sourceforge.fidocadj.primitives.PrimitivePCBPad; import net.sourceforge.fidocadj.primitives.PrimitiveRectangle; import net.sourceforge.fidocadj.primitives.PrimitiveOval; import net.sourceforge.fidocadj.primitives.MacroDesc; import net.sourceforge.fidocadj.primitives.PrimitivePolygon; /** ParserActions: perform parsing of FidoCadJ code. In general, those routines are constructed such as they are relatively fault-tolerant. If an error is detected in the file, the parsing is continued anyway and just an error message is sent to the console. Most of the times, the user will not see the error and this is probably OK since he/she will not be interested in it. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2007-2023 by Davide Bucci </pre> */ public class ParserActions { private final DrawingModel model; // This is the maximum number of tokens which will be considered in a line static final int MAX_TOKENS=10000; // True if FidoCadJ should use Windows style line feeds (appending \r // to the text generated). static final boolean useWindowsLineFeed=false; // Name of the last file opened public String openFileName = null; /** Standard constructor: provide the database class. @param pp the drawing model (database of the circuit). */ public ParserActions (DrawingModel pp) { model=pp; } /** Parse the circuit contained in the StringBuffer specified. This function resets the primitive database and then parses the circuit. @param s the string containing the circuit */ public void parseString(StringBuffer s) { model.getPrimitiveVector().clear(); addString(s, false); model.setChanged(true); } /** Renders a split version of the macros contained in the given string. @param s a string containing macros to be splitted. @param splitStandardMacros if it is true, even the standard macros will be split. @return the split macros. */ public StringBuffer splitMacros(StringBuffer s, boolean splitStandardMacros) { StringBuffer txt= new StringBuffer(""); DrawingModel qQ=new DrawingModel(); qQ.setLibrary(model.getLibrary()); // Inherit the library qQ.setLayers(model.getLayers()); // Inherit the layers // from the obtained string, obtain the new qQ object which will // be exported and then loaded into the clipboard. try { ParserActions pas=new ParserActions(qQ); pas.parseString(s); File temp= File.createTempFile("copy", ".fcd"); temp.deleteOnExit(); String frm=""; if(splitStandardMacros) { frm = "fcda"; } else { frm = "fcd"; } ExportGraphic.export(temp, qQ, frm, 1,true,false, true,false, false); FileInputStream input = null; BufferedReader bufRead = null; try { input = new FileInputStream(temp); bufRead = new BufferedReader( new InputStreamReader(input, Globals.encoding)); String line=bufRead.readLine(); if (line==null) { bufRead.close(); return new StringBuffer(""); } txt = new StringBuffer(); do { txt.append(line); txt.append("\n"); line =bufRead.readLine(); } while (line != null); } finally { if(input!=null) { input.close(); } if(bufRead!=null) { bufRead.close(); } } } catch(IOException e) { System.out.println("Error: "+e); } return txt; } /** Get the FidoCadJ text file. @param extensions specify if FCJ extensions should be used @return the sketch in the text FidoCadJ format */ public StringBuffer getText(boolean extensions) { StringBuffer s=registerConfiguration(extensions); for (GraphicPrimitive g:model.getPrimitiveVector()){ s.append(g.toString(extensions)); if(useWindowsLineFeed) { s.append("\r"); } } return s; } /** If it is needed, provides all the configurations settings at the beginning of the FidoCadJ file. @param extensions it is true when FidoCadJ should export using its extensions. @return a StringBuffer containing the configuration settings in the FidoCadJ file format. */ public StringBuffer registerConfiguration(boolean extensions) { StringBuffer s = new StringBuffer(); // This is something which is not contemplated by the original // FidoCAD for Windows. If extensions are not activated, just exit. if(!extensions) { return s; } // Here is the beginning of the output. We can eventually provide // some hints about the configuration of the software (if needed). // We start by checking if the diameter of the electrical connection // should be written. // We consider that a difference of 1e-5 is small enough if(Math.abs(Globals.diameterConnectionDefault- Globals.diameterConnection)>1e-5) { s.append("FJC C "+Globals.diameterConnection+"\n"); } s.append(checkAndRegisterLayers()); // Check if the line widths should be indicated if(Math.abs(Globals.lineWidth - Globals.lineWidthDefault)>1e-5) { s.append("FJC A "+Globals.lineWidth+"\n"); } if(Math.abs(Globals.lineWidthCircles - Globals.lineWidthCirclesDefault)>1e-5) { s.append("FJC B "+Globals.lineWidthCircles+"\n"); } return s; } /** Check if the layers should be indicated. */ private StringBuffer checkAndRegisterLayers() { StringBuffer s=new StringBuffer(); List<LayerDesc> layerV=model.getLayers(); List<LayerDesc> standardLayers = StandardLayers.createStandardLayers(); for(int i=0; i<layerV.size();++i) { LayerDesc l = (LayerDesc)layerV.get(i); if (l.getModified()) { int rgb=l.getColor().getRGB(); float alpha=l.getAlpha(); s.append("FJC L "+i+" "+rgb+" "+alpha+"\n"); // We compare the layers to the standard configuration. // If the name has been modified, the name configuration // is also saved. String defaultName= ((LayerDesc)standardLayers.get(i)).getDescription(); if (!l.getDescription().equals(defaultName)) { s.append("FJC N "+i+" "+l.getDescription()+"\n"); } } } return s; } /** Parse the circuit contained in the StringBuffer specified. this funcion add the circuit to the current primitive database. @param s the string containing the circuit @param selectNew specify that the added primitives should be selected. */ public void addString(StringBuffer s, boolean selectNew) //throws IOException { int i; // Character pointer within the string int j; // Token counter within the string boolean hasFCJ=false; // The last primitive had FCJ extensions StringBuffer token=new StringBuffer(); String macroFont = model.getTextFont(); int macroFontSize = model.getTextFontSize(); // Flag indicating that the line is already too long and should not be // processed anymore: boolean lineTooLong=false; GraphicPrimitive g = new PrimitiveLine(macroFont, macroFontSize); // The tokenized command string. String[] tokens=new String[MAX_TOKENS]; // Name and value fields for a primitive. Those arrays will contain // the tokenized TJ commands which follow an appropriate FCJ modifier. String[] name=null; String[] value=null; int vn=0; int vv=0; // Since the modifier FCJ follow the command, we need to save the // tokens of the line previously read, as well as the number of // tokens found in it. String[] oldTokens=new String[MAX_TOKENS]; int oldJ=0; int macroCounter=0; int l; token.ensureCapacity(256); /* This code is not very easy to read. If more extensions of the original FidoCAD format (performed with the FCJ tag) are to be implemented, it can be interesting to rewrite the parser as a state machine. */ synchronized(this) { List<LayerDesc> layerV=model.getLayers(); char c='\n'; int len; // Actual line number. This is useful to indicate where errors are. int lineNum=1; j=0; token.setLength(0); len=s.length(); // The purpose of this code is to tokenize the lines. Things are // made more complicated by the FCJ mechanism which acts as a // modifier for the previous command. for(i=0; i<len;++i){ c=s.charAt(i); if(c=='\n' || c=='\r'|| i==len-1) { //The string is finished lineTooLong=false; if(i==len-1 && c!='\n' && c!=' '){ token.append(c); } ++lineNum; tokens[j]=token.toString(); if (token.length()==0) { // Avoids trailing spaces j--; } try{ // When we enter here, we have tokenized the current // line and we kept in memory also the previous one. // The first possibility is that the current line does // not contain a FCJ modifier. In this case, process // the previous line since we have all the information // needed // for doing that. if(hasFCJ && !"FCJ".equals(tokens[0])) { hasFCJ = registerPrimitivesWithFCJ(hasFCJ, tokens, g, oldTokens, oldJ, selectNew); } if("FCJ".equals(tokens[0])) { // FidoCadJ extension! // Here the FCJ modifier changes something on the // previous command. So ve check case by case what // has to be modified. if(hasFCJ && "MC".equals(oldTokens[0])) { macroCounter=2; g=new PrimitiveMacro(model.getLibrary(),layerV, macroFont, macroFontSize); g.parseTokens(oldTokens, oldJ+1); } else if (hasFCJ && "LI".equals(oldTokens[0])) { g=new PrimitiveLine(macroFont, macroFontSize); // We concatenate the two lines in a single // array // of tokens (the same code will be repeated // several // times for other commands also). for(l=0; l<j+1; ++l) { oldTokens[l+oldJ+1]=tokens[l]; } // Update the number of tokens oldJ+=j+1; // The actual parsing of the tokens is // relegated // to the primitive. g.parseTokens(oldTokens, oldJ+1); g.setSelected(selectNew); if(oldJ>5 && "1".equals(oldTokens[oldJ])) { macroCounter = 2; } else { model.addPrimitive(g,false,null); } } else if (hasFCJ && "BE".equals(oldTokens[0])) { g=new PrimitiveBezier(macroFont, macroFontSize); for(l=0; l<j+1; ++l) { oldTokens[l+oldJ+1]=tokens[l]; } oldJ+=j+1; g.parseTokens(oldTokens, oldJ+1); g.setSelected(selectNew); if(oldJ>5 && "1".equals(oldTokens[oldJ])) { macroCounter = 2; } else { model.addPrimitive(g,false,null); } } else if (hasFCJ && ("RV".equals(oldTokens[0])|| "RP".equals(oldTokens[0]))) { g=new PrimitiveRectangle(macroFont, macroFontSize); for(l=0; l<j+1; ++l) { oldTokens[l+oldJ+1]=tokens[l]; } oldJ+=j+1; g.parseTokens(oldTokens, oldJ+1); g.setSelected(selectNew); if(oldJ>2 && "1".equals(oldTokens[oldJ])) { macroCounter = 2; } else { model.addPrimitive(g,false,null); } } else if (hasFCJ && ("EV".equals(oldTokens[0])|| "EP".equals(oldTokens[0]))) { g=new PrimitiveOval(macroFont, macroFontSize); for(l=0; l<j+1; ++l) { oldTokens[l+oldJ+1]=tokens[l]; } oldJ+=j+1; g.parseTokens(oldTokens, oldJ+1); g.setSelected(selectNew); if(oldJ>2 && "1".equals(oldTokens[oldJ])) { macroCounter = 2; } else { model.addPrimitive(g,false,null); } } else if (hasFCJ && ("PV".equals(oldTokens[0])|| "PP".equals(oldTokens[0]))) { g=new PrimitivePolygon(macroFont, macroFontSize); for(l=0; l<j+1; ++l) { oldTokens[l+oldJ+1]=tokens[l]; } oldJ+=j+1; g.parseTokens(oldTokens, oldJ+1); g.setSelected(selectNew); if(oldJ>2 && "1".equals(oldTokens[oldJ])) { macroCounter = 2; } else { model.addPrimitive(g,false,null); } } else if (hasFCJ && ("CV".equals(oldTokens[0])|| "CP".equals(oldTokens[0]))) { g=new PrimitiveComplexCurve(macroFont, macroFontSize); for(l=0; l<j+1; ++l) { oldTokens[l+oldJ+1]=tokens[l]; } oldJ+=j+1; g.parseTokens(oldTokens, oldJ+1); g.setSelected(selectNew); // If we have a name/value following, we // put macroCounter (successively used by // TY to determine that we are in a case in // which // TY commands must not be considered as // separate). if(oldJ>2 && "1".equals(oldTokens[oldJ])) { macroCounter = 2; } else { model.addPrimitive(g,false,null); } } else if (hasFCJ && "PL".equals(oldTokens[0])) { macroCounter = 2; } else if (hasFCJ && "PA".equals(oldTokens[0])) { macroCounter = 2; } else if (hasFCJ && "SA".equals(oldTokens[0])) { macroCounter = 2; } hasFCJ=false; } else if("FJC".equals(tokens[0])) { fidoConfig(tokens, j, layerV); } else if("LI".equals(tokens[0])) { // Save the tokenized line. // We cannot create the macro until we parse the // following line (which can be FCJ) macroCounter=0; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } oldJ=j; hasFCJ=true; } else if("BE".equals(tokens[0])) { macroCounter=0; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } oldJ=j; hasFCJ=true; } else if("MC".equals(tokens[0])) { // Save the tokenized line. macroCounter=0; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } oldJ=j; hasFCJ=true; } else if("TE".equals(tokens[0])) { hasFCJ=false; macroCounter=0; g=new PrimitiveAdvText(); g.parseTokens(tokens, j+1); g.setSelected(selectNew); model.addPrimitive(g,false,null); } else if("TY".equals(tokens[0])) { // The TY command is somewhat special, because // it can be used to specify the name and the value // of a primitive or a macro. Therefore, we try // to understand in which case we are hasFCJ=false; if(macroCounter==2) { macroCounter--; name=new String[j+1]; for(l=0; l<j+1;++l) { name[l]=tokens[l]; } vn=j; } else if(macroCounter==1) { value=new String[j+1]; for(l=0; l<j+1;++l) { value[l]=tokens[l]; } vv=j; if (name!=null) { g.setName(name,vn+1); } g.setValue(value,vv+1); g.setSelected(selectNew); model.addPrimitive(g, false,null); macroCounter=0; } else { // If we are in the classical case of a simple // isolated TY command, we process it. g=new PrimitiveAdvText(); g.parseTokens(tokens, j+1); g.setSelected(selectNew); model.addPrimitive(g,false,null); } } else if("PL".equals(tokens[0])) { hasFCJ=true; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } macroCounter=0; oldJ=j; g=new PrimitivePCBLine(macroFont, macroFontSize); g.parseTokens(tokens, j+1); g.setSelected(selectNew); } else if("PA".equals(tokens[0])) { hasFCJ=true; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } macroCounter=0; g=new PrimitivePCBPad(macroFont, macroFontSize); oldJ=j; g.parseTokens(tokens, j+1); g.setSelected(selectNew); } else if("SA".equals(tokens[0])) { hasFCJ=true; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } oldJ=j; macroCounter=0; g=new PrimitiveConnection(macroFont, macroFontSize); g.parseTokens(tokens, j+1); g.setSelected(selectNew); //addPrimitive(g,false,false); } else if("EV".equals(tokens[0]) ||"EP".equals(tokens[0])) { macroCounter=0; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } oldJ=j; hasFCJ=true; } else if("RV".equals(tokens[0]) ||"RP".equals(tokens[0])) { macroCounter=0; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } oldJ=j; hasFCJ=true; } else if("PV".equals(tokens[0]) ||"PP".equals(tokens[0])) { macroCounter=0; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } oldJ=j; hasFCJ=true; } else if("CV".equals(tokens[0]) ||"CP".equals(tokens[0])) { macroCounter=0; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } oldJ=j; hasFCJ=true; } } catch(IOException eE) { System.out.println("Error encountered: "+eE.toString()); System.out.println("string parsing line: "+lineNum); hasFCJ = true; macroCounter = 0; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } oldJ=j; } catch(NumberFormatException fF) { System.out.println( "I could not read a number at line: " +lineNum); hasFCJ = true; macroCounter = 0; for(l=0; l<j+1; ++l) { oldTokens[l]=tokens[l]; } oldJ=j; } j=0; token.setLength(0); } else if (c==' ' && !lineTooLong){ // Ready for next token tokens[j]=token.toString(); token.setLength(0); ++j; if (j>=MAX_TOKENS) { System.out.println("Too much tokens!"); System.out.println("string parsing line: "+lineNum); j=MAX_TOKENS-1; lineTooLong=true; continue; } } else { if (!lineTooLong) { token.append(c); } } } // We need to process the very last line, which is contained in // the tokens currently read. try{ registerPrimitivesWithFCJ(hasFCJ, tokens, g, oldTokens, oldJ, selectNew); } catch(IOException eE) { System.out.println("Error encountered: "+eE.toString()); System.out.println("string parsing line: "+lineNum); } catch(NumberFormatException fF) { System.out.println("I could not read a number at line: " +lineNum); } model.sortPrimitiveLayers(); } } /** Handle the FCJ command for the program configuration. */ private void fidoConfig(String[] tokens, int ntokens, List<LayerDesc> layerV) { double newConnectionSize = -1.0; double newLineWidth = -1.0; double newLineWidthCircles = -1.0; // FidoCadJ Configuration if("C".equals(tokens[1])) { // Connection size newConnectionSize = Double.parseDouble(tokens[2]); } else if("L".equals(tokens[1])) { // Layer configuration int layerNum = Integer.parseInt(tokens[2]); if (layerNum>=0&&layerNum<layerV.size()) { int rgb=Integer.parseInt(tokens[3]); float alpha=Float.parseFloat(tokens[4]); LayerDesc ll=(LayerDesc)layerV.get(layerNum); ll.getColor().setRGB(rgb); ll.setAlpha(alpha); ll.setModified(true); } } else if("N".equals(tokens[1])) { // Layer name int layerNum = Integer.parseInt(tokens[2]); if (layerNum>=0&&layerNum<layerV.size()){ String lName=""; StringBuffer temp=new StringBuffer(25); for(int t=3; t<ntokens+1; ++t) { temp.append(tokens[t]); temp.append(" "); } lName=temp.toString(); LayerDesc ll=(LayerDesc)layerV.get(layerNum); ll.setDescription(lName); ll.setModified(true); } } else if("A".equals(tokens[1])) { // Connection size newLineWidth = Double.parseDouble(tokens[2]); } else if("B".equals(tokens[1])) { // Connection size newLineWidthCircles = Double.parseDouble(tokens[2]); } // If the schematics has some configuration information, we need // to set them up. if (newConnectionSize>0) { Globals.diameterConnection=newConnectionSize; } if (newLineWidth>0) { Globals.lineWidth = newLineWidth; } if (newLineWidthCircles>0) { Globals.lineWidthCircles = newLineWidthCircles; } } /** This method checks if a primitive may have FCJ modifiers following. If no further FCJ tokens are present, the primitive is created immediately. If a FCJ token follows, we proceed to further parsing what follows. */ private boolean registerPrimitivesWithFCJ(boolean hasFCJt, String[] tokens, GraphicPrimitive gg, String[] oldTokens, int oldJ, boolean selectNew) throws IOException { String macroFont = model.getTextFont(); int macroFontSize = model.getTextFontSize(); List<LayerDesc> layerV=model.getLayers(); GraphicPrimitive g=gg; boolean hasFCJ=hasFCJt; boolean addPrimitive = false; if(hasFCJ && !"FCJ".equals(tokens[0])) { if ("MC".equals(oldTokens[0])) { g=new PrimitiveMacro(model.getLibrary(), layerV, macroFont, macroFontSize); addPrimitive = true; } else if ("LI".equals(oldTokens[0])) { g=new PrimitiveLine(macroFont, macroFontSize); addPrimitive = true; } else if ("BE".equals(oldTokens[0])) { g=new PrimitiveBezier(macroFont, macroFontSize); addPrimitive = true; } else if ("RP".equals(oldTokens[0])|| "RV".equals(oldTokens[0])) { g=new PrimitiveRectangle(macroFont, macroFontSize); addPrimitive = true; } else if ("EP".equals(oldTokens[0])|| "EV".equals(oldTokens[0])) { g=new PrimitiveOval(macroFont, macroFontSize); addPrimitive = true; } else if ("PP".equals(oldTokens[0]) ||"PV".equals(oldTokens[0])) { g=new PrimitivePolygon(macroFont, macroFontSize); addPrimitive = true; } else if("PL".equals(oldTokens[0])) { g=new PrimitivePCBLine(macroFont, macroFontSize); addPrimitive = true; } else if ("CP".equals(oldTokens[0]) ||"CV".equals(oldTokens[0])) { g=new PrimitiveComplexCurve(macroFont, macroFontSize); addPrimitive = true; } else if("PA".equals(oldTokens[0])) { g=new PrimitivePCBPad(macroFont, macroFontSize); addPrimitive = true; } else if("SA".equals(oldTokens[0])) { g=new PrimitiveConnection(macroFont, macroFontSize); addPrimitive = true; } } if(addPrimitive) { g.parseTokens(oldTokens, oldJ+1); g.setSelected(selectNew); model.addPrimitive(g,false,null); hasFCJ = false; } return hasFCJ; } /** Read all librairies contained in the given URL at the given prefix. This is particularly useful to read librairies shipped in a jar file. @param s the URL containing the libraries. @param prefix_s the prefix to be adopted for the keys of all elements in the library. Most of the times it is the filename, except for standard or internal libraries. */ public void loadLibraryInJar(URL s, String prefixS) { String prefix=prefixS; if(s==null) { if (prefix==null) { prefix=""; } System.out.println("Resource not found! "+prefix); return; } try { readLibraryBufferedReader(new BufferedReader(new InputStreamReader(s.openStream(), Globals.encoding)), prefix); } catch (IOException eE) { System.out.println("Problems reading library: "+s.toString()); } } /** Read the library contained in a file @param openFileName the name of the file to be loaded @throws IOException when something goes horribly wrong. Most of the times the filename is not found. */ public void readLibraryFile(String openFileName) throws IOException { InputStreamReader input = null; BufferedReader bufRead = null; String prefix=""; try { input = new InputStreamReader(new FileInputStream(openFileName), Globals.encoding); bufRead = new BufferedReader(input); prefix = Globals.getFileNameOnly(openFileName); if ("FCDstdlib".equals(prefix)) { prefix=""; } readLibraryBufferedReader(bufRead, prefix); } finally { if(bufRead!=null) { bufRead.close(); } if(input!=null) { input.close(); } } } /** Read a library provided by a buffered reader. Adds all the macro keys in memory, with the given prefix. @param bufRead The buffered reader prepared with the stream containing the library we want to read. @param prefix The prefix which should be added to the macro key when using a non standard macro. @throws IOException when something goes horribly wrong. */ public void readLibraryBufferedReader(BufferedReader bufRead, String prefix) throws IOException { String macroName=""; String longName=""; String categoryName=""; String libraryName=""; int i; String line=""; MacroDesc macroDesc; while(true) { // Read and process line by line. line = bufRead.readLine(); if(line==null) { break; } // Avoid trailing spaces line=line.trim(); // Avoid processing shorter lines if (line.length()<=1) { continue; } // A category if(line.charAt(0)=='{') { categoryName=""; StringBuffer temp=new StringBuffer(25); for(i=1; i<line.length()&&line.charAt(i)!='}'; ++i){ temp.append(line.charAt(i)); } categoryName=temp.toString().trim(); if(i==line.length()) { IOException e=new IOException( "Category non terminated with }."); throw e; } continue; } // A macro if(line.charAt(0)=='[') { macroName=""; longName=""; StringBuffer temp=new StringBuffer(25); for(i=1; line.charAt(i)!=' ' && line.charAt(i)!=']' && i<line.length(); ++i) { temp.append(line.charAt(i)); } macroName=temp.toString().trim(); int j; temp=new StringBuffer(25); for(j=i; j<line.length()&&line.charAt(j)!=']'; ++j){ temp.append(line.charAt(j)); } longName=temp.toString(); if(j==line.length()) { IOException e=new IOException( "Macro name non terminated with ]."); throw e; } if ("FIDOLIB".equals(macroName)) { libraryName = longName.trim(); continue; } else { if(!"".equals(prefix)) { macroName=prefix+"."+macroName; } macroName=macroName.toLowerCase(new Locale("en")); model.getLibrary().put(macroName, new MacroDesc(macroName,"","","","", prefix)); /*System.out.printf("-- macroName:%s | longName:%s | categoryName:%s | libraryName:%s | prefix:%s\n", macroName,longName,categoryName,libraryName,prefix);*/ continue; } } // TODO rewrite this block if(!"".equals(macroName)){ // Add the macro name. // NOTE: in FidoCAD, the macro prefix is somewhat case // insensitive, since it indicates a file name and in // Windows all file names are case insensitive. Under // other operating systems, we need to be waaay much // careful, hence we convert the macro name to lower case. macroName = macroName.toLowerCase(new Locale("en")); macroDesc = model.getLibrary().get(macroName); if(macroDesc==null) { return; } macroDesc.name = longName; macroDesc.key = macroName; macroDesc.category = categoryName; macroDesc.library = libraryName; macroDesc.filename = prefix; macroDesc.description = macroDesc.description + "\n" + line; } } } /** Try to load all libraries ("*.fcl") files in the given directory. FCDstdlib.fcl if exists will be considered as standard library. @param s the directory in which the libraries should be present. */ public void loadLibraryDirectory(String s) { String[] files; // The names of the files in the directory. File dir = new File(s); // Obtain the list of files in the specified directory. files = dir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { // This filter allows to obtain all files with the fcd // file extension return name.toLowerCase(new Locale("en")).endsWith(".fcl"); } }); // We first check if the directory is existing or is not empty. if(!dir.exists() || files==null) { if (!"".equals(s)){ System.out.println("Warning! Library directory is incorrect:"); System.out.println(s); } System.out.println( "Activated FidoCadJ internal libraries and symbols."); return; } // We read all the directory content, file by file for (String fs: files) { File f = new File(dir, fs); try { // Here we have a hopefully valid file in f, so we may read its // contents readLibraryFile(f.getPath()); } catch (IOException eE) { System.out.println("Problems reading library "+ f.getName()+" "+eE); } } } }
41,388
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/package-info.java
/**<p> The package circuit.controllers contains classes useful for modify the drawing stored in the circuit.model.DrawingModel class. They contain the code needed for parsing the drawing code, to take care of undo operations (with some limitations when libraries are taken into account) as well as interaction with the pointing device.</p> <p>Each controller class implements a certain number of "actions" (hence the name of the classes) to be performed on the model specified generally during the construction. </p> */ package net.sourceforge.fidocadj.circuit.controllers;
584
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ContinuosMoveActions.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/ContinuosMoveActions.java
package net.sourceforge.fidocadj.circuit.controllers; import java.io.*; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.ChangeCoordinatesListener; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.StandardLayers; import net.sourceforge.fidocadj.primitives.PrimitiveLine; import net.sourceforge.fidocadj.primitives.PrimitiveOval; import net.sourceforge.fidocadj.primitives.PrimitiveRectangle; import net.sourceforge.fidocadj.primitives.PrimitiveComplexCurve; import net.sourceforge.fidocadj.primitives.PrimitivePolygon; import net.sourceforge.fidocadj.primitives.PrimitivePCBLine; import net.sourceforge.fidocadj.primitives.PrimitiveMacro; /** Extends ElementsEdtActions in order to support those events such as MouseMove, which require a continuous interaction and an immediate rendering. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 by Davide Bucci </pre> @author Davide Bucci */ public class ContinuosMoveActions extends ElementsEdtActions { // A coordinates listener private ChangeCoordinatesListener coordinatesListener=null; private int oldx; private int oldy; /** Constructor @param pp the DrawingModel to be associated to the controller @param s the selection controller. @param u undo controller, exploited here @param e editor controller, exploited here */ public ContinuosMoveActions(DrawingModel pp, SelectionActions s, UndoActions u, EditorActions e) { super(pp, s, u, e); oldx=-1; oldy=-1; } /** Define the listener to be called when the coordinates of the mouse cursor are changed @param c the new coordinates listener */ public void addChangeCoordinatesListener(ChangeCoordinatesListener c) { coordinatesListener=c; } /** Handle a continuous move of the pointer device. It can be the result of a mouse drag for a rectangular selection, or a component move. @param cs the coordinate mapping which should be used @param xa the pointer position (x), in screen coordinates @param ya the pointer position (y), in screen coordinates @param isControl true if the CTRL key is pressed. This modifies some behaviors (for example, when introducing an ellipse it is forced to be a circle and so on). @return true if a repaint should be done */ public boolean continuosMove(MapCoordinates cs, int xa, int ya, boolean isControl) { // This transformation/antitrasformation is useful to take care // of the snapping. int x=cs.mapX(cs.unmapXsnap(xa),0); int y=cs.mapY(0,cs.unmapYsnap(ya)); // If there is anything interesting to do, leave immediately. if(oldx==x && oldy==y) { return false; } oldx=x; oldy=y; // Notify the current pointer coordinates, if a listener is available. if (coordinatesListener!=null) { coordinatesListener.changeCoordinates( cs.unmapXsnap(xa), cs.unmapYsnap(ya)); } boolean toRepaint=false; // This is the newer code: if primEdit is different from null, // it will be drawn in the paintComponent event // We need to differentiate this case since when we are entering a // macro, primEdit contains some useful hints about the orientation // and the mirroring if (actionSelected !=ElementsEdtActions.MACRO) { primEdit = null; } /* MACRO *********************************************************** +1+# # # # ######### ## ##### ## ############# ############### # ########### # # # # # #### #### */ if (actionSelected == ElementsEdtActions.MACRO) { try { int orientation = 0; boolean mirror = false; if (primEdit instanceof PrimitiveMacro) { orientation = ((PrimitiveMacro)primEdit).getOrientation(); mirror = ((PrimitiveMacro)primEdit).isMirrored(); } PrimitiveMacro n = new PrimitiveMacro(dmp.getLibrary(), StandardLayers.createEditingLayerArray(), cs.unmapXsnap(x), cs.unmapYsnap(y),macroKey,"", cs.unmapXsnap(x)+10, cs.unmapYsnap(y)+5, "", cs.unmapXsnap(x)+10, cs.unmapYsnap(y)+10, dmp.getTextFont(), dmp.getTextFontSize(), orientation, mirror); n.setDrawOnlyLayer(-1); primEdit = n; toRepaint=true; successiveMove = true; } catch (IOException eE) { // Here we do not do nothing. System.out.println("Warning: exception while handling macro: " +eE); } } if (clickNumber == 0) { return toRepaint; } /* LINE ************************************************************** +1+ ** ** ** ** +2+ */ if (actionSelected == ElementsEdtActions.LINE) { primEdit = new PrimitiveLine(xpoly[1], ypoly[1], cs.unmapXsnap(x), cs.unmapYsnap(y), 0, false, false, 0, 3, 2, 0, dmp.getTextFont(), dmp.getTextFontSize()); toRepaint=true; successiveMove = true; if (coordinatesListener!=null) { double w = Math.sqrt((xpoly[1]- cs.unmapXsnap(xa))* (xpoly[1]-cs.unmapXsnap(xa))+ (ypoly[1]-cs.unmapYsnap(ya))* (ypoly[1]-cs.unmapYsnap(ya))); double wmm = w*127/1000; coordinatesListener.changeInfos( Globals.messages.getString("length")+Globals.roundTo(w,2)+ " ("+Globals.roundTo(wmm,2)+" mm)"); } } /* PCBLINE *********************************************************** +1+ *** *** *** *** +2+ */ if (actionSelected == ElementsEdtActions.PCB_LINE) { primEdit = new PrimitivePCBLine(xpoly[1], ypoly[1], cs.unmapXsnap(x), cs.unmapYsnap(y), ae.getPcbThickness(), 0, dmp.getTextFont(), dmp.getTextFontSize()); toRepaint=true; successiveMove = true; if (coordinatesListener!=null) { double w = Math.sqrt((xpoly[1]- cs.unmapXsnap(xa))* (xpoly[1]-cs.unmapXsnap(xa))+ (ypoly[1]-cs.unmapYsnap(ya))* (ypoly[1]-cs.unmapYsnap(ya))); coordinatesListener.changeInfos( Globals.messages.getString("length")+ Globals.roundTo(w,2)); } } /* BEZIER ************************************************************ +3+ +1+ ****** **** ** +2+ ** ** ** +4+ */ if (actionSelected == ElementsEdtActions.BEZIER) { // Since we do not know how to fabricate a cubic curve with less // than four points, we use a polygon instead. primEdit = new PrimitivePolygon(false, 0, 0, dmp.getTextFont(), dmp.getTextFontSize()); for(int i=1; i<=clickNumber; ++i) { ((PrimitivePolygon)primEdit).addPoint(xpoly[i], ypoly[i]); } ((PrimitivePolygon)primEdit).addPoint(cs.unmapXsnap(x), cs.unmapYsnap(y)); toRepaint=true; successiveMove = true; } /* POLYGON *********************************************************** +1+ +3+ ************** *********** ******** ***** +2+ */ if (actionSelected == ElementsEdtActions.POLYGON) { primEdit = new PrimitivePolygon(false, 0, 0, dmp.getTextFont(), dmp.getTextFontSize()); for(int i=1; i<=clickNumber && i<ElementsEdtActions.NPOLY; ++i) { ((PrimitivePolygon)primEdit).addPoint(xpoly[i], ypoly[i]); } ((PrimitivePolygon)primEdit).addPoint(cs.unmapXsnap(x), cs.unmapYsnap(y)); toRepaint=true; successiveMove = true; } /* COMPLEX CURVE **************************************************** +1+ +5+ ***** ***** ****************+4+ +2+*********** **** +3+ */ if (actionSelected == ElementsEdtActions.COMPLEXCURVE) { primEdit = new PrimitiveComplexCurve(false, false, 0, false, false, 0, 3, 2, 0, dmp.getTextFont(),dmp.getTextFontSize()); for(int i=1; i<=clickNumber && i<ElementsEdtActions.NPOLY; ++i) { ((PrimitiveComplexCurve)primEdit).addPoint(xpoly[i], ypoly[i]); } ((PrimitiveComplexCurve)primEdit).addPoint(cs.unmapXsnap(x), cs.unmapYsnap(y)); toRepaint=true; successiveMove = true; } /* RECTANGLE ********************************************************* +1+ ********** ********** ********** ********** +2+ */ if (actionSelected == ElementsEdtActions.RECTANGLE) { // If control is hold, trace a square int ymm; if(isControl&&clickNumber>0) { ymm=cs.mapY(xpoly[1],ypoly[1])+x-cs.mapX(xpoly[1],ypoly[1]); } else { ymm=y; } primEdit = new PrimitiveRectangle(xpoly[1], ypoly[1], cs.unmapXsnap(x), cs.unmapYsnap(ymm), false, 0, 0, dmp.getTextFont(), dmp.getTextFontSize()); toRepaint=true; successiveMove = true; } /* ELLIPSE *********************************************************** +1+ *** ******* ********* ********* ******* *** +2+ */ if (actionSelected == ElementsEdtActions.ELLIPSE) { // If control is hold, trace a circle int ymm; if(isControl&&clickNumber>0) { ymm=cs.mapY(xpoly[1],ypoly[1])+x-cs.mapX(xpoly[1],ypoly[1]); } else { ymm=y; } primEdit = new PrimitiveOval(xpoly[1], ypoly[1], cs.unmapXsnap(x), cs.unmapYsnap(ymm), false, 0, 0, dmp.getTextFont(), dmp.getTextFontSize()); toRepaint=true; successiveMove = true; } return toRepaint; } }
12,466
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
EditorActions.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/EditorActions.java
package net.sourceforge.fidocadj.circuit.controllers; import java.util.*; import net.sourceforge.fidocadj.circuit.model.ProcessElementsInterface; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; import net.sourceforge.fidocadj.primitives.PrimitiveMacro; /** EditorActions: contains a controller which can perform basic editor actions on a primitive database. Those actions include rotating and mirroring objects and selecting/deselecting them. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 by Davide Bucci </pre> @author Davide Bucci */ public class EditorActions { private final DrawingModel dmp; private final UndoActions ua; private final SelectionActions sa; // Tolerance in pixels to select an object public int sel_tolerance = 10; /** Standard constructor: provide the database class. @param pp the Model containing the database. @param s the SelectionActions controller @param u the Undo controller, to ease undo operations. */ public EditorActions (DrawingModel pp, SelectionActions s, UndoActions u) { dmp=pp; ua=u; sa=s; sel_tolerance = 10; } /** Set the current selection tolerance in pixels (the default when the class is created is 10 pixels. @param s the new tolerance. */ public void setSelectionTolerance(int s) { sel_tolerance = s; } /** Get the selection tolerance in pixels. @return the current selection tolerance. */ public int getSelectionTolerance() { return sel_tolerance; } /** Rotate all selected primitives. */ public void rotateAllSelected() { GraphicPrimitive g = sa.getFirstSelectedPrimitive(); if(g==null) { return; } final int ix = g.getFirstPoint().x; final int iy = g.getFirstPoint().y; sa.applyToSelectedElements(new ProcessElementsInterface() { public void doAction(GraphicPrimitive g) { g.rotatePrimitive(false, ix, iy); } }); if(ua!=null) { ua.saveUndoState(); } } /** Move all selected primitives. @param dx relative x movement @param dy relative y movement */ public void moveAllSelected(final int dx, final int dy) { sa.applyToSelectedElements(new ProcessElementsInterface() { public void doAction(GraphicPrimitive g) { g.movePrimitive(dx, dy); } }); if(ua!=null) { ua.saveUndoState(); } } /** Mirror all selected primitives. */ public void mirrorAllSelected() { GraphicPrimitive g = sa.getFirstSelectedPrimitive(); if(g==null) { return; } final int ix = g.getFirstPoint().x; sa.applyToSelectedElements(new ProcessElementsInterface(){ public void doAction(GraphicPrimitive g) { g.mirrorPrimitive(ix); } }); if(ua!=null) { ua.saveUndoState(); } } /** Delete all selected primitives. @param saveState true if the undo controller should save the state of the drawing, after the delete operation is done. It should be put to false, when the delete operation is part of a more complex operation which is not yet ended after the call to this method. */ public void deleteAllSelected(boolean saveState) { int i; List<GraphicPrimitive> v=dmp.getPrimitiveVector(); for (i=0; i<v.size(); ++i){ if(v.get(i).getSelected()) { v.remove(v.get(i--)); } } if (saveState && ua!=null) { ua.saveUndoState(); } } /** Sets the layer for all selected primitives. @param l the wanted layer index. @return true if at least a layer has been changed. */ public boolean setLayerForSelectedPrimitives(int l) { boolean toRedraw=false; // Search for all selected primitives. for (GraphicPrimitive g: dmp.getPrimitiveVector()) { // If selected, change the layer. Macros must be always associated // to layer 0. if (g.getSelected() && ! (g instanceof PrimitiveMacro)) { g.setLayer(l); toRedraw=true; } } if(toRedraw) { dmp.sortPrimitiveLayers(); dmp.setChanged(true); ua.saveUndoState(); } return toRedraw; } /** Calculates the minimum distance between the given point and a set of primitive. Every coordinate is logical. @param px the x coordinate of the given point. @param py the y coordinate of the given point. @return the distance in logical units. */ public int distancePrimitive(int px, int py) { int distance; int mindistance=Integer.MAX_VALUE; int layer=0; List<LayerDesc> layerV=dmp.getLayers(); // Check the minimum distance by searching among all // primitives for (GraphicPrimitive g: dmp.getPrimitiveVector()) { distance=g.getDistanceToPoint(px,py); if(distance<=mindistance) { layer = g.getLayer(); if(layerV.get(layer).isVisible) { mindistance=distance; } } } return mindistance; } /** Handle the selection (or deselection) of objects. Search the closest graphical objects to the given (screen) coordinates. This method provides an interface to the {@link #selectPrimitive} method, which is oriented towards a more low-level process. @param cs the coordinate mapping to be employed. @param x the x coordinate of the click (screen). @param y the y coordinate of the click (screen). @param toggle select always if false, toggle selection on/off if true. */ public void handleSelection(MapCoordinates cs, int x, int y, boolean toggle) { // Deselect primitives if needed. if(!toggle) { sa.setSelectionAll(false); } // Calculate a reasonable tolerance. If it is too small, we ensure // that it is rounded up to 2. int toll= cs.unmapXnosnap(x+sel_tolerance)-cs.unmapXnosnap(x); if (toll<2) { toll=2; } selectPrimitive(cs.unmapXnosnap(x), cs.unmapYnosnap(y), toll, toggle); } /** Select primitives close to the given point. Every parameter is given in logical coordinates. @param px the x coordinate of the given point (logical). @param py the y coordinate of the given point (logical). @param tolerance tolerance for the selection. @param toggle select always if false, toggle selection on/off if true @return true if a primitive has been selected. */ private boolean selectPrimitive(int px, int py, int tolerance, boolean toggle) { int distance; int mindistance=Integer.MAX_VALUE; int layer; GraphicPrimitive gpsel=null; List<LayerDesc> layerV=dmp.getLayers(); /* The search method is very simple: we compute the distance of the given point from each primitive and we retain the minimum value, if it is less than a given tolerance. */ for (GraphicPrimitive g: dmp.getPrimitiveVector()) { layer = g.getLayer(); if(layerV.get(layer).isVisible || g instanceof PrimitiveMacro) { distance=g.getDistanceToPoint(px,py); if (distance<=mindistance) { gpsel=g; mindistance=distance; } } } // Check if we found something! if (mindistance<tolerance && gpsel!=null) { if(toggle) { gpsel.setSelected(!gpsel.getSelected()); } else { gpsel.setSelected(true); } return true; } return false; } /** Select primitives in a rectangular region (given in logical coordinates) @param px the x coordinate of the top left point. @param py the y coordinate of the top left point. @param w the width of the region @param h the height of the region @return true if at least a primitive has been selected */ public boolean selectRect(int px, int py, int w, int h) { int layer; boolean s=false; // Avoid processing a trivial case. if(w<1 || h <1) { return false; } List<LayerDesc> layerV=dmp.getLayers(); // Process every primitive, if the corresponding layer is visible. for (GraphicPrimitive g: dmp.getPrimitiveVector()){ layer= g.getLayer(); if((layer>=layerV.size() || layerV.get(layer).isVisible || g instanceof PrimitiveMacro) && g.selectRect(px,py,w,h)) { s=true; } } return s; } }
10,135
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
HandleActions.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/HandleActions.java
package net.sourceforge.fidocadj.circuit.controllers; import java.util.*; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; import net.sourceforge.fidocadj.primitives.PrimitiveRectangle; import net.sourceforge.fidocadj.primitives.PrimitiveMacro; import net.sourceforge.fidocadj.primitives.PrimitiveOval; /** CopyPasteActions: contains a controller which can perform handle drag and move actions on a primitive database <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 by Davide Bucci </pre> @author Davide Bucci */ public class HandleActions { private final DrawingModel dmp; private final EditorActions edt; private final UndoActions ua; private final SelectionActions sa; // ******** DRAG & INTERFACE ********* // True if we are at the beginning of a dragging operation. private boolean firstDrag; // The graphic primitive being treated. private GraphicPrimitive primBeingDragged=null; // The handle of the active graphic primitive being treated. private int handleBeingDragged; // Old cursor position for handle drag. private int opx; private int opy; // True if the primitive has moved while dragging. private boolean hasMoved; // Other old cursor position for handle drag... private int oldpx; private int oldpy; /** Standard constructor: provide the database class. @param pp the drawing model @param e the editor controller @param s the selection controller @param u the undo controller */ public HandleActions (DrawingModel pp, EditorActions e, SelectionActions s, UndoActions u) { dmp=pp; edt=e; ua=u; sa=s; firstDrag=false; handleBeingDragged=GraphicPrimitive.NO_DRAG; } /** Drag all the selected primitives during a drag operation. Position the primitives in the given (screen) position @param cc the element containing the drawing, which can receive repaint callbacks. @param px the x position (screen coordinates). @param py the y position (screen coordinates). @param cs the coordinate mapping. */ public void dragPrimitives(PrimitivesParInterface cc, int px, int py, MapCoordinates cs) { // Check if we are effectively dragging the whole primitive... if(handleBeingDragged!=GraphicPrimitive.DRAG_PRIMITIVE) { return; } firstDrag=false; int dx=cs.unmapXsnap(px)-oldpx; int dy=cs.unmapYsnap(py)-oldpy; oldpx=cs.unmapXsnap(px); oldpy=cs.unmapXsnap(py); if(dx==0 && dy==0) { return; } // Here we adjust the new positions for all selected elements... for (GraphicPrimitive g : dmp.getPrimitiveVector()){ if(g.getSelected()) { // This code is needed to ensure that all layer are printed // when dragging a component (it solves bug #24) if (g instanceof PrimitiveMacro) { ((PrimitiveMacro)g).setDrawOnlyLayer(-1); } for(int j=0; j<g.getControlPointNumber();++j){ g.virtualPoint[j].x+=dx; g.virtualPoint[j].y+=dy; // Here we show the new place of the primitive. } g.setChanged(true); } } cc.forcesRepaint(); } /** Start dragging handle. Check if the pointer is on the handle of a primitive and if it is the case, enter the dragging state. @param px the (screen) x coordinate of the pointer. @param py the (screen) y coordinate of the pointer. @param tolerance the tolerance (screen. i.e. no of pixel). @param multiple specifies whether multiple selection is active. @param cs the coordinate mapping to be used. */ public void dragHandleStart(int px, int py, int tolerance, boolean multiple, MapCoordinates cs) { int i; int isel=0; int mindistance=Integer.MAX_VALUE; int distance=mindistance; int layer; hasMoved=false; GraphicPrimitive gp; List<LayerDesc> layerV=dmp.getLayers(); oldpx=cs.unmapXnosnap(px); oldpy=cs.unmapXnosnap(py); firstDrag=true; int sptol=Math.abs(cs.unmapXnosnap(px+tolerance)-cs.unmapXnosnap(px)); if (sptol<2) { sptol=2; } // Search for the closest primitive to the given point // Performs a cycle through all primitives and check their // distance. for (i=0; i<dmp.getPrimitiveVector().size(); ++i){ gp=(GraphicPrimitive)dmp.getPrimitiveVector().get(i); layer= gp.getLayer(); // Does not allow for selecting an invisible primitive if(layer<layerV.size() && !((LayerDesc)layerV.get(layer)).isVisible && !(gp instanceof PrimitiveMacro)) { continue; } if(gp.selectedState){ // Verify if the pointer is on a handle handleBeingDragged=gp.onHandle(cs, px, py); if(handleBeingDragged!=GraphicPrimitive.NO_DRAG) { primBeingDragged=gp; continue; } } distance=gp.getDistanceToPoint(oldpx,oldpy); if (distance<=mindistance) { isel=i; mindistance=distance; } } // Verify if the whole primitive should be drag if (mindistance<sptol && handleBeingDragged<0){ primBeingDragged= (GraphicPrimitive)dmp.getPrimitiveVector().get(isel); if (!multiple && !primBeingDragged.getSelected()) { sa.setSelectionAll(false); } if(!multiple) { primBeingDragged.setSelected(true); } handleBeingDragged=GraphicPrimitive.DRAG_PRIMITIVE; firstDrag=true; oldpx=cs.unmapXsnap(px); oldpy=cs.unmapXsnap(py); } else if (handleBeingDragged<0) { // We want to select things in a rectangular area oldpx=cs.unmapXsnap(px); oldpy=cs.unmapXsnap(py); handleBeingDragged=GraphicPrimitive.RECT_SELECTION; } } /** End dragging handle. @param cC the editor object @param px the (screen) x coordinate of the pointer. @param py the (screen) y coordinate of the pointer. @param multiple specifies whether multiple selection is active. @param cs the coordinate mapping to be used. */ public void dragHandleEnd(PrimitivesParInterface cC, int px, int py, boolean multiple, MapCoordinates cs) { // Check if we are effectively dragging something... cC.setEvidenceRect(0,0,-1,-1); if(handleBeingDragged<0){ if(handleBeingDragged==GraphicPrimitive.RECT_SELECTION){ int xa=Math.min(oldpx, cs.unmapXnosnap(px)); int ya=Math.min(oldpy, cs.unmapYnosnap(py)); int xb=Math.max(oldpx, cs.unmapXnosnap(px)); int yb=Math.max(oldpy, cs.unmapYnosnap(py)); if(!multiple) { sa.setSelectionAll(false); } edt.selectRect(xa, ya, xb-xa, yb-ya); } // Test if we are anyway dragging an entire primitive if(handleBeingDragged==GraphicPrimitive.DRAG_PRIMITIVE && hasMoved && ua!=null) { ua.saveUndoState(); } handleBeingDragged=GraphicPrimitive.NO_DRAG; return; } handleBeingDragged=GraphicPrimitive.NO_DRAG; if(ua!=null) { ua.saveUndoState(); } } /** Drag a handle. @param cC the editor object. @param px the (screen) x coordinate of the pointer. @param py the (screen) y coordinate of the pointer. @param cs the coordinates mapping to be used. @param isControl true if the control key is held down. */ public void dragHandleDrag(PrimitivesParInterface cC, int px, int py, MapCoordinates cs, boolean isControl) { hasMoved=true; boolean flip=false; // Check if we are effectively dragging a handle... if(handleBeingDragged<0){ if(handleBeingDragged==GraphicPrimitive.DRAG_PRIMITIVE) { dragPrimitives(cC, px, py, cs); } // if not, we are performing a rectangular selection if(handleBeingDragged==GraphicPrimitive.RECT_SELECTION) { int xa = cs.mapXi(oldpx, oldpy, false); int ya = cs.mapYi(oldpx, oldpy, false); int xb = opx; int yb = opy; if(opx>xa && px<xa) { flip=true; } if(opy>ya && py<ya) { flip=true; } if(!firstDrag) { int a = Math.min(xa,xb); int b = Math.min(ya,yb); int c = Math.abs(xb-xa); int d = Math.abs(yb-ya); xb=px; yb=py; opx=px; opy=py; cC.setEvidenceRect(Math.min(xa,xb), Math.min(ya,yb), Math.abs(xb-xa), Math.abs(yb-ya)); a=Math.min(a, Math.min(xa,xb)); b=Math.min(b, Math.min(ya,yb)); c=Math.max(c, Math.abs(xb-xa)); d=Math.max(d, Math.abs(yb-ya)); if (flip) { cC.forcesRepaint(); } else { cC.forcesRepaint(a,b,c+10,d+10); } return; } xb=px; yb=py; opx=px; opy=py; firstDrag=false; } return; } if(!firstDrag) { cC.forcesRepaint(); } firstDrag=false; // Here we adjust the new positions for the handle being drag... primBeingDragged.virtualPoint[handleBeingDragged].x=cs.unmapXsnap(px); // If control is hold, trace a square int ymm; if(!isControl || !(primBeingDragged instanceof PrimitiveOval || primBeingDragged instanceof PrimitiveRectangle)) { ymm=py; } else { // Transform the rectangle in a square, or the oval in a circle. int hn=0; if(handleBeingDragged==0) { hn=1; } ymm=cs.mapYi(primBeingDragged.virtualPoint[hn].x, primBeingDragged.virtualPoint[hn].y,false)+px- cs.mapXi(primBeingDragged.virtualPoint[hn].x, primBeingDragged.virtualPoint[hn].y,false); } primBeingDragged.virtualPoint[handleBeingDragged].y=cs.unmapYsnap(ymm); primBeingDragged.setChanged(true); } }
12,048
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
SelectionActions.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/SelectionActions.java
package net.sourceforge.fidocadj.circuit.controllers; import java.util.*; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.circuit.model.ProcessElementsInterface; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; import net.sourceforge.fidocadj.primitives.PrimitiveMacro; /** SelectionActions: contains a controller which handles those actions which involve selection operations or which apply to selected elements. The actions proposed by this class involve selected elements. However, no action proposes a change of the characteristics of the elements, at least directly. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2015-2023 by Davide Bucci </pre> */ public class SelectionActions { private final DrawingModel dmp; /** Construct the controller and associates it to a given model. @param pp the model to be employed. */ public SelectionActions(DrawingModel pp) { dmp=pp; } /** Get the first selected primitive @return the selected primitive, null if none. */ public GraphicPrimitive getFirstSelectedPrimitive() { for (GraphicPrimitive g: dmp.getPrimitiveVector()) { if (g.getSelected()) { return g; } } return null; } /** Apply an action to selected elements contained in the model. @param tt the method containing the action to be performed */ public void applyToSelectedElements(ProcessElementsInterface tt) { for (GraphicPrimitive g:dmp.getPrimitiveVector()){ if (g.getSelected()) { tt.doAction(g); } } } /** Get an array describing the state of selection of the objects. @return a vector containing Boolean objects with the selection states of all objects in the database. */ public List<Boolean> getSelectionStateVector() { List<Boolean> v = new Vector<Boolean>(dmp.getPrimitiveVector().size()); for(GraphicPrimitive g : dmp.getPrimitiveVector()) { v.add(Boolean.valueOf(g.getSelected())); } return v; } /** Select/deselect all primitives. @param state true if you want to select, false for deselect. */ public void setSelectionAll(boolean state) { for (GraphicPrimitive g: dmp.getPrimitiveVector()) { g.setSelected(state); } } /** Sets the state of the objects in the database according to the given vector. @param v the vector containing the selection state of elements */ public void setSelectionStateVector(List<Boolean> v) { int i=0; for(GraphicPrimitive g : dmp.getPrimitiveVector()) { g.setSelected(v.get(i++).booleanValue()); } } /** Determine if only one primitive has been selected @return true if only one primitive is selected, false otherwise (which means that either more than several primitives or no primitive are selected). */ public boolean isUniquePrimitiveSelected() { boolean isUnique=true; boolean hasFound=false; for (GraphicPrimitive g: dmp.getPrimitiveVector()) { if (g.getSelected()) { if(hasFound) { isUnique = false; } hasFound = true; } } return hasFound && isUnique; } /** Determine if the selection can be splitted @return true if the selection contains at least a macro, or some of its elements have a name or a value (which are separated). */ public boolean selectionCanBeSplitted() { for (GraphicPrimitive g: dmp.getPrimitiveVector()) { if (g.getSelected() && (g instanceof PrimitiveMacro || g.hasName() || g.hasValue())) { return true; } } return false; } /** Obtain a string containing all the selected elements. @param extensions true if FidoCadJ extensions should be used. @param pa the parser controller. @return the string. */ public StringBuffer getSelectedString(boolean extensions, ParserActions pa) { StringBuffer s=new StringBuffer("[FIDOCAD]\n"); s.append(pa.registerConfiguration(extensions)); for (GraphicPrimitive g: dmp.getPrimitiveVector()){ if(g.getSelected()) { s.append(g.toString(extensions)); } } return s; } }
5,362
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
UndoActions.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/UndoActions.java
package net.sourceforge.fidocadj.circuit.controllers; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.circuit.HasChangedListener; import net.sourceforge.fidocadj.globals.FileUtils; import net.sourceforge.fidocadj.undo.UndoState; import net.sourceforge.fidocadj.undo.UndoManager; import net.sourceforge.fidocadj.undo.LibraryUndoListener; import net.sourceforge.fidocadj.undo.UndoActorListener; /** UndoActions: perform undo operations. Since some parsing operations are to be done, this class requires the ParserActions controller. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2007-2023 by Davide Bucci </pre> */ public class UndoActions implements UndoActorListener { private final ParserActions pa; // Undo manager private final UndoManager um; // Database of the temporary directories private final List<String> tempDir; // Maximum number of levels to be retained for undo operations. private static final int MAX_UNDO=100; // A drawing modification flag. If true, there are unsaved changes. private boolean isModified; private String tempLibraryDirectory=""; // Listeners private LibraryUndoListener libraryUndoListener; private HasChangedListener cl; /** Public constructor. @param a a parser controller (undo snapshots are kept in text format). */ public UndoActions(ParserActions a) { pa=a; um=new UndoManager(MAX_UNDO); libraryUndoListener=null; tempDir=new Vector<String>(); cl =null; } /** Undo the last editing action */ public void undo() { UndoState r = (UndoState)um.undoPop(); // Check if it is an operation involving libraries. if(um.isNextOperationOnALibrary() && libraryUndoListener!=null) { libraryUndoListener.undoLibrary(r.libraryDir); } if(!"".equals(r.text)) { StringBuffer s=new StringBuffer(r.text); pa.parseString(s); } isModified = r.isModified; pa.openFileName = r.fileName; if(cl!=null) { cl.somethingHasChanged(); } } /** Redo the last undo action */ public void redo() { UndoState r = (UndoState)um.undoRedo(); if(r.libraryOperation && libraryUndoListener!=null) { libraryUndoListener.undoLibrary(r.libraryDir); } if(!"".equals(r.text)) { StringBuffer s=new StringBuffer(r.text); pa.parseString(s); } isModified = r.isModified; pa.openFileName = r.fileName; if(cl!=null) { cl.somethingHasChanged(); } } /** Save the undo state, in the case an editing operation has been done on the drawing. */ public void saveUndoState() { UndoState s = new UndoState(); // In fact, the whole drawing is stored as a text. // In this way, we can easily store it on a string. s.text=pa.getText(true).toString(); s.isModified=isModified; s.fileName=pa.openFileName; s.libraryDir=tempLibraryDirectory; s.libraryOperation=false; um.undoPush(s); isModified = true; if(cl!=null) { cl.somethingHasChanged(); } } /** Save the undo state, in the case an editing operation has been performed on a library. @param t the library directory to be used. */ public void saveUndoLibrary(String t) { tempLibraryDirectory=t; UndoState s = new UndoState(); s.text=pa.getText(true).toString(); s.libraryDir=tempLibraryDirectory; s.isModified=isModified; s.fileName=pa.openFileName; s.libraryOperation=true; tempDir.add(t); um.undoPush(s); } /** Define a listener for a undo operation involving libraries. @param l the library undo listener. */ public void setLibraryUndoListener(LibraryUndoListener l) { libraryUndoListener = l; } /** Determine if the drawing has been modified. @return the state. */ public boolean getModified () { return isModified; } /** Set the drawing modified state. @param s the new state to be set. */ public void setModified (boolean s) { isModified = s; if(cl!=null) { cl.somethingHasChanged(); } } /** Set the listener of the state change. @param l the new listener. */ public void setHasChangedListener (HasChangedListener l) { cl = l; } /** Clear all temporary files and directories created by the library undo system. */ public void doTheDishes() { for (String fileName:tempDir) { try { FileUtils.deleteDirectory(new File(fileName)); } catch (IOException eE) { System.out.println("Warning: "+eE); } } } }
5,635
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
CopyPasteActions.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/CopyPasteActions.java
package net.sourceforge.fidocadj.circuit.controllers; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.globals.ProvidesCopyPasteInterface; /** CopyPasteActions: contains a controller which can perform copy and paste actions on a primitive database. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public class CopyPasteActions { private final DrawingModel dmp; private final EditorActions edt; private final ParserActions pa; private final UndoActions ua; private final SelectionActions sa; private final ProvidesCopyPasteInterface cpi; // True if elements should be shifted when copy/pasted private boolean shiftCP; /** Standard constructor. @param pp the drawing model. @param ed an editor controller. @param aa a parser controller (pasting implies parsing). @param s a selection controller @param u an undo controller. @param p an object with copy and paste methods available. */ public CopyPasteActions(DrawingModel pp, EditorActions ed, SelectionActions s, ParserActions aa, UndoActions u, ProvidesCopyPasteInterface p) { dmp=pp; edt=ed; pa=aa; sa=s; ua=u; cpi=p; shiftCP=false; } /** Paste from the system clipboard @param xstep if the shift should be applied, this is the x shift @param ystep if the shift should be applied, this is the y shift */ public void paste(int xstep, int ystep) { sa.setSelectionAll(false); try { pa.addString(new StringBuffer(cpi.pasteText()), true); } catch (Exception eE) { System.out.println("Warning: paste operation has gone wrong."); } if(shiftCP) { edt.moveAllSelected(xstep, ystep); } ua.saveUndoState(); dmp.setChanged(true); } /** Copy in the system clipboard all selected primitives. @param extensions specify if FCJ extensions should be applied. @param splitNonStandard specify if non standard macros should be split. */ public void copySelected(boolean extensions, boolean splitNonStandard) { StringBuffer s = sa.getSelectedString(extensions, pa); /* If we have to split non standard macros, we need to work on a temporary file, since the splitting works on the basis of the export technique. The temporary file will then be loaded in the clipboard. */ if (splitNonStandard) { s=pa.splitMacros(s, false); } cpi.copyText(s.toString()); } /** Check if the elements are to be shifted when copy/pasted. @return true if the elements are shifted when copy/pasted. */ public boolean getShiftCopyPaste() { return shiftCP; } /** Determines if the elements are to be shifted when copy/pasted @param s true if the elements should be shifted */ public void setShiftCopyPaste(boolean s) { shiftCP=s; } }
3,865
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
AddElements.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/AddElements.java
package net.sourceforge.fidocadj.circuit.controllers; import java.io.*; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; import net.sourceforge.fidocadj.primitives.PrimitivePCBPad; import net.sourceforge.fidocadj.primitives.PrimitivePCBLine; import net.sourceforge.fidocadj.primitives.PrimitiveRectangle; import net.sourceforge.fidocadj.primitives.PrimitiveBezier; import net.sourceforge.fidocadj.primitives.PrimitiveOval; import net.sourceforge.fidocadj.primitives.PrimitiveMacro; import net.sourceforge.fidocadj.primitives.PrimitiveConnection; import net.sourceforge.fidocadj.primitives.PrimitiveLine; /** AddElements: handle the dynamic insertion of graphic elements. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2015-2023 by Davide Bucci </pre> @author Davide Bucci */ public class AddElements { final private DrawingModel dmp; final private UndoActions ua; // Default sizes for PCB elements public int pcbPadSizeX; public int pcbPadSizeY; public int pcbPadStyle; public int pcbPadDrill; public int pcbThickness; /** Standard constructor. @param pp the drawing model object on which this controller operates. @param u an undo controller (if available) */ public AddElements(DrawingModel pp, UndoActions u) { dmp=pp; ua=u; pcbThickness = 5; pcbPadSizeX=5; pcbPadSizeY=5; pcbPadDrill=2; } /** Sets the default PCB pad size x. @param s the wanted size in logical units. */ public void setPcbPadSizeX(int s) { pcbPadSizeX=s; } /** Gets the default PCB pad size x. @return the x size in logical units. */ public int getPcbPadSizeX() { return pcbPadSizeX; } /** Sets the default PCB pad size y. @param s the wanted size in logical units. */ public void setPcbPadSizeY(int s) { pcbPadSizeY=s; } /** Gets the default PCB pad size y. @return the size in logical units. */ public int getPcbPadSizeY() { return pcbPadSizeY; } /** Sets the default PCB pad style. @param s the style. */ public void setPcbPadStyle(int s) { pcbPadStyle=s; } /** Gets the default PCB pad style. @return the style. */ public int getPcbPadStyle() { return pcbPadStyle; } /** Sets the default PCB pad drill size. @param s the wanted drill size, in logical units. */ public void setPcbPadDrill(int s) { pcbPadDrill=s; } /** Gets the default PCB pad drill size. @return the drill size, in logical units. */ public int getPcbPadDrill() { return pcbPadDrill; } /** Sets the default PCB track thickness. @param s the wanted thickness in logical units. */ public void setPcbThickness(int s) { pcbThickness=s; } /** Gets the default PCB track thickness. @return the track thickness in logical units. */ public int getPcbThickness() { return pcbThickness; } /** Add a connection primitive at the given point. @param x the x coordinate of the connection (logical) @param y the y coordinate of the connection (logical) @param currentLayer the layer on which the primitive should be put. */ public void addConnection(int x, int y, int currentLayer) { PrimitiveConnection g=new PrimitiveConnection(x, y, currentLayer, dmp.getTextFont(), dmp.getTextFontSize()); g.setMacroFont(dmp.getTextFont(), dmp.getTextFontSize()); dmp.addPrimitive(g, true, ua); } /** Introduce a line. You can introduce lines point by point, so you should keep track of the number of clicks you received (clickNumber). You must count the number of clicks and see if there is a modification needed on it (the return value). @param x coordinate of the click (logical) @param y coordinate of the click (logical) @param xpoly the array of x coordinates of points to be introduced. @param ypoly the array of x coordinates of points to be introduced. @param currentLayer the layer on which the primitive should be put. @param clickNumber the click number: 1 is the first click, 2 is the second (and final) one. @param altButton true if the alternate button is pressed (the introduction of lines is thus stopped). @return the new value of clickNumber. */ public int addLine(int x, int y, int[] xpoly, int[] ypoly, int currentLayer, int clickNumber, boolean altButton) { int cn=clickNumber; // clickNumber == 0 means that no line is being drawn xpoly[clickNumber] = x; ypoly[clickNumber] = y; if (clickNumber == 2 || altButton) { // Here we know the two points needed for creating // the line (clickNumber=2 means that). // The object is thus added to the database. PrimitiveLine g= new PrimitiveLine(xpoly[1], ypoly[1], xpoly[2], ypoly[2], currentLayer, false, false, 0,3,2,0, dmp.getTextFont(), dmp.getTextFontSize()); dmp.addPrimitive(g, true, ua); // Check if the user has clicked with the right button. // In this case, the introduction is stopped, or we continue // with a second line (segment) continuous to the one just // introduced. if(altButton) { cn = 0; } else { cn = 1; xpoly[1] = xpoly[2]; ypoly[1] = ypoly[2]; } } return cn; } /** Introduce the macro being edited at the given coordinate. @param x the x coordinate (logical). @param y the y coordinate (logical). @param sa the SelectionActions controller to handle the selection state of the whole drawing, which will be unselected. @param pe the current primitive being edited. @param macroKey the macro key of the macro to insert (maybe it should be obtained directly from pe). @return the new primitive being edited. */ public GraphicPrimitive addMacro(int x, int y, SelectionActions sa, GraphicPrimitive pe, String macroKey) { GraphicPrimitive primEdit=pe; try { // Here we add a macro. There is a remote risk that the macro // we are inserting contains an error. This is not something // which would happen frequently, since if the macro is in the // library this means it is available, but we need to use // the block try anyway. sa.setSelectionAll(false); int orientation = 0; boolean mirror = false; if (primEdit instanceof PrimitiveMacro) { orientation = ((PrimitiveMacro)primEdit).getOrientation(); mirror = ((PrimitiveMacro)primEdit).isMirrored(); } dmp.addPrimitive(new PrimitiveMacro(dmp.getLibrary(), dmp.getLayers(), x, y, macroKey,"", x+10, y+5, "", x+10, y+10, dmp.getTextFont(), dmp.getTextFontSize(), orientation, mirror), true, ua); primEdit=null; } catch (IOException gG) { // A simple error message on the console will be enough System.out.println(gG); } return primEdit; } /** Introduce an ellipse. You can introduce ellipses with two clicks, so you should keep track of the number of clicks you received (clickNumber). You must count the number of clicks and see if there is a modification needed on it (the return value). @param x coordinate of the click (logical). @param ty coordinate of the click (logical). @param xpoly the array of x coordinates of points to be introduced. @param ypoly the array of x coordinates of points to be introduced. @param currentLayer the layer on which the primitive should be put. @param clickNumber the click number: 1 is the first click, 2 is the second (and final) one. @param isCircle if true, force the ellipse to be a circle @return the new value of clickNumber. */ public int addEllipse(int x, int ty, int xpoly[], int ypoly[], int currentLayer, int clickNumber, boolean isCircle) { int y=ty; int cn=clickNumber; if(isCircle) { y=ypoly[1]+x-xpoly[1]; } // clickNumber == 0 means that no ellipse is being drawn xpoly[clickNumber] = x; ypoly[clickNumber] = y; if (cn == 2) { PrimitiveOval g=new PrimitiveOval(xpoly[1], ypoly[1], xpoly[2], ypoly[2], false, currentLayer,0, dmp.getTextFont(), dmp.getTextFontSize()); dmp.addPrimitive(g, true, ua); cn = 0; } return cn; } /** Introduce a Bézier curve. You can introduce this with four clicks, so you should keep track of the number of clicks you received (clickNumber). You must count the number of clicks and see if there is a modification needed on it (the return value). In other words, when using this method, you are responsible of storing this value somewhere and providing it any time you need to call addBezier again. @param x coordinate of the click (logical) @param y coordinate of the click (logical) @param xpoly the array of x coordinates of points to be introduced. @param ypoly the array of x coordinates of points to be introduced. @param currentLayer the layer on which the primitive should be put. @param clickNumber the click number: 1 is the first click, 2 is the second one, and so on... @return the new value of clickNumber. */ public int addBezier(int x, int y, int xpoly[], int ypoly[], int currentLayer, int clickNumber) { int cn=clickNumber; // clickNumber == 0 means that no bezier is being drawn xpoly[clickNumber] = x; ypoly[clickNumber] = y; // a polygon definition is ended with a double click if (clickNumber == 4) { PrimitiveBezier g=new PrimitiveBezier(xpoly[1], ypoly[1], xpoly[2], ypoly[2], xpoly[3], ypoly[3], xpoly[4], ypoly[4], currentLayer, false, false, 0,3,2,0, dmp.getTextFont(), dmp.getTextFontSize()); dmp.addPrimitive(g, true, ua); cn = 0; } return cn; } /** Introduce a rectangle. You can introduce this with two clicks, so you should keep track of the number of clicks you received (clickNumber). You must count the number of clicks and see if there is a modification needed on it (the return value). @param x coordinate of the click (logical). @param ty coordinate of the click (logical). @param xpoly the array of x coordinates of points to be introduced. @param ypoly the array of x coordinates of points to be introduced. @param currentLayer the layer on which the primitive should be put. @param clickNumber the click number: 1 is the first click, 2 is the second (and final) one. @param isSquare force the rectangle to be a square. @return the new value of clickNumber. */ public int addRectangle(int x, int ty, int xpoly[], int ypoly[], int currentLayer, int clickNumber, boolean isSquare) { int y=ty; int cn=clickNumber; if(isSquare) { y=ypoly[1]+x-xpoly[1]; } // clickNumber == 0 means that no rectangle is being drawn. xpoly[clickNumber] = x; ypoly[clickNumber] = y; if (cn == 2) { // The second click ends the rectangle introduction. // We thus create the primitive and store it. PrimitiveRectangle g=new PrimitiveRectangle(xpoly[1], ypoly[1], xpoly[2], ypoly[2], false, currentLayer,0, dmp.getTextFont(), dmp.getTextFontSize()); dmp.addPrimitive(g, true, ua); cn = 0; } if (cn>=2) { cn = 0; } return cn; } /** Introduce a PCB line. You can introduce this with two clicks, so you should keep track of the number of clicks you received (clickNumber). You must count the number of clicks and see if there is a modification needed on it (the return value). @param x coordinate of the click (logical). @param y coordinate of the click (logical). @param xpoly the array of x coordinates of points to be introduced. @param ypoly the array of x coordinates of points to be introduced. @param currentLayer the layer on which the primitive should be put. @param clickNumber the click number: 1 is the first click, 2 is the second (and final) one. @param altButton if true, the introduction of PCBlines should be stopped. @param thickness the thickness of the PCB line. @return the new value of clickNumber. */ public int addPCBLine(int x, int y, int xpoly[], int ypoly[], int currentLayer, int clickNumber, boolean altButton, float thickness) { int cn=clickNumber; // clickNumber == 0 means that no pcb line is being drawn xpoly[cn] = x; ypoly[cn] = y; if (cn == 2|| altButton) { // Here is the end of the PCB line introduction: we create the // primitive. final PrimitivePCBLine g=new PrimitivePCBLine(xpoly[1], ypoly[1], xpoly[2], ypoly[2], thickness, currentLayer, dmp.getTextFont(), dmp.getTextFontSize()); dmp.addPrimitive(g, true,ua); // Check if the user has clicked with the right button. if(altButton) { // We stop the PCB line here cn = 0; } else { // We then make sort that a new PCB line will be beginning // exactly at the same coordinates at which the previous // one was stopped. cn = 1; xpoly[1] = xpoly[2]; ypoly[1] = ypoly[2]; } } return cn; } /** Introduce a new PCB pad. @param x coordinate of the click (logical). @param y coordinate of the click (logical). @param currentLayer the layer on which the primitive should be put. */ public void addPCBPad(int x, int y, int currentLayer) { final PrimitivePCBPad g=new PrimitivePCBPad(x, y, pcbPadSizeX, pcbPadSizeY, pcbPadDrill, pcbPadStyle, currentLayer, dmp.getTextFont(), dmp.getTextFontSize()); dmp.addPrimitive(g, true, ua); } }
17,717
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitivesParInterface.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/PrimitivesParInterface.java
package net.sourceforge.fidocadj.circuit.controllers; /** PrimitivesParInterface specifies some actions useful to modify characteristics of primitives. They are usually provided by the editor component. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 by Davide Bucci </pre> */ public interface PrimitivesParInterface { /** Selects the closest object to the given point (in logical coordinates) and pops up a dialog for the editing of its Param_opt. @param x the x logical coordinate of the point used for the selection @param y the y logical coordinate of the point used for the selection */ void selectAndSetProperties(int x,int y); /** Shows a dialog which allows the user modify the parameters of a given primitive. If more than one primitive is selected, modify only the layer of all selected primitives. */ void setPropertiesForPrimitive(); /** Show a popup menu representing the actions that can be done on the selected context. @param x the x coordinate where the popup menu should be put @param y the y coordinate where the popup menu should be put */ void showPopUpMenu(int x, int y); /** Increases or decreases the zoom by a step of 33% @param increase if true, increase the zoom, if false decrease @param x coordinate to which center the viewport (screen coordinates) @param y coordinate to which center the viewport (screen coordinates) @param rate amount the zoom must be multiplied. Must be >1.0 */ void changeZoomByStep(boolean increase, int x, int y, double rate); /** Makes sure the object gets focus. */ void getFocus(); /** Forces a repaint event. */ void forcesRepaint(); /** Forces a repaint. @param x the x leftmost corner of the dirty region to repaint. @param y the y leftmost corner of the dirty region to repaint. @param width the width of the dirty region. @param height the height of the dirty region. */ void forcesRepaint(int x, int y, int width, int height); /** Activate and sets an evidence rectangle which will be put on screen at the next redraw. All sizes are given in pixel. @param lx the x coordinate of the left top corner @param ly the y coordinate of the left top corner @param w the width of the rectangle @param h the height of the rectangle */ void setEvidenceRect(int lx, int ly, int w, int h); }
3,238
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ElementsEdtActions.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/controllers/ElementsEdtActions.java
package net.sourceforge.fidocadj.circuit.controllers; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.layers.StandardLayers; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; import net.sourceforge.fidocadj.primitives.PrimitiveComplexCurve; import net.sourceforge.fidocadj.primitives.PrimitivePolygon; import net.sourceforge.fidocadj.primitives.PrimitiveAdvText; import net.sourceforge.fidocadj.primitives.PrimitiveMacro; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.toolbars.ChangeSelectionListener; /** ElementsEdtActions: contains a controller for adding/modifying elements to a drawing model. In the jargon of this file "editing primitive" means the one which is currently being entered if an editing action is in place. For example, if the user wants to introduce a new macro, it will be the new macro which is shown in green, following the mouse pointer. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2020 by Davide Bucci </pre> @author Davide Bucci */ public class ElementsEdtActions { protected final DrawingModel dmp; protected final UndoActions ua; protected final EditorActions edt; final SelectionActions sa; final AddElements ae; private ChangeSelectionListener selectionListener; // The current layer being edited public int currentLayer; // Array used to keep track of the insertion of elements which require // more than one click (logical coordinates). Index begins at 1 to // clickNumber. public int[] xpoly; public int[] ypoly; // used when entering a macro public String macroKey; // Nuber of clicks done when entering an object. public int clickNumber; // The primitive being edited public transient GraphicPrimitive primEdit; // editing action being done public int actionSelected; // Track wether an editing action is being made. public boolean successiveMove; // TO IMPROVE: this must be synchronized with the value in PrimitivePolygon // Maximum number of polygon vertices public static final int NPOLY=256; // Selection states public static final int NONE = 0; public static final int SELECTION = 1; public static final int ZOOM = 2; public static final int HAND = 3; public static final int LINE = 4; public static final int TEXT = 5; public static final int BEZIER = 6; public static final int POLYGON = 7; public static final int ELLIPSE = 8; public static final int RECTANGLE = 9; public static final int CONNECTION = 10; public static final int PCB_LINE = 11; public static final int PCB_PAD = 12; public static final int MACRO = 13; public static final int COMPLEXCURVE = 14; protected PrimitivesParInterface primitivesParListener; /** Standard constructor: provide the database class. @param pp the Model containing the database. @param s the selection controller. @param u the Undo controller, to ease undo operations. @param e the Basic editing controller, for handling selection operations. */ public ElementsEdtActions (DrawingModel pp, SelectionActions s, UndoActions u, EditorActions e) { dmp=pp; ua=u; ae=new AddElements(dmp,ua); edt=e; sa=s; xpoly = new int[NPOLY]; ypoly = new int[NPOLY]; currentLayer=0; primEdit = null; selectionListener=null; primitivesParListener=null; actionSelected = SELECTION; } /** Set the change selection listener. The selection listener is not called when the selection state is changed manually by means of the setActionSelected method, but it is instead when it is internally changed by the ElementEdtActions class (such as with a mouse operation). @param c the new selection listener. */ public void setChangeSelectionListener(ChangeSelectionListener c) { selectionListener=c; } /** Get the current {@link AddElements} controller. @return the current controller. */ public AddElements getAddElements() { return ae; } /** Set the listener for showing popups and editing actions which are platform-dependent. @param l the listener to be employed. */ public void setPrimitivesParListener(PrimitivesParInterface l) { primitivesParListener=l; } /** Determine wether the current primitive being added is a macro. @return true if the current primitive (i.e. the one who is in green under the mouse cursor) is a macro. */ public boolean isEnteringMacro() { return primEdit instanceof PrimitiveMacro; } /** Chooses the entering state. @param s the new state to be set. @param macro the current macro key if a applicable, which means that a macro is being entered. */ public void setState(int s, String macro) { actionSelected=s; clickNumber=0; successiveMove=false; macroKey=macro; } /** Rotate the macro being edited around its first control point (90 degrees clockwise rotation). */ public void rotateMacro() { if(primEdit instanceof PrimitiveMacro) { primEdit.rotatePrimitive(false, primEdit.getFirstPoint().x, primEdit.getFirstPoint().y); } } /** Mirror the macro being edited around the x coordinate of the first control point. */ public void mirrorMacro() { if(primEdit instanceof PrimitiveMacro) { primEdit.mirrorPrimitive(primEdit.getFirstPoint().x); } } /** Here we analyze and handle the mouse click. The behaviour is different depending on which selection state we are. @param cs the current coordinate mapping @param x the x coordinate of the click (in screen coordinates) @param y the y coordinate of the click (in screen coordinates) @param button3 true if the alternate button has been pressed @param toggle if true, circle the selection state or activate alternate input method (i.e. ellipses are forced to be circles, rectangles squares and so on...) @param doubleClick true if a double click has to be processed @return true if a repaint is needed. */ public boolean handleClick(MapCoordinates cs, int x, int y, boolean button3, boolean toggle, boolean doubleClick) { boolean repaint=false; if(clickNumber>NPOLY-1) { clickNumber=NPOLY-1; } // We need to differentiate this case since when we are entering a // macro, primEdit already contains some useful hints about the // orientation and the mirroring, so we need to keep it. if (actionSelected !=MACRO) { primEdit = null; } if(button3 && actionSelected==MACRO) { actionSelected=SELECTION; if(selectionListener!=null) { selectionListener.setSelectionState(actionSelected,""); } primEdit = null; return true; } // Right-click in certain cases shows the parameters dialog. if(button3 && actionSelected!=NONE && actionSelected!=SELECTION && actionSelected!=ZOOM && actionSelected!=TEXT && primitivesParListener!=null) { primitivesParListener.selectAndSetProperties(x,y); return false; } switch(actionSelected) { // No action: ignore case NONE: clickNumber = 0; break; // Selection state case SELECTION: clickNumber = 0; // Double click shows the Parameters dialog. if(doubleClick&&primitivesParListener!=null) { primitivesParListener.setPropertiesForPrimitive(); break; } else if(button3 && primitivesParListener!=null) { // Show a pop up menu if the user does a right-click primitivesParListener.showPopUpMenu(x,y); } else { // Select elements edt.handleSelection(cs, x, y, toggle); } break; // Zoom state case ZOOM: if(primitivesParListener!=null) { primitivesParListener.changeZoomByStep(!button3, x,y,1.5); } break; // Put a connection (easy: just one click is needed) case CONNECTION: ae.addConnection(cs.unmapXsnap(x),cs.unmapXsnap(y), currentLayer); repaint=true; break; // Put a PCB pad (easy: just one click is needed) case PCB_PAD: // Add a PCB pad primitive at the given point ae.addPCBPad(cs.unmapXsnap(x), cs.unmapYsnap(y), currentLayer); repaint=true; break; // Add a line: two clicks needed case LINE: if (doubleClick) { clickNumber=0; } else { successiveMove=false; clickNumber=ae.addLine(cs.unmapXsnap(x), cs.unmapYsnap(y), xpoly, ypoly, currentLayer, ++clickNumber, button3); repaint=true; } break; // Add a text line: just one click is needed case TEXT: if (doubleClick && primitivesParListener!=null) { primitivesParListener.selectAndSetProperties(x,y); break; } PrimitiveAdvText newtext = new PrimitiveAdvText(cs.unmapXsnap(x), cs.unmapYsnap(y), 3,4,dmp.getTextFont(),0,0, "String", currentLayer); sa.setSelectionAll(false); dmp.addPrimitive(newtext, true, ua); newtext.setSelected(true); repaint=true; if(primitivesParListener!=null) { primitivesParListener.setPropertiesForPrimitive(); } break; // Add a Bézier polygonal curve: we need four clicks. case BEZIER: repaint=true; if(button3) { clickNumber = 0; } else { if(doubleClick) { successiveMove=false; } clickNumber=ae.addBezier(cs.unmapXsnap(x), cs.unmapYsnap(y), xpoly, ypoly, currentLayer, ++clickNumber); } break; // Insert a polygon: continue until double click. case POLYGON: // a polygon definition is ended with a double click if (doubleClick) { PrimitivePolygon poly=new PrimitivePolygon(false, currentLayer,0, dmp.getTextFont(), dmp.getTextFontSize()); for(int i=1; i<=clickNumber; ++i) { poly.addPoint(xpoly[i],ypoly[i]); } dmp.addPrimitive(poly, true,ua); clickNumber = 0; repaint=true; break; } else { ++ clickNumber; successiveMove=false; // clickNumber == 0 means that no polygon is being drawn // prevent that we exceed the number of allowed points if (clickNumber==NPOLY) { return false; } xpoly[clickNumber] = cs.unmapXsnap(x); ypoly[clickNumber] = cs.unmapYsnap(y); } break; // Insert a complex curve: continue until double click. case COMPLEXCURVE: // a polygon definition is ended with a double click if (doubleClick) { PrimitiveComplexCurve compc=new PrimitiveComplexCurve(false, false, currentLayer, false, false, 0, 3, 2, 0, dmp.getTextFont(), dmp.getTextFontSize()); for(int i=1; i<=clickNumber; ++i) { compc.addPoint(xpoly[i],ypoly[i]); } dmp.addPrimitive(compc, true,ua); clickNumber = 0; repaint=true; } else { ++ clickNumber; successiveMove=false; // prevent that we exceed the number of allowed points if (clickNumber==NPOLY) { return false; } // clickNumber == 0 means that no polygon is being drawn xpoly[clickNumber] = cs.unmapXsnap(x); ypoly[clickNumber] = cs.unmapYsnap(y); } break; // Enter an ellipse: two clicks needed case ELLIPSE: // If control is hold, trace a circle successiveMove=false; clickNumber=ae.addEllipse(cs.unmapXsnap(x), cs.unmapYsnap(y), xpoly, ypoly, currentLayer, ++clickNumber, toggle&&clickNumber>0); repaint=true; break; // Enter a rectangle: two clicks needed case RECTANGLE: // If control is hold, trace a square successiveMove=false; clickNumber=ae.addRectangle(cs.unmapXsnap(x), cs.unmapYsnap(y), xpoly, ypoly, currentLayer, ++clickNumber, toggle&&clickNumber>0); repaint=true; break; // Insert a PCB line: two clicks needed. case PCB_LINE: if (doubleClick) { clickNumber = 0; break; } successiveMove=false; clickNumber = ae.addPCBLine(cs.unmapXsnap(x), cs.unmapYsnap(y), xpoly, ypoly, currentLayer, ++clickNumber, button3, ae.getPcbThickness()); repaint=true; break; // Enter a macro: just one click is needed. case MACRO: successiveMove=false; primEdit=ae.addMacro(cs.unmapXsnap(x), cs.unmapYsnap(y), sa, primEdit, macroKey); repaint=true; break; default: break; } return repaint; } /** Draws the current editing primitive. @param g the graphic context on which to draw. @param cs the current coordinate mapping system. */ public void drawPrimEdit(GraphicsInterface g, MapCoordinates cs) { if(primEdit!=null) { primEdit.draw(g, cs, StandardLayers.createEditingLayerArray()); } } /** Shows the clicks done by the user. @param g the graphic context where one should write. @param cs the current coordinate mapping. */ public void showClicks(GraphicsInterface g, MapCoordinates cs) { int x; int y; g.setColor(g.getColor().red()); // The data here begins at index 1, due to the internal construction. int mult=(int)Math.round(g.getScreenDensity()/112); g.applyStroke(2.0f*mult,0); for(int i=1; i<=clickNumber; ++i) { x = cs.mapXi(xpoly[i], ypoly[i], false); y = cs.mapYi(xpoly[i], ypoly[i], false); g.drawLine(x-15*mult, y, x+15*mult, y); g.drawLine(x, y-15*mult, x, y+15*mult); } } /** Get the current editing action (see the constants defined in this class) @return the current editing action. */ public int getSelectionState() { return actionSelected; } /** Set the current editing primitive. @param gp the current editing primitive. */ public void setPrimEdit(GraphicPrimitive gp) { primEdit=gp; } /** Get the current editing primitive. @return the current editing primitive. */ public GraphicPrimitive getPrimEdit() { return primEdit; } }
18,110
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/model/package-info.java
/** <p> The package circuit.model contains model.DrawingModel class, which is the database of the graphical objects composing the drawing.</p> */ package net.sourceforge.fidocadj.circuit.model;
196
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DrawingModel.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/model/DrawingModel.java
package net.sourceforge.fidocadj.circuit.model; import java.util.*; import net.sourceforge.fidocadj.circuit.ImageAsCanvas; import net.sourceforge.fidocadj.circuit.controllers.UndoActions; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; import net.sourceforge.fidocadj.primitives.MacroDesc; import net.sourceforge.fidocadj.primitives.PrimitiveMacro; /** Database of the FidoCadJ drawing. This is the "model" in the model/view/controller pattern. Offers methods to modify its contents, but they are relatively low level and database-oriented. More high-level operations can be done via the controllers operating on this class. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class DrawingModel { // ************* DRAWING ************* // Array used to determine which layer is used in the drawing. public boolean[] layersUsed; // Higher priority layer used in the drawing. public int maxLayer; // True if only pads should be drawn. public boolean drawOnlyPads; // Positive if during the redraw step only a particular layer should be // drawn public int drawOnlyLayer; public ImageAsCanvas imgCanvas; // Font and size to be used for the text associated to the macros. private String macroFont; private int macroFontSize; // True if the drawing characteristics have been modified. This implies // that during the first redraw a in-depth calculation of all coordinates // will be done. For performance reasons, this is indeed done only when // necessary. public boolean changed; // TODO: should be private // ******* PRIMITIVE DATABASE ******** // List containing all primitives in the drawing. private List<GraphicPrimitive> primitiveVector; // List containing all layers used in the drawing. public List<LayerDesc> layerV; // Library of macros loaded. private Map<String, MacroDesc> library; /** The standard constructor. Not so much interesting, apart for the fact that it allocates memory of a few internal objects and reset all state flags. */ public DrawingModel() { setPrimitiveVector(new Vector<GraphicPrimitive>(25)); layerV=new Vector<LayerDesc>(LayerDesc.MAX_LAYERS); library=new TreeMap<String, MacroDesc>(); macroFont = "Courier New"; imgCanvas= new ImageAsCanvas(); drawOnlyPads=false; drawOnlyLayer=-1; layersUsed = new boolean[LayerDesc.MAX_LAYERS]; changed=true; } /** Apply an action to all elements contained in the model. @param tt the method containing the action to be performed */ public void applyToAllElements(ProcessElementsInterface tt) { for (GraphicPrimitive g:primitiveVector){ tt.doAction(g); } } /** Get the layer description vector @return a vector of LayerDesc describing layers. */ public List<LayerDesc> getLayers() { return layerV; } /** Set the layer description vector. @param v a vector of LayerDesc describing layers. */ public void setLayers(final List<LayerDesc> v) { layerV=v; applyToAllElements(new ProcessElementsInterface() { public void doAction(GraphicPrimitive g) { if (g instanceof PrimitiveMacro) { ((PrimitiveMacro) g).setLayers(v); } } }); changed=true; } /** Get the current library @return a map String/String describing the current library. */ public Map<String, MacroDesc> getLibrary() { return library; } /** Specify the current library. @param l the new library (a String/String hash table) */ public void setLibrary(Map<String, MacroDesc> l) { library=l; changed=true; } /** Resets the current library. */ public void resetLibrary() { setLibrary(new TreeMap<String, MacroDesc>()); changed=true; } /** Add a graphic primitive. @param p the primitive to be added. @param sort if true, sort the primitive layers @param ua if different from <pre>null</pre>, the operation will be undoable. */ public void addPrimitive(GraphicPrimitive p, boolean sort, UndoActions ua) { // The primitive database MUST be ordered. The idea is that we insert // primitives without ordering them and then we call a sorter. synchronized(this) { getPrimitiveVector().add(p); // We check if the primitives should be sorted depending of // their layer // If there are more than a few primitives to insert, it is wise to // sort only once, at the end of the insertion process. if (sort) { sortPrimitiveLayers(); } // Check if it should be undoable. if (ua!=null) { ua.saveUndoState(); ua.setModified(true); // We now have to track that something has changed. This // forces all the // caching system used by the drawing routines to be refreshed. changed=true; } } } /** Set the font of all elements. @param f the font name @param tsize the size @param ua the undo controller or null if not useful. */ public void setTextFont(String f, int tsize, UndoActions ua) { int size=tsize; macroFont=f; macroFontSize = size; for (GraphicPrimitive g:getPrimitiveVector()) { g.setMacroFont(f, size); } changed=true; if(ua!=null) { ua.setModified(true); } } /** Get the font of all macros. @return the font name */ public String getTextFont() { return macroFont; } /** Get the size of the font used for all macros. @return the font name */ public int getTextFontSize() { if(getPrimitiveVector().isEmpty()) { return macroFontSize; } // TODO: not very elegant piece of code. // Basically, we grab the settings of the very first object stored. int size=((GraphicPrimitive)getPrimitiveVector().get(0)) .getMacroFontSize(); if(size<=0) { size=1; } macroFontSize=size; return macroFontSize; } /** Performs a sort of the primitives on the basis of their layer. The sorting metod adopted is the Shell sort. By the practical point of view, this seems to be rather good even for large drawings. This is because the primitive list is always more or less already ordered. */ public void sortPrimitiveLayers() { int i; GraphicPrimitive g; maxLayer = 0; // Indexes int j; int k; int l; // Swap temporary variable GraphicPrimitive s; // Shell sort. This is a farly standard implementation for(l = getPrimitiveVector().size()/2; l>0; l/=2) { for(j = l; j< getPrimitiveVector().size(); ++j) { for(i=j-l; i>=0; i-=l) { if(((GraphicPrimitive)getPrimitiveVector().get(i+l)).layer>= ((GraphicPrimitive)getPrimitiveVector().get(i)).layer) { break; } else { // Swap s = (GraphicPrimitive)getPrimitiveVector().get(i); getPrimitiveVector().set(i, getPrimitiveVector().get(i+l)); getPrimitiveVector().set(i+l, s); } } } } // Since for sorting we need to analyze all the primitives in the // database, this is a good place to calculate which layers are // used. We thus start by resetting the array. maxLayer = -1; k=0; for (l=0; l<LayerDesc.MAX_LAYERS; ++l) { layersUsed[l] = false; for (i=k; i<getPrimitiveVector().size(); ++i) { g=(GraphicPrimitive)getPrimitiveVector().get(i); // We keep track of the maximum layer number used in the // drawing. if (g.layer>maxLayer) { maxLayer = g.layer; } if (g.containsLayer(l)) { layersUsed[l]=true; k=i; for (int z = 0; z<l; ++z) { layersUsed[z]=true; } break; } } } } /** Get the maximum layer which contains something. This value is updated after a redraw. This is tracked for efficiency reasons. @return the maximum layer number. */ public int getMaxLayer() { return maxLayer; } /** Returns true if the specified layer is contained in the schematic being drawn. The analysis is done when the schematics is created, so the results of this method are ready before the redraw step. @param l the number of the layer to be checked. @return true if the specified layer is contained in the drawing. */ public boolean containsLayer(int l) { return layersUsed[l]; } /** Returns true if there is no drawing in memory @return true if the drawing is empty. */ public boolean isEmpty() { return getPrimitiveVector().isEmpty(); } /** Set the change state of the class. Changed just means that we want to recalculate everything in deep during the following redraw. This is different from being "modified", since "modified" implies that the current drawing has not been saved yet. @param c if true, force a deep recalculation of all primitive parameters at the first redraw. */ public void setChanged(boolean c) { changed=c; } /** Obtains a vector containing all elements. @return the vector containing all graphical objects. */ public List<GraphicPrimitive> getPrimitiveVector() { return primitiveVector; } /** Sets a vector containing all elements. @param primitiveVector the vector containing all graphical objects. */ public void setPrimitiveVector(List<GraphicPrimitive> primitiveVector) { this.primitiveVector = primitiveVector; } /** Specify that the drawing process should only draw holes of the pcb pad @param pd it is true if only holes should be drawn */ public void setDrawOnlyPads(boolean pd) { drawOnlyPads=pd; } /** Set the layer to be drawn. If it is negative, draw all layers. @param la the layer to be drawn. */ public void setDrawOnlyLayer(int la) { drawOnlyLayer=la; } }
11,962
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ProcessElementsInterface.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/circuit/model/ProcessElementsInterface.java
package net.sourceforge.fidocadj.circuit.model; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; /** Provides a general way to apply an action to a graphic element. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2015 by Davide Bucci </pre> */ public interface ProcessElementsInterface { /** Process the given graphic primitive and execute a generic action on it. @param g the graphic primitive to be processed. */ void doAction(GraphicPrimitive g); }
1,184
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DialogEditLayer.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/DialogEditLayer.java
package net.sourceforge.fidocadj.dialogs; import java.util.Vector; import android.app.Activity; import android.app.Dialog; import android.app.DialogFragment; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.SurfaceView; import android.widget.Button; import android.widget.TextView; import android.util.DisplayMetrics; import android.graphics.Color; import android.widget.SeekBar; import android.widget.EditText; import net.sourceforge.fidocadj.globals.*; import net.sourceforge.fidocadj.layers.*; import net.sourceforge.fidocadj.*; import net.sourceforge.fidocadj.graphic.android.ColorAndroid; import net.sourceforge.fidocadj.R; /** Allows to select the layer name, color and transparence. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014-2015 by Davide Bucci </pre> @author Davide Bucci */ public class DialogEditLayer extends DialogFragment implements SeekBar.OnSeekBarChangeListener { private Activity context; private Dialog dialog; private SeekBar colorRbar; private SeekBar colorGbar; private SeekBar colorBbar; private SeekBar colorAlphaBar; private SurfaceView preview; private EditText editLayerName; public int valueR; public int valueG; public int valueB; public int valueAlpha; private FidoEditor drawingPanel; private Vector<LayerDesc> layers; private int currentLayer; private View currentView; /** Creator. @param cl the current layer. @param v the current view. */ public DialogEditLayer(int cl, View v) { currentLayer=cl; currentView=v; } /** Called when the dialog is being create, this method updates the user interface. @param savedInstanceState the state of the instance (not used). */ @Override public Dialog onCreateDialog(Bundle savedInstanceState) { context = getActivity(); dialog = new Dialog(context); dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_edit_layer); // Get the bars corresponding to the R,G,B and alpha coefficients. colorRbar=(SeekBar)dialog.findViewById(R.id.color_r); colorGbar=(SeekBar)dialog.findViewById(R.id.color_g); colorBbar=(SeekBar)dialog.findViewById(R.id.color_b); colorAlphaBar=(SeekBar)dialog.findViewById(R.id.color_alpha); // Get the preview area. preview=(SurfaceView)dialog.findViewById(R.id.preview_surface); editLayerName = (EditText)dialog.findViewById(R.id.edit_layername); // Get the drawing panel. drawingPanel = (FidoEditor)context.findViewById(R.id.drawingPanel); // Get the list of the layers. layers = drawingPanel.getDrawingModel().getLayers(); //currentLayer=drawingPanel.eea.currentLayer; // Set the listeners. colorRbar.setOnSeekBarChangeListener(this); colorGbar.setOnSeekBarChangeListener(this); colorBbar.setOnSeekBarChangeListener(this); colorAlphaBar.setOnSeekBarChangeListener(this); // Get the current layer data and set the cursors and the info colorRbar.setProgress(layers.get(currentLayer).getColor().getRed()); colorGbar.setProgress(layers.get(currentLayer).getColor().getGreen()); colorBbar.setProgress(layers.get(currentLayer).getColor().getBlue()); colorAlphaBar.setProgress( (int)(layers.get(currentLayer).getAlpha()*255.0)); editLayerName.setText(layers.get(currentLayer).getDescription()); // Get the Ok button and add a click handler. Button okButton=(Button)dialog.findViewById( R.id.dialog_edit_layer_ok); okButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Save the current state. layers.get(currentLayer).setColor( new ColorAndroid( Color.rgb(colorRbar.getProgress(), colorGbar.getProgress(), colorBbar.getProgress()))); layers.get(currentLayer).setDescription( editLayerName.getText().toString()); layers.get(currentLayer).setAlpha( (float)colorAlphaBar.getProgress()/255.0f); dialog.dismiss(); currentView.invalidate(); } }); // Get the Cancel button and add a click handler. Button cancelButton=(Button)dialog.findViewById( R.id.dialog_edit_layer_cancel); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); return dialog; } /** This method is called when a slider is operated. In our case, this happens when the user changes a value for red, green, blue or alpha. */ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // Determine which color bar is being manipulated. if(seekBar.equals(colorRbar)) { valueR=progress; } else if(seekBar.equals(colorGbar)) { valueG=progress; } else if(seekBar.equals(colorBbar)) { valueB=progress; } else { valueAlpha=progress; } preview.setBackgroundColor(Color.argb(valueAlpha, valueR, valueG, valueB)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }
6,552
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/package-info.java
/** All the dialog windows (and related ancillary classes) of FidoCadJ. */ package net.sourceforge.fidocadj.dialogs;
121
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DialogParameters.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/DialogParameters.java
package net.sourceforge.fidocadj.dialogs; import java.util.ArrayList; import java.util.List; import java.util.Vector; import android.widget.Toast; import android.app.Activity; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.Point; import android.os.Bundle; import android.text.InputFilter; import android.text.Spanned; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.View.OnClickListener; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.ScrollView; import android.widget.Space; import net.sourceforge.fidocadj.R; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.FontG; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.FidoEditor; import net.sourceforge.fidocadj.storage.StaticStorage; /** Allows to create a generic dialog, capable of displaying and let the user modify the parameters of a graphic primitive. The idea is that the dialog uses a ParameterDescripion vector which contains all the elements, their description as well as the type. Depending on the contents of the array, the window will be created automatically. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014-2015 by Dante Loi, Davide Bucci </pre> @author Dante Loi */ public class DialogParameters extends DialogFragment { private final static int DENSITY_LOW = 120; private final static int DENSITY_MEDIUM = 160; private final static int DENSITY_HIGH = 240; private final static int DENSITY_TV = 213; private final static int DENSITY_XHIGH = 320; private final static int DENSITY_XXHIGH = 480; private final static int DENSITY_XXXHIGH = 640; private final static int SYSTEM_UI_LAYOUT_FLAGS=1536; private static Vector<ParameterDescription> vec; private static boolean strict; private static Vector<LayerDesc> layers; // Sizes private int fieldWidth; private int fieldHeight; private int textSize; private int buttonWidth; private int buttonHeight; //Dialog border private static final int BORDER = 30; //maximum strings' length private static final int MAX_LEN = 200; // Maximum number of user interface elements of the same type present // in the dialog window. private static final int MAX_ELEMENTS = 10; // Text box array and counter private EditText etv[]; private int ec; // Check box array and counter private CheckBox cbv[]; private int cc; // Spinner array and counter private Spinner spv[]; private int sc; /** Get a ParameterDescription vector describing the characteristics modified by the user. @return a ParameterDescription vector describing each parameter. */ public Vector<ParameterDescription> getCharacteristics() { return vec; } /** Creates the dialog and passes its arguments to it. @param vec the vector containing the various parameters to be set. @param strict true if a strict FidoCAD compatibility is required. @param layers the vector describing the current layers. @return a new istance of DialogParameters. */ public static DialogParameters newInstance(Vector<ParameterDescription> vec, boolean strict, Vector<LayerDesc> layers) { DialogParameters dialog = new DialogParameters(); Bundle args = new Bundle(); args.putSerializable("vec", vec); args.putBoolean("strict", strict); args.putSerializable("layers", layers); dialog.setArguments(args); dialog.setRetainInstance(true); return dialog; } /** Create the user interface by processing all the parameters given during the construction of the class. @param savedInstanceState the saved instance state. @return the dialog containing the user interface. */ public Dialog onCreateDialog(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState == null){ vec = (Vector<ParameterDescription>) getArguments() .getSerializable("vec"); layers = (Vector<LayerDesc>) getArguments() .getSerializable("layers"); strict = getArguments().getBoolean("strict"); } else{ vec = (Vector<ParameterDescription>) savedInstanceState .getSerializable("vec"); layers = (Vector<LayerDesc>) savedInstanceState .getSerializable("layers"); strict = savedInstanceState.getBoolean("strict"); } final Activity context = getActivity(); final Dialog dialog = new Dialog(context); dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); dialog.getWindow().setSoftInputMode( WindowManager.LayoutParams .SOFT_INPUT_STATE_ALWAYS_HIDDEN); LinearLayout vv = new LinearLayout(context){ //VKB hiding, with a touch on the dialog. @Override public boolean onTouchEvent(MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_DOWN) { InputMethodManager imm = (InputMethodManager) context.getSystemService( Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getWindowToken(), SYSTEM_UI_LAYOUT_FLAGS); } return true; } }; vv.setOrientation(LinearLayout.VERTICAL); vv.setBackgroundColor(getResources(). getColor(R.color.background_white)); vv.setPadding(BORDER, BORDER, BORDER, BORDER); etv = new EditText[MAX_ELEMENTS]; cbv = new CheckBox[MAX_ELEMENTS]; spv = new Spinner[MAX_ELEMENTS]; ParameterDescription pd; ec = 0; cc = 0; sc = 0; //Setting of the dialog sizes. DisplayMetrics metrics = getResources().getDisplayMetrics(); int screenDensity = metrics.densityDpi; int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; setSizeByScreen(screenSize, screenDensity); //Filter for the Integer EditText, //allows to write only digit in the filtered fields. InputFilter filter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (!Character.isDigit(source.charAt(i))) { return ""; } } return null; } }; // We process all parameter passed. Depending on its type, a // corresponding interface element will be created. // A symmetrical operation is done when validating parameters. for (int ycount = 0; ycount < vec.size(); ++ycount) { pd = (ParameterDescription) vec.elementAt(ycount); LinearLayout vh = new LinearLayout(context); vh.setGravity(Gravity.FILL_HORIZONTAL); vh.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT); // We do not need to store label objects, since we do not need // to retrieve data from them. TextView lab = new TextView(context); lab.setTextColor(Color.BLACK); lab.setText(pd.description); lab.setPadding(0, 0, 10, 0); lab.setGravity(Gravity.CENTER); lab.setTextSize(textSize); if (!(pd.parameter instanceof Boolean)) vh.addView(lab); // Now, depending on the type of parameter we create interface // elements and we populate the dialog. if (pd.parameter instanceof PointG) { etv[ec] = new EditText(context); etv[ec].setTextColor(Color.BLACK); etv[ec].setBackgroundResource(R.drawable.field_background); Integer x = Integer.valueOf(((PointG) (pd.parameter)).x); etv[ec].setText(x.toString()); etv[ec].setMaxWidth(MAX_LEN); etv[ec].setLayoutParams( new LayoutParams(fieldWidth/2,fieldHeight)); etv[ec].setSingleLine(); etv[ec].setFilters(new InputFilter[]{filter}); etv[ec].setTextSize(textSize); vh.addView(etv[ec++]); etv[ec] = new EditText(context); Integer y = Integer.valueOf(((PointG) (pd.parameter)).y); etv[ec].setText(y.toString()); etv[ec].setTextColor(Color.BLACK); etv[ec].setBackgroundResource(R.drawable.field_background); etv[ec].setMaxWidth(MAX_LEN); etv[ec].setLayoutParams( new LayoutParams(fieldWidth/2,fieldHeight)); etv[ec].setSingleLine(); etv[ec].setFilters(new InputFilter[]{filter}); etv[ec].setTextSize(textSize); vh.addView(etv[ec++]); } else if (pd.parameter instanceof String) { etv[ec] = new EditText(context); etv[ec].setTextColor(Color.BLACK); etv[ec].setGravity(Gravity.FILL_HORIZONTAL| Gravity.CENTER_HORIZONTAL); etv[ec].setBackgroundResource(R.drawable.field_background); etv[ec].setText((String) (pd.parameter)); etv[ec].setMaxWidth(MAX_LEN); etv[ec].setLayoutParams( new LayoutParams(fieldWidth,fieldHeight)); etv[ec].setSingleLine(); etv[ec].setTextSize(textSize); // If we have a String text field in the first position, its // contents should be evidenced, since it is supposed to be // the most important field (e.g. for the AdvText primitive) if (ycount == 0) etv[ec].selectAll(); vh.addView(etv[ec++]); } else if (pd.parameter instanceof Boolean) { cbv[cc] = new CheckBox(context); cbv[cc].setText(pd.description); cbv[cc].setTextColor(Color.BLACK); cbv[cc].setLayoutParams( new LayoutParams(fieldWidth,fieldHeight)); cbv[cc].setChecked(((Boolean) (pd.parameter)).booleanValue()); cbv[cc].setTextSize(textSize); vh.addView(cbv[cc++]); } else if (pd.parameter instanceof Integer) { etv[ec] = new EditText(context); etv[ec].setTextColor(Color.BLACK); etv[ec].setBackgroundResource(R.drawable.field_background); etv[ec].setText(((Integer) pd.parameter).toString()); etv[ec].setMaxWidth(MAX_LEN); etv[ec].setLayoutParams( new LayoutParams(fieldWidth,fieldHeight)); etv[ec].setSingleLine(); etv[ec].setFilters(new InputFilter[]{filter}); etv[ec].setTextSize(textSize); vh.addView(etv[ec++]); } else if (pd.parameter instanceof Float) { etv[ec] = new EditText(context); etv[ec].setTextColor(Color.BLACK); etv[ec].setBackgroundResource(R.drawable.field_background); int dummy = java.lang.Math.round((Float) pd.parameter); etv[ec].setText(" "+dummy); etv[ec].setMaxWidth(MAX_LEN); etv[ec].setLayoutParams( new LayoutParams(fieldWidth,fieldHeight)); etv[ec].setSingleLine(); etv[ec].setTextSize(textSize); vh.addView(etv[ec++]); } else if (pd.parameter instanceof FontG) { spv[sc] = new Spinner(context); String[] s = {"Normal","Italic","Bold"}; ArrayAdapter<String> adapter = new ArrayAdapter<String> ( context, android.R.layout.simple_spinner_item , s); spv[sc].setAdapter(adapter); spv[sc].setBackgroundResource(R.drawable.field_background); spv[sc].setLayoutParams( new LayoutParams(fieldWidth,fieldHeight)); for (int i = 0; i < s.length; ++i) { if (s[i].equals(((FontG) pd.parameter).getFamily())) spv[sc].setSelection(i); else spv[sc].setSelection(0); } vh.addView(spv[sc++]); } else if (pd.parameter instanceof LayerInfo) { spv[sc] = new Spinner(context); LayerSpinnerAdapter adapter = new LayerSpinnerAdapter(context, R.layout.layer_spinner_item, layers); spv[sc].setAdapter(adapter); spv[sc].setBackgroundResource(R.drawable.field_background); spv[sc].setSelection(((LayerInfo) pd.parameter).layer); spv[sc].setLayoutParams( new LayoutParams(fieldWidth,fieldHeight)); vh.addView(spv[sc++]); } else if (pd.parameter instanceof ArrowInfo) { spv[sc] = new Spinner(context); List<ArrowInfo> l = new ArrayList<ArrowInfo>(); l.add(new ArrowInfo(0)); l.add(new ArrowInfo(1)); l.add(new ArrowInfo(2)); l.add(new ArrowInfo(3)); ArrowSpinnerAdapter adapter = new ArrowSpinnerAdapter( context, R.layout.spinner_item, l); spv[sc].setAdapter(adapter); spv[sc].setBackgroundResource(R.drawable.field_background); spv[sc].setSelection(((ArrowInfo) pd.parameter).style); spv[sc].setLayoutParams( new LayoutParams(fieldWidth,fieldHeight)); vh.addView(spv[sc++]); } else if (pd.parameter instanceof DashInfo) { spv[sc] = new Spinner(context); List<DashInfo> l = new ArrayList<DashInfo>(); for (int k = 0; k < Globals.dashNumber; ++k) l.add(new DashInfo(k)); //TODO: customize the Arrayadapter. DashSpinnerAdapter adapter = new DashSpinnerAdapter( context, android.R.layout.simple_spinner_item, l); spv[sc].setAdapter(adapter); spv[sc].setBackgroundResource(R.drawable.field_background); spv[sc].setSelection(((DashInfo) pd.parameter).style); spv[sc].setLayoutParams( new LayoutParams(fieldWidth,fieldHeight)); vh.addView(spv[sc++]); } vv.addView(vh); } LinearLayout buttonView = new LinearLayout(context); buttonView.setGravity(Gravity.RIGHT); buttonView.setOrientation(LinearLayout.HORIZONTAL); Button ok = new Button(context); ok.setTextColor(getResources().getColor(R.color.active_light)); ok.setBackgroundColor(getResources().getColor(R.color.background_dark)); ok.setText(getResources().getText(R.string.Ok_btn)); ok.setTextSize(textSize); ok.setLayoutParams( new LayoutParams(buttonWidth,buttonHeight)); ok.setOnClickListener(new OnClickListener() { @Override public void onClick(View buttonView) { try { int ycount; ParameterDescription pd; ec = 0; cc = 0; sc = 0; // Here we read all the contents of the interface and we // update the contents of the parameter description array. for (ycount = 0; ycount < vec.size(); ++ycount) { pd = (ParameterDescription) vec.elementAt(ycount); if (pd.parameter instanceof Point) { ((Point) (pd.parameter)).x = Integer .parseInt(etv[ec++].getText().toString()); ((Point) (pd.parameter)).y = Integer .parseInt(etv[ec++].getText().toString()); } else if (pd.parameter instanceof String) { pd.parameter = etv[ec++].getText().toString(); } else if (pd.parameter instanceof Boolean) { android.util.Log.e("fidocadj", "value:"+Boolean.valueOf( cbv[cc].isChecked())); pd.parameter = Boolean.valueOf( cbv[cc++].isChecked()); } else if (pd.parameter instanceof Integer) { pd.parameter = Integer.valueOf(Integer .parseInt(etv[ec++].getText().toString())); } else if (pd.parameter instanceof Float) { pd.parameter = Float.valueOf( Float.parseFloat( etv[ec++].getText().toString())); } else if (pd.parameter instanceof FontG) { pd.parameter = new FontG((String) spv[sc++] .getSelectedItem()); } else if (pd.parameter instanceof LayerInfo) { pd.parameter = new LayerInfo((Integer) spv[sc++] .getSelectedItemPosition()); } else if (pd.parameter instanceof ArrowInfo) { pd.parameter = new ArrowInfo((Integer) spv[sc++] .getSelectedItemPosition()); } else if (pd.parameter instanceof DashInfo) { pd.parameter = new DashInfo((Integer) spv[sc++] .getSelectedItemPosition()); } } } catch (NumberFormatException E) { // Error detected. Probably, the user has entered an // invalid string when FidoCadJ was expecting a numerical // input. Toast t = new Toast(context); t.setText(Globals.messages.getString("Format_invalid")); t.show(); } FidoEditor caller = StaticStorage.getCurrentEditor(); caller.saveCharacteristics(vec); dialog.dismiss(); } }); buttonView.addView(ok); Space space = new Space(context); space.setLayoutParams( new LayoutParams(5, buttonHeight)); buttonView.addView(space); Button cancel = new Button(context); cancel.setTextColor(getResources().getColor(R.color.active_dark)); cancel.setBackgroundColor(getResources().getColor( R.color.background_dark)); cancel.setText(getResources().getText(R.string.Cancel_btn)); cancel.setTextSize(textSize); cancel.setLayoutParams( new LayoutParams(buttonWidth, buttonHeight)); cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View buttonView) { dialog.dismiss(); } }); buttonView.addView(cancel); vv.addView(buttonView); ScrollView sv=new ScrollView(context); sv.addView(vv); dialog.setContentView((View)sv); return dialog; } /** Called when the dialog is dismissed. @param savedInstanceState the state of the instance to be saved. */ public void onDismiss(Bundle savedInstanceState) { savedInstanceState.putSerializable("vec", vec); savedInstanceState.putBoolean("strict", strict); savedInstanceState.putSerializable("layers", layers); } /** Called when this view is destroyed. */ @Override public void onDestroyView() { if (getDialog() != null && getRetainInstance()) getDialog().setDismissMessage(null); super.onDestroyView(); } /** Customized item for the layout spinner. */ private class LayerSpinnerAdapter extends ArrayAdapter<LayerDesc> { private final Context context; private final List<LayerDesc> layers; public LayerSpinnerAdapter(Context context, int textViewResourceId, List<LayerDesc> layers) { super(context, textViewResourceId, layers); this.context = context; this.layers = layers; } @Override public View getView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } /** Get a custom view showing each layer in the spinner. Here the user is not supposed to edit the layers. */ public View getCustomView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = ((Activity) context).getLayoutInflater(); View row = inflater.inflate(R.layout.layer_spinner_item_noedit, parent, false); row.setBackgroundColor(Color.WHITE); SurfaceView sv = (SurfaceView) row.findViewById(R.id.surface_view); sv.setBackgroundColor(layers.get(position).getColor().getRGB()); TextView v = (TextView) row.findViewById(R.id.name_item); v.setText(layers.get(position).getDescription()); v.setTextColor(Color.BLACK); v.setBackgroundColor(Color.WHITE); v.setTextSize(textSize); return row; } } /** Customized item for the arrow spinner. */ private class ArrowSpinnerAdapter extends ArrayAdapter<ArrowInfo> { private final Context context; private final List<ArrowInfo> info; public ArrowSpinnerAdapter(Context context, int textViewResourceId, List<ArrowInfo> info) { super(context, textViewResourceId, info); this.context = context; this.info = info; } @Override public View getView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } public View getCustomView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = ((Activity) context).getLayoutInflater(); LinearLayout row = (LinearLayout)inflater. inflate(R.layout.spinner_item, parent, false); CellArrow ca = new CellArrow(context); ca.setStyle(info.get(position)); row.addView(ca); return row; } } private class DashSpinnerAdapter extends ArrayAdapter<DashInfo> { private final Context context; private final List<DashInfo> info; public DashSpinnerAdapter(Context context, int textViewResourceId, List<DashInfo> info) { super(context, textViewResourceId, info); this.context = context; this.info = info; } @Override public View getView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } public View getCustomView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = ((Activity) context).getLayoutInflater(); LinearLayout row = (LinearLayout)inflater. inflate(R.layout.spinner_item, parent, false); CellDash da = new CellDash(context); da.setStyle(info.get(position)); row.addView(da); return row; } } /** Adapts the various dialog's dimension at the screen density and size. @param size, the physical screen size of the device. @param density, the screen resolution of the device. */ private void setSizeByScreen(int size, int density) { // Default values (show something in any case). fieldWidth = 300; fieldHeight = 50; textSize = 15; buttonWidth = 115; buttonHeight = 60; android.util.Log.e("fidocadj", "size: "+size+" density: "+density); if(size == Configuration.SCREENLAYOUT_SIZE_SMALL) { switch(density) { case DENSITY_LOW: // Not tested yet on a real device fieldWidth = 80; fieldHeight = 20; textSize = 7; buttonWidth = 100; buttonHeight = 25; break; case DENSITY_MEDIUM: // Not tested on a real device yet! fieldWidth = 130; fieldHeight = 25; textSize = 9; buttonWidth = 120; buttonHeight = 40; break; case DENSITY_HIGH: // no break d:240 case DENSITY_TV: // Not tested on a real device yet! fieldWidth = 300; fieldHeight = 60; textSize = 11; buttonWidth = 160; buttonHeight = 60; break; case DENSITY_XHIGH: // Not tested on a real device yet! fieldWidth = 350; fieldHeight = 70; textSize = 13; buttonWidth = 170; buttonHeight = 65; break; case DENSITY_XXHIGH: // D: around 480 // Not tested on a real device yet! fieldWidth = 400; fieldHeight = 80; textSize = 14; buttonWidth = 200; buttonHeight = 70; break; case DENSITY_XXXHIGH: // Not tested on a real device yet! fieldWidth = 450; fieldHeight = 95; textSize = 16; buttonWidth = 230; buttonHeight = 90; break; default: fieldWidth = 300; fieldHeight = 50; textSize = 10; break; } } else if(size == Configuration.SCREENLAYOUT_SIZE_NORMAL) { //s:2 switch(density) { case DENSITY_LOW: // Not tested on a real device yet! fieldWidth = 120; fieldHeight = 25; textSize = 8; buttonWidth = 120; buttonHeight = 30; break; case DENSITY_MEDIUM: // Not tested on a real device yet! fieldWidth = 150; fieldHeight = 30; textSize = 9; buttonWidth = 150; buttonHeight = 50; break; case DENSITY_HIGH: // no break d:240 case DENSITY_TV: // Not tested on a real device yet! //Tested with Nexus S (VD) fieldWidth = 190; fieldHeight = 45; textSize = 11; buttonWidth = 80; buttonHeight = 50; break; case DENSITY_XHIGH: fieldWidth = 400; fieldHeight = 80; textSize = 14; buttonWidth = 200; buttonHeight = 80; break; case DENSITY_XXHIGH: // d: 480 //tested with Google Nexus 5 //tested with Samsung Galaxy S5 (real device) fieldWidth = 450; fieldHeight = 90; textSize = 15; buttonWidth = 225; buttonHeight = 100; break; case DENSITY_XXXHIGH: // Not tested on a real device yet! fieldWidth = 550; fieldHeight = 110; textSize = 18; buttonWidth = 275; buttonHeight = 100; break; default: fieldWidth = 300; fieldHeight = 50; textSize = 10; break; } } else if(size == Configuration.SCREENLAYOUT_SIZE_LARGE) { switch(density) { /*case DENSITY_LOW: break; case DENSITY_MEDIUM: break; break;*/ case DENSITY_HIGH: // no break, d:240 case DENSITY_TV: //tested with nexus7 800x1280 fieldWidth = 300; fieldHeight = 50; textSize = 16; break; case DENSITY_XHIGH: //tested with nexus7 1200x1920 fieldWidth = 450; fieldHeight = 80; textSize = 18; break; case DENSITY_XXHIGH: // not tested yet fieldWidth = 500; fieldHeight = 100; textSize = 20; break; case DENSITY_XXXHIGH: // not tested yet fieldWidth = 550; fieldHeight = 110; textSize = 22; break; default: fieldWidth = 300; fieldHeight = 50; textSize = 16; break; } } else if(size == Configuration.SCREENLAYOUT_SIZE_XLARGE) { // s: 4 switch(density) { case DENSITY_LOW: break; case DENSITY_MEDIUM: // d:160 // Samsung Galaxy Note 10.1 v. 2013 (real device) fieldWidth = 400; fieldHeight = 40; textSize = 16; buttonWidth = 275; buttonHeight = 70; break; case DENSITY_TV: // no break here case DENSITY_HIGH: // d:240 // Not tested yet! fieldWidth = 600; fieldHeight = 70; textSize = 17; buttonWidth = 300; buttonHeight = 100; break; case DENSITY_XHIGH: // Not tested yet! fieldWidth = 600; fieldHeight = 70; textSize = 18; buttonWidth = 320; buttonHeight = 110; break; case DENSITY_XXHIGH: // Not tested yet! fieldWidth = 650; fieldHeight = 80; textSize = 20; buttonWidth = 350; buttonHeight = 130; break; case DENSITY_XXXHIGH: // Not tested yet! fieldWidth = 700; fieldHeight = 90; textSize = 22; buttonWidth = 370; buttonHeight = 140; break; default: break; } } } }
34,788
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ParameterDescription.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/ParameterDescription.java
package net.sourceforge.fidocadj.dialogs; /** The user should check the parameter type before using. The allowed parameter types are: (Integer|Double|String|Boolean|Point). <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public class ParameterDescription { public Object parameter; // the parameter to be passed public String description; // string describing the parameter public boolean isExtension; // is this parameter a extension of FidoCAD? /** Creator. */ public ParameterDescription () { isExtension = false; } /** Obtain a text representation of the object, mainly for debug purposes. @return the representation of the object. */ @Override public String toString() { String s; s="[ParameterDescription("+parameter+", "+description+"]"; return s; } }
1,634
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DialogOpenFile.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/DialogOpenFile.java
package net.sourceforge.fidocadj.dialogs; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import net.sourceforge.fidocadj.FidoEditor; import net.sourceforge.fidocadj.R; import android.app.Activity; import android.app.Dialog; import android.app.DialogFragment; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; /** <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Dante Loi </pre> @author Dante Loi */ public class DialogOpenFile extends DialogFragment { private String[] files; private FidoEditor drawingPanel; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Activity context = getActivity(); final Dialog dialog = new Dialog(context); drawingPanel = (FidoEditor)context.findViewById(R.id.drawingPanel); dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.open_file); File dir = context.getFilesDir(); files = dir.list(); List<String> listFiles = new ArrayList<String>(); for( String str:files) if( str.indexOf("state.fcd.tmp") == -1 ) listFiles.add(str); if(listFiles.isEmpty()) listFiles.add("No such file."); ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>( context, R.layout.list_item, R.id.lblListItem, listFiles); ListView list = (ListView) dialog.findViewById(R.id.fileList); list.setAdapter(arrayAdapter); list.setPadding(10, 10, 10, 10); OnItemClickListener clickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { StringBuilder text = new StringBuilder(); text.append("[FIDOCAD]\n"); File file = new File(context.getFilesDir(),files[position]); try { BufferedReader br = new BufferedReader( new FileReader(file)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close(); } catch (IOException e) { e.printStackTrace(); } drawingPanel.getParserActions().openFileName = files[position]; drawingPanel.getParserActions().parseString(new StringBuffer(text.toString())); drawingPanel.getUndoActions().saveUndoState(); drawingPanel.invalidate(); dialog.dismiss(); } }; list.setOnItemClickListener(clickListener); return dialog; } }
3,840
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
CellArrow.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/CellArrow.java
package net.sourceforge.fidocadj.dialogs; import net.sourceforge.fidocadj.graphic.android.ColorAndroid; import net.sourceforge.fidocadj.graphic.android.GraphicsAndroid; import net.sourceforge.fidocadj.primitives.Arrow; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.view.View; /** This class provides a view showing the different arrow styles which might be used in a spinner list. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014-2016 by Dante Loi, Davide Bucci </pre> */ public class CellArrow extends View { private ArrowInfo arrow; /** Standard constructor. @param context the context of the cell. */ public CellArrow(Context context) { super(context); } /** Select the style of the arrow to be used. @param arrow the wanted style. */ public void setStyle(ArrowInfo arrow) { this.arrow = arrow; } /** Paint the cell with the arrow. @param canvas the canvas where to draw. */ @Override protected void onDraw(Canvas canvas) { // Background: white! canvas.drawColor(Color.WHITE); GraphicsAndroid g = new GraphicsAndroid(canvas); ColorAndroid c = new ColorAndroid(); g.setColor(c.black()); // Compute a reasonable size for the arrows, depending on the // screen resolution. int mult=(int)Math.floor(g.getScreenDensity()/112); if (mult<1) mult=1; // Draw the arrow. g.applyStroke(2*mult, 0); g.drawLine(getWidth()/3, getHeight()/2,2*getWidth()/3, getHeight()/2); Arrow arrowDummy = new Arrow(); arrowDummy.drawArrowPixels(g, getWidth()/3, getHeight()/2, 2*getWidth()/3, getHeight()/2, mult*10, mult*4, arrow.style); } }
2,511
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DialogAbout.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/DialogAbout.java
package net.sourceforge.fidocadj.dialogs; import net.sourceforge.fidocadj.R; import android.app.Activity; import android.app.Dialog; import android.app.DialogFragment; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.TextView; import android.util.DisplayMetrics; import net.sourceforge.fidocadj.globals.*; /** Shows a rather standard "About" dialog. Nothing more exotic than showing the nice icon of the program, its name as well as three lines of description. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Dante Loi </pre> @author Dante Loi */ public class DialogAbout extends DialogFragment { private final String url = "https://sourceforge.net/projects/fidocadj/"; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Activity context = getActivity(); final Dialog dialog = new Dialog(context); dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_about); TextView version = (TextView) dialog.findViewById(R.id.version); version.setText(Globals.version); TextView screenInfo = (TextView) dialog.findViewById(R.id.screen_info); // Update a debug line with the screen codes. DisplayMetrics metrics = getResources().getDisplayMetrics(); int screenDensity = metrics.densityDpi; int screenSize = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK; screenInfo.setText("Screen, d: "+screenDensity +" s: "+ screenSize); dialog.show(); Button link = (Button) dialog.findViewById(R.id.link_button); link.setText(url); link.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); Intent chooser = Intent.createChooser(intent, getText(R.string.Choose_browser)); startActivity(chooser); } }); return dialog; } }
3,010
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
LayerInfo.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/LayerInfo.java
package net.sourceforge.fidocadj.dialogs; /** <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2009-2023 by Davide Bucci </pre> @author Davide Bucci */ public class LayerInfo { int layer; /** Create a LayerInfo object with the given layer @param i the layer to be used. */ public LayerInfo(int i) { layer=i; } public int getLayer() { return layer; } }
1,084
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DialogLayer.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/DialogLayer.java
package net.sourceforge.fidocadj.dialogs; import java.util.List; import java.util.Vector; import net.sourceforge.fidocadj.FidoEditor; import net.sourceforge.fidocadj.R; import android.app.Activity; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.SurfaceView; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Button; import android.widget.Switch; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.CompoundButton; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.graphic.android.ColorAndroid; /** <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014-2015 by Dante Loi, Davide Bucci </pre> @author Dante Loi */ public class DialogLayer extends DialogFragment { private FidoEditor drawingPanel; private Button layerButton; private Dialog diag; /** Create the dialog where the user can choose the current layer. @param savedInstanceState the saved instance state (not used). */ @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Activity context = getActivity(); final Dialog dialog = new Dialog(context); drawingPanel = (FidoEditor)context.findViewById(R.id.drawingPanel); layerButton= (Button)context.findViewById(R.id.layer); dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.open_file); final Vector<LayerDesc> layers = drawingPanel.getDrawingModel().getLayers(); // Here we create an adapter for the list. It is the custom class // defined in this very file. LayerAdapter customLayerAdapter = new LayerAdapter( context, R.layout.layer_spinner_item, layers); // We associate the adapter with the ListView list = (ListView) dialog.findViewById(R.id.fileList); list.setAdapter(customLayerAdapter); list.setPadding(10, 10, 10, 10); diag=dialog; return dialog; } /** Inner class which provides a custom-made view which will be embedded in the list shown by the dialog. */ private class LayerAdapter extends ArrayAdapter<LayerDesc> { private final Context context; private final List<LayerDesc> layers; public LayerAdapter(Context context, int textViewResourceId, List<LayerDesc> layers) { super(context, textViewResourceId, layers); this.context = context; this.layers = layers; } /** Obtain the custom view associated to the given position. */ @Override public View getView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } /** Obtain the custom view associated to the given position. */ @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } /** Get a custom View showing the useful information about the layers: color and visibility. @param position the ordinal position in the list (layer number) @param convertView @param parent the parent component. @return the custom view. */ public View getCustomView(int pos, View convertView, ViewGroup parent) { final int position=pos; LayoutInflater inflater = ((Activity) context).getLayoutInflater(); final View row = inflater.inflate(R.layout.layer_spinner_item, parent, false); row.setBackgroundColor(Color.WHITE); // Here we show a small rectangle of the layer color SurfaceView sv = (SurfaceView) row.findViewById(R.id.surface_view); sv.setBackgroundColor(layers.get(position).getColor().getRGB()); // A text element showing the layer name, in black if the // layer is visible or in gray if it is not. Button b = (Button) row.findViewById(R.id.name_item); b.setText(layers.get(position).getDescription()); b.setOnClickListener(new SpecSelectCurrentLayer(drawingPanel, layerButton, layers, diag, position)); // We have a switch which determines whether a layer is visible // or not. Switch ss = (Switch) row.findViewById(R.id.visibility_item); ss.setChecked(layers.get(position).isVisible); ss.setOnCheckedChangeListener( new SpecCheckedChangeListener(convertView, layers, position)); b.setTextColor(Color.BLACK); b.setBackgroundColor(Color.WHITE); b.setTextSize(20); Button edit = (Button) row.findViewById(R.id.edit_item); edit.setOnClickListener(new View.OnClickListener() { /** Create a new layer editing dialog and show it. */ @Override public void onClick(View v) { drawingPanel.eea.currentLayer = position; // show layer dialog DialogEditLayer dl = new DialogEditLayer(position, row); dl.show(getFragmentManager(), ""); } }); return row; } } /** Handle a click on the selection button */ private class SpecSelectCurrentLayer implements View.OnClickListener { private FidoEditor drawingPanel; private List<LayerDesc> layers; private Button layerButton; private int position; private Dialog dialog; /** Creator. */ public SpecSelectCurrentLayer(FidoEditor dp, Button lb, List<LayerDesc> l, Dialog d, int pos) { drawingPanel=dp; layers=l; layerButton=lb; dialog=d; position=pos; } /** Handle a click on the visibility switch */ @Override public void onClick(View v) { drawingPanel.eea.currentLayer = position; layerButton.setBackgroundColor( ((ColorAndroid)layers.get(position).getColor()) .getColorAndroid()); drawingPanel.invalidate(); dialog.dismiss(); } } /** Handle the change of the visibility toggle switch. */ private class SpecCheckedChangeListener implements OnCheckedChangeListener { private int position; private List<LayerDesc> layers; private View parentView; public SpecCheckedChangeListener(View p, List<LayerDesc> l, int pos) { layers=l; position=pos; parentView=p; } /** Handle a click on the visibility switch */ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { layers.get(position).setVisible(isChecked); parentView.invalidate(); } } }
8,425
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
CellDash.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/CellDash.java
package net.sourceforge.fidocadj.dialogs; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.graphic.android.ColorAndroid; import net.sourceforge.fidocadj.graphic.android.GraphicsAndroid; import net.sourceforge.fidocadj.primitives.Arrow; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.view.View; /** This class provides a view showing the different dash styles which might be used in a spinner list. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014-2015 by Dante Loi, Davide Bucci </pre> */ public class CellDash extends View { private DashInfo dash; /** Standard constructor. @param context the context of the cell. */ public CellDash(Context context) { super(context); } /** Select the wanted dash style. @param dash_s the wanted style. */ public void setStyle(DashInfo dash_s) { this.dash = dash_s; } /** Draw the cell with the dashing styles. @param canvas the canvas where to draw. */ @Override protected void onDraw(Canvas canvas) { // Background: white! canvas.drawColor(Color.WHITE); GraphicsAndroid g = new GraphicsAndroid(canvas); ColorAndroid c = new ColorAndroid(); g.setColor(c.black()); // Compute a reasonable size for the arrows, depending on the // screen resolution. int mult=(int)Math.floor(g.getScreenDensity()/112); if (mult<1) mult=1; // Draw a line. g.applyStroke(2*mult, dash.getStyle()); g.drawLine(getWidth()/3, getHeight()/2,2*getWidth()/3, getHeight()/2); } }
2,419
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ArrowInfo.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/ArrowInfo.java
package net.sourceforge.fidocadj.dialogs; /** This class contains information about the arrow style. It is useful for the automatic generation of the properties dialog. @author Davide Bucci <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2009-2023 by Davide Bucci </pre> */ public class ArrowInfo { public int style; /** Standard constructor: specify the style to be used. @param i style to set */ public ArrowInfo(int i) { style=i; } /** Obtain the style of the arrow. @return the arrow style. */ public int getStyle() { return style; } }
1,305
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DialogSaveName.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/DialogSaveName.java
package net.sourceforge.fidocadj.dialogs; import net.sourceforge.fidocadj.FidoEditor; import net.sourceforge.fidocadj.R; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import com.explorer.ExplorerActivity; import com.explorer.IO; /** Shows a text field for entry the new file name, and save it in the file system. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Dante Loi, Giuseppe Amato, Davide Bucci </pre> @author Dante Loi, Giuseppe Amato, Davide Bucci */ @SuppressLint("DefaultLocale") public class DialogSaveName extends DialogFragment { private String circuit; private FidoEditor drawingPanel; private Dialog dialog; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Activity context = getActivity(); dialog = new Dialog(context); drawingPanel = (FidoEditor) context.findViewById(R.id.drawingPanel); circuit = drawingPanel.getText(); dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.save_with_name); EditText editPath = (EditText) dialog.findViewById(R.id.editPath); editPath.setText(IO.rootDir); Button save = (Button) dialog.findViewById(R.id.save); save.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { save(); dialog.dismiss(); } }); Button cancel = (Button) dialog.findViewById(R.id.cancel); cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); ((ImageView) dialog.findViewById(R.id.explorerBt)) .setOnClickListener(new OnClickListener() { public void onClick(View v) { onFolderClick(v); } }); return dialog; } private void save() { EditText editName = (EditText) dialog.findViewById(R.id.editName); EditText editPath = (EditText) dialog.findViewById(R.id.editPath); String fileName = editName.getText().toString(); if (!fileName.toLowerCase().endsWith(".fcd")) { fileName += ".fcd"; } String path = editPath.getText().toString(); writeFile(IO.joinPath(new String[] { path, fileName })); } /** Check if the file with the specified filename exists and prompt a * dialog to confirm overwrite * * @param filename the filename to write to */ private void writeFile(String filename) { drawingPanel.getParserActions().openFileName = filename; if (IO.checkSDFile(drawingPanel.getParserActions().openFileName)) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); String msg = getResources().getString(R.string.Warning_overwrite); builder.setMessage(msg) .setCancelable(false) .setTitle(R.string.Warning) .setIcon(android.R.drawable.ic_dialog_info) .setPositiveButton(R.string.Ok_btn, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { IO.writeFileToSD( drawingPanel.getParserActions(). openFileName, circuit); } }) .setNegativeButton(R.string.Cancel_btn, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } else { IO.writeFileToSD(drawingPanel.getParserActions().openFileName, circuit); } } /** Invoke the ExplorerActivity to select folder @param v not used. */ public void onFolderClick(View v) { Intent myIntent = new Intent(getActivity(), ExplorerActivity.class); myIntent.putExtra(ExplorerActivity.DIRECTORY, true); int requestCode = ExplorerActivity.REQUEST_FOLDER; startActivityForResult(myIntent, requestCode); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case ExplorerActivity.REQUEST_FOLDER: if (data.hasExtra(ExplorerActivity.DIRECTORY)) { String folder = data.getExtras().getString( ExplorerActivity.DIRECTORY); EditText editpath = (EditText) dialog .findViewById(R.id.editPath); editpath.setText(folder); } break; default: break; } } } }
6,623
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DashInfo.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/dialogs/DashInfo.java
package net.sourceforge.fidocadj.dialogs; /** This class contains some settings about the actual dashing style. It is used in the automatic primitive characteristics dialog. @author Davide Bucci <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2009-2023 by Davide Bucci </pre> */ public class DashInfo { // Here we store the dash style public int style; /** Creator. @param i the style to be stored */ public DashInfo(int i) { style=i; } /** Retrieve the style. @return the style. */ public int getStyle() { return style; } }
1,295
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/package-info.java
/** Package providing a model (database) as well as a representation of libraries. MacroDesc class (currently in the primitives package) will be moved here in the future. */ package net.sourceforge.fidocadj.librarymodel;
233
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
LibraryModel.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/LibraryModel.java
package net.sourceforge.fidocadj.librarymodel; import java.util.*; import java.io.FileNotFoundException; import java.io.IOException; import net.sourceforge.fidocadj.undo.UndoActorListener; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.globals.LibUtils; import net.sourceforge.fidocadj.librarymodel.event.KeyChangeEvent; import net.sourceforge.fidocadj.librarymodel.event.LibraryListener; import net.sourceforge.fidocadj.librarymodel.event.RemoveEvent; import net.sourceforge.fidocadj.librarymodel.event.AddEvent; import net.sourceforge.fidocadj.librarymodel.event.RenameEvent; import net.sourceforge.fidocadj.primitives.MacroDesc; // TODO: comment public methods // NOTE: This model has no adding macro method. /** Model class for macro operation. This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 Kohta Ozaki - Davide Bucci */ public class LibraryModel { final private List<LibraryListener> libraryListeners; final private DrawingModel drawingModel; final private List<Library> libraries; // Bridge for existing system. private Map<String,MacroDesc> masterLibrary; private UndoActorListener undoActorListener; /** Costructor. @param drawingModel DrawingModel instance to fetch macros. */ public LibraryModel(DrawingModel drawingModel) { this.drawingModel = drawingModel; libraryListeners = new ArrayList<LibraryListener>(); libraries = new ArrayList<Library>(); updateLibraries(); } /** Adds LibraryListener. @param listener LibraryLisner. */ public void addLibraryListener(LibraryListener listener) { libraryListeners.add(listener); } /** Removes LibraryListener. @param listener LibraryListener. */ public void removeLibraryListener(LibraryListener listener) { libraryListeners.remove(listener); } /** Removes category from library. Notices LibraryListeners after removed. @param category Category to remove. @throws IllegalLibraryAccessException If access standard library. */ public void remove(Category category) throws IllegalLibraryAccessException { Library parentLibrary; if(category==null) { return; } parentLibrary = category.getParentLibrary(); if(parentLibrary.isStdLib()) { throw new IllegalLibraryAccessException( "A category in standard library can't be removed."); } parentLibrary.removeCategory(category); synchronizeMasterLibrary(); save(); saveLibraryState(); fireRemoved(parentLibrary,category); } /** Removes library and deletes file. Notices LibraryListeners after removed. @param library Library to remove. @throws IllegalLibraryAccessException If access standard library. */ public void remove(Library library) throws IllegalLibraryAccessException { // NOTE: We must consider this method contains deleting file. if(library==null) { return; } if(library.isStdLib()) { throw new IllegalLibraryAccessException( "A standard library can't be removed."); } libraries.remove(library); synchronizeMasterLibrary(); try{ LibUtils.deleteLib(library.getFilename()); } catch (FileNotFoundException e){ System.out.println("library not found:"+library.getFilename()); } catch (IOException e) { System.out.println("Exception: "+e); } saveLibraryState(); fireRemoved(null,library); } /** Removes macro from library. Notices LibraryListeners after removed. @param macro MacroDesc to remove. @throws IllegalLibraryAccessException If access standard library. */ public void remove(MacroDesc macro) throws IllegalLibraryAccessException { Category category; if(macro==null) { return; } category = (Category)getParentNode(macro); if(category==null) { throw new IllegalLibraryAccessException("It's a wondering macro."); } if(category.getParentLibrary().isStdLib()) { throw new IllegalLibraryAccessException( "A standard library can't be removed."); } category.removeMacro(macro); synchronizeMasterLibrary(); save(); saveLibraryState(); fireRemoved(category,macro); } /** Renames macro. Notices LibraryListeners after renamed. @param macro MacroDesc to rename. @param newName New macro name. @throws IllegalLibraryAccessException If access standard library. @throws IllegalNameException If new name is invalid. */ public void rename(MacroDesc macro,String newName) throws IllegalNameException, IllegalLibraryAccessException { if(macro==null) { return; } String oldName = macro.name; //validation if(newName==null || newName.length()==0) { throw new IllegalNameException("Name length must not be zero."); } if(isStdLib(macro)) { throw new IllegalLibraryAccessException( "A macro in standard library can't be renamed."); } // TODO:validation // macro.isValidName(newName); macro.name = newName; save(); saveLibraryState(); fireRenamed(getParentNode(macro),macro,oldName); } /** Renames category. Notices LibraryListeners after renamed. @param category Category to rename. @param newName New category name. @throws IllegalLibraryAccessException If access standard library. @throws IllegalNameException If new name is invalid. */ public void rename(Category category,String newName) throws IllegalNameException,IllegalLibraryAccessException { String oldName = category.getName(); //validation if(newName==null || newName.length()==0) { throw new IllegalNameException("Name length must not be zero."); } if(category.getParentLibrary().isStdLib()) { throw new IllegalLibraryAccessException( "A category in standard library can't be renamed."); } if(!Category.isValidName(newName)) { throw new IllegalNameException("invalid name"); } category.setName(newName); synchronizeMacros(category.getParentLibrary()); save(); saveLibraryState(); fireRenamed(getParentNode(category),category,oldName); } /** Renames library. Notices LibraryListeners after renamed. @param library Library to rename. @param newName New library name. @throws IllegalLibraryAccessException If access standard library. @throws IllegalNameException If new name is invalid. */ public void rename(Library library,String newName) throws IllegalNameException,IllegalLibraryAccessException { String oldName = library.getName(); //validation if(newName==null || newName.length()==0) { throw new IllegalNameException("Name length must not be zero."); } if(library.isStdLib()) { throw new IllegalLibraryAccessException( "A standard library can't be renamed."); } if(!Library.isValidName(newName)) { throw new IllegalNameException("invalid name"); } library.setName(newName); synchronizeMacros(library); synchronizeMasterLibrary(); save(); saveLibraryState(); fireRenamed(null,library,oldName); } /** Copies macro into category. Notices LibraryListeners after copied. @param macro target macro. @param destCategory destination category. */ public void copy(MacroDesc macro, Category destCategory) { //TODO: Standard library check. MacroDesc newMacro; System.out.println("copy:"+macro+destCategory); newMacro = copyMacro(macro,destCategory); synchronizeMacros(destCategory.getParentLibrary()); synchronizeMasterLibrary(); save(); saveLibraryState(); fireAdded(destCategory,newMacro); } /** Utility function. */ private MacroDesc copyMacro(MacroDesc macro, Category destCategory) { MacroDesc newMacro; String newPlainKey; int retry; if(macro==null || destCategory==null) { return null; } newMacro = cloneMacro(macro); newPlainKey = createRandomMacroKey(); for(retry=20; 0<retry; retry--) { if(!destCategory.getParentLibrary().containsMacroKey(newPlainKey)) { break; } } if(retry<0) { throw new RuntimeException("Key generation failed."); } newMacro.key = createMacroKey(destCategory.getParentLibrary(). getFilename(),newPlainKey); destCategory.addMacro(newMacro); return newMacro; } /** Copies category into library. Notices LibraryListeners after copied. @param category target category. @param destLibrary destination library. */ public void copy(Category category, Library destLibrary) { //TODO: Standard library check. Category newCategory; if(category==null || destLibrary==null) { return; } newCategory = new Category(category.getName(), category.getParentLibrary(), false); for(MacroDesc macro:category.getAllMacros()) { copyMacro(macro,newCategory); } destLibrary.addCategory(newCategory); synchronizeMacros(destLibrary); synchronizeMasterLibrary(); save(); saveLibraryState(); fireAdded(destLibrary, newCategory); } /** Changes macro key. Notices LibraryListeners after changed. @param macro MacroDesc to change key. @param newKey New macro key without library prefix. @throws IllegalLibraryAccessException If access standard library. @throws IllegalKeyException If new key is invalid. */ public void changeKey(MacroDesc macro,String newKey) throws IllegalKeyException,IllegalLibraryAccessException { String oldKey; Category category; if(macro==null || newKey.length()==0) { throw new IllegalKeyException("Name length must not be zero."); } if(isStdLib(macro)) { throw new IllegalLibraryAccessException( "A macro in standard library can't be renamed."); } // key validation // key exists check category = (Category)getParentNode(macro); if(category.getParentLibrary().containsMacroKey(newKey)) { throw new IllegalKeyException("New key already exists."); } oldKey = getPlainMacroKey(macro); macro.key = createMacroKey(macro.filename,newKey); save(); saveLibraryState(); fireKeyChanged(getParentNode(macro),macro,oldKey); } /** Utility function. */ private MacroDesc cloneMacro(MacroDesc macro) { return new MacroDesc(macro.key, macro.name, macro.description, macro.category, macro.library, macro.filename); } /** Returns macro key without library prefix. @param macro macro. @return String plain key. */ public static String getPlainMacroKey(MacroDesc macro) { String[] parted; if(macro==null) { return null; } parted = macro.key.split("\\."); if(1<parted.length) { return parted[1]; } else { return parted[0]; } } /** Returns new macro key. @return String plain key. */ public static String createRandomMacroKey() { long t=System.nanoTime(); long h=0; for(int i=0; t>0; ++i) { t>>=i*8; h^=t & 0xFF; } return String.valueOf(h); } /** Returns identifiable macro key. @param fileName filename of library. @param key plain key. @return String key. */ public static String createMacroKey(String fileName,String key) { String macroKey = fileName+"."+key; return macroKey.toLowerCase(new Locale("en")); } /** Synchronizes MacroDesc's properties with library. */ private void synchronizeMacros(Library library) { String plainKey; if(library.isStdLib()) { return; } for(Category category:library.getAllCategories()) { for(MacroDesc m:category.getAllMacros()) { m.category = category.getName(); m.library = library.getName(); m.filename = library.getFilename(); plainKey = getPlainMacroKey(m); m.key = createMacroKey(library.getFilename(),plainKey); } } } /** Sets UndoActorListener. @param undoActorListener UndoActorListener. */ public void setUndoActorListener(UndoActorListener undoActorListener) { this.undoActorListener = undoActorListener; } /** Returns true if macro is in standard library. This method will be removed in the future. @param macro MacroDesc */ private boolean isStdLib(MacroDesc macro) { // An alternative way to see if a macro is standard or not // is to extract the prefix from the key and to see if the // prefix is "" or the one of the standard libraries. for(Library l:getAllLibraries()) { if(l.isStdLib()) { for(Category c:l.getAllCategories()) { for(MacroDesc m:c.getAllMacros()) { if(macro.equals(m)) { return true; } } } } } return false; } private void fireAdded(Object parentNode,Object addedNode) { for(LibraryListener l:libraryListeners) { l.libraryNodeAdded(new AddEvent(parentNode,addedNode)); } } private void fireRenamed(Object parentNode,Object renamedNode, String oldName) { for(LibraryListener l:libraryListeners) { l.libraryNodeRenamed(new RenameEvent(parentNode,renamedNode, oldName)); } } private void fireRemoved(Object parentNode,Object removedNode) { for(LibraryListener l:libraryListeners) { l.libraryNodeRemoved(new RemoveEvent(parentNode,removedNode)); } } private void fireKeyChanged(Object parentNode,Object changedNode, String oldKey) { for(LibraryListener l:libraryListeners) { l.libraryNodeKeyChanged(new KeyChangeEvent(parentNode,changedNode, oldKey)); } } // NOTE: This implementation is incorrect. (DB why? equals may fail?) private Object getParentNode(Object node) { for(Library l:getAllLibraries()) { if(node.equals(l)) { return null; // A library does not have any parent! } for(Category c:l.getAllCategories()) { if(node.equals(c)) { return l; } for(MacroDesc m:c.getAllMacros()) { if(node.equals(m)) { return c; } } } } return null; // Node not found } /** Returns MacroDesc map. @return Map composed of String key and MacroDesc from parser. */ public Map<String,MacroDesc> getAllMacros() { return masterLibrary; } /** Returns Libraries as list. @return List of Library objects. */ public List<Library> getAllLibraries() { return libraries; } /** Saves library to file. */ public void save() { //TODO: throw necessary exceptions. for(Library library:libraries){ try{ if(!library.isStdLib()){ LibUtils.save(masterLibrary, LibUtils.getLibPath(library.getFilename()), library.getName().trim(), library.getFilename()); } } catch (FileNotFoundException e) { System.out.println("Error accessing to the file."); } } } /** Saves library state for undo. */ public void saveLibraryState() { try { LibUtils.saveLibraryState(undoActorListener); } catch (IOException e) { System.out.println("Exception: "+e); } } /** Not implemented. */ public void undoLibrary() { // TODO: this should undo the last library operation. } /** Updates library. */ public void forceUpdate() { updateLibraries(); fireChanged(); } private void fireChanged() { for(LibraryListener l:libraryListeners) { l.libraryLoaded(); } } /** Bridges existing components. This method will be removed in the future. */ private void synchronizeMasterLibrary() { masterLibrary.clear(); for(Library library:libraries) { for(Category category:library.getAllCategories()) { for(MacroDesc macro:category.getAllMacros()) { masterLibrary.put(macro.key,macro); } } } } private void updateLibraries() { Library library; Category category; boolean catIsHidden; String key; Map<String,Library> tmpLibraryMap = new HashMap<String,Library>(); masterLibrary = drawingModel.getLibrary(); libraries.clear(); for(MacroDesc md:masterLibrary.values()) { cleanMacro(md); key = md.filename + "/" + md.library; if(tmpLibraryMap.containsKey(key)) { library = tmpLibraryMap.get(key); } else { library = new Library(md.library,md.filename,LibUtils.isStdLib(md)); tmpLibraryMap.put(key,library); libraries.add(library); } if(library.getCategory(md.category)==null) { catIsHidden = "hidden".equals(md.category); category = new Category(md.category,library,catIsHidden); library.addCategory(category); } else { category = library.getCategory(md.category); } category.addMacro(md); } fireChanged(); } private void cleanMacro(MacroDesc macro) { macro.name = macro.name.trim(); } /** Exception for library operation error. */ public class LibraryException extends Exception { LibraryException(String message) { super(message); } } /** Exception for an illegal name (when searching, etc...) */ public class IllegalNameException extends LibraryException { IllegalNameException(String message) { super(message); } } /** Exception for an illegal library access (i.e. non existant, most of the times). */ public class IllegalLibraryAccessException extends LibraryException { IllegalLibraryAccessException(String message) { super(message); } } /** Exception for an illegal key in a library. */ public class IllegalKeyException extends LibraryException { IllegalKeyException(String message) { super(message); } } }
21,379
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
Library.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/Library.java
package net.sourceforge.fidocadj.librarymodel; import java.util.*; /** The Library class provides a set of methods to manipulate libraries. This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 Kohta Ozaki */ public class Library { private String libraryName; private final String filename; private final boolean isStd; private final List<Category> categories; /** Standard constructor. @param libraryName the name of the library. @param filename the name of the file where the library is contained. @param isStd true if the library should be considered as standard. */ Library(String libraryName, String filename,boolean isStd) { this.libraryName = libraryName; this.filename = filename; this.isStd = isStd; categories = new ArrayList<Category>(); } /** Get the name of the library. @return the library name. */ public String getName() { return libraryName; } /** Set the name of the library. @param name the name to be employed. */ public void setName(String name) { this.libraryName = name; } /** Get the name of the file of the library. @return the filename. */ public String getFilename() { return filename; } /** Gets all the categories contained in the library. @return a list containing all categories. */ public List<Category> getAllCategories() { return categories; } /** Get a category in the library. @param name the name of the category to be retrieved. @return the category with the required name or null if nothing has been found. */ public Category getCategory(String name) { Category result=null; for(Category c:categories) { if(c.getName().equals(name)) { result=c; break; } } return result; } /** Add the given category to the library. @param category the category to be added. */ public void addCategory(Category category) { categories.add(category); } /** Remove a category from the library. @param category the category to be removed. */ public void removeCategory(Category category) { categories.remove(category); } /** Check if the library is standard. @return true if the library is standard. */ public boolean isStdLib() { return isStd; } /** Check if the library is hidden. TODO: this method always returns false. @return true if the library is hidden. */ public boolean isHidden() { return false; } /** Check if the name of the library is valid. TODO: this method always returns true. @param name the name to be checked. @return true if the name is valid. */ public static boolean isValidName(String name) { return true; } /** Check if the library contains the macro specified with the key. @param key the key to be searched for. @return true if the key is found, false otherwise. */ public boolean containsMacroKey(String key) { if(key==null) { return true; } for(Category category:categories) { if(category.containsMacroKey(key)) { return true; } } return false; } /** Provide a string description of the library. @return the string description (simply the name) of the library. */ @Override public String toString() { return getName(); } }
4,410
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
Category.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/Category.java
package net.sourceforge.fidocadj.librarymodel; import java.util.*; import net.sourceforge.fidocadj.primitives.MacroDesc; /** The Category class provides a set of methods to manipulate categories in a library. This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014 Kohta Ozaki */ public class Category { String name; Library parentLibrary; List<MacroDesc> macros; boolean isHidden; /** Standard constructor. @param name the name of the category. @param parentLibrary the parent library to which the category belongs. @param idHidden true if the category should not be shown. */ Category(String name,Library parentLibrary,boolean isHidden) { macros = new ArrayList<MacroDesc>(); this.name = name; this.parentLibrary = parentLibrary; this.isHidden = isHidden; } /** Get the parent library. @return the parent library. */ public Library getParentLibrary() { return parentLibrary; } /** Set the parent library. @param parentLibrary the parent library to be employed. */ public void setParentLibrary(Library parentLibrary) { this.parentLibrary = parentLibrary; } /** Get the name of the category. @return the name. */ public String getName() { return name; } /** Set the name of the category. @param name the name. */ public void setName(String name) { this.name = name; } /** Add a macro to this category. @param macroDesc the macro to be added. */ public void addMacro(MacroDesc macroDesc) { macros.add(macroDesc); } /** Remove a macro from this category. @param macroDesc the macro to be removed. */ public void removeMacro(MacroDesc macroDesc) { macros.remove(macroDesc); } /** Get a list of all macros comprised in the category. @return the list of macros. */ public List<MacroDesc> getAllMacros() { return macros; } /** Check if the category is hidden. @return true if the category is hidden, false if it is visible. */ public boolean isHidden() { return isHidden; } /** Check if the category name is valid. TODO: this method doesn't do much: it always returns true. @param name the name of the category to be checked. @return true if the name is valid. */ public static boolean isValidName(String name) { return true; } /** Check if a macro having a given key is already contained in the category. @param key the key of the macro to search for. @return true if the macro is already present. */ public boolean containsMacroKey(String key) { if(key==null) { return true; } for(MacroDesc macro:macros) { if(LibraryModel.getPlainMacroKey(macro).equals(key)) { return true; } } return false; } }
3,752
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/utils/package-info.java
/** Various general purpose classes for libraries. */ package net.sourceforge.fidocadj.librarymodel.utils;
112
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
LibraryUndoExecutor.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/utils/LibraryUndoExecutor.java
package net.sourceforge.fidocadj.librarymodel.utils; import java.io.*; import net.sourceforge.fidocadj.globals.FileUtils; import net.sourceforge.fidocadj.globals.LibUtils; import net.sourceforge.fidocadj.undo.LibraryUndoListener; import net.sourceforge.fidocadj.librarymodel.LibraryModel; /** Execute undo actions on libraries. ANDROID VERSION. This class is a placeholder for the moment. No real code is present yet. This class does not handle the temporary files and dir operations required by the undo operation on libraries. It just performs the low level file copy operations required. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 Kohta Ozaki, Davide Bucci </pre> */ public class LibraryUndoExecutor implements LibraryUndoListener { LibraryModel libraryModel; /** Constructor. @param model the drawing model. */ public LibraryUndoExecutor(LibraryModel model) { libraryModel = model; } /** Execute an undo operation on a library. @param s the path to the temporary library directory where the libraries are stored immediately before the operation which should be undone has been performed. */ public void undoLibrary(String s) { // NONE } }
1,937
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
CircuitPanelUpdater.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/utils/CircuitPanelUpdater.java
package net.sourceforge.fidocadj.librarymodel.utils; import net.sourceforge.fidocadj.librarymodel.event.LibraryListener; import net.sourceforge.fidocadj.librarymodel.event.AddEvent; import net.sourceforge.fidocadj.librarymodel.event.KeyChangeEvent; import net.sourceforge.fidocadj.librarymodel.event.RemoveEvent; import net.sourceforge.fidocadj.librarymodel.event.RenameEvent; import net.sourceforge.fidocadj.circuit.controllers.ParserActions; import net.sourceforge.fidocadj.circuit.model.DrawingModel; /** Class implementing a library listener, with some callback methods. ANDROID version. For the moment, there is nothing very exciting happening here and this class is only a placeholder. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 Kohta Ozaki, Davide Bucci </pre> */ public class CircuitPanelUpdater implements LibraryListener { /** Constructor. */ public CircuitPanelUpdater() { } /** Called when a library has been loaded. */ public void libraryLoaded() { } /** Called when a library has been renamed. @param e the renaming event. */ public void libraryNodeRenamed(RenameEvent e) { //NOP } /** Called when a node has been removed from a library. @param e the remove event. */ public void libraryNodeRemoved(RemoveEvent e) { } /** Called when a node has been added. @param e the adding event. */ public void libraryNodeAdded(AddEvent e) { //NOP } /** Called when the key for a node (macro) has been changed. @param e the node key changing event. */ public void libraryNodeKeyChanged(KeyChangeEvent e) { } /** Parse again the circuit and redraw everything. */ private void updateCircuitPanel() { } }
2,480
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/event/package-info.java
/** Package for handling events on the libraries. TODO: improve documentation of this package: what is the general philosophy? How are the classes interacting together? What is the relation between a "node" and an element in a directory? */ package net.sourceforge.fidocadj.librarymodel.event;
310
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
AddEvent.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/event/AddEvent.java
package net.sourceforge.fidocadj.librarymodel.event; /** Event handling in library editing: add a node to a library. This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014 Kohta Ozaki */ public class AddEvent { final private Object addedNode; final private Object parentNode; /** Standard constructor. @param parentNode node which will become the parent node. @param addedNode node to be added. */ public AddEvent(Object parentNode, Object addedNode) { this.parentNode = parentNode; this.addedNode = addedNode; } /** Return the value of addedNode. @return the addedNode. */ public Object getAddedNode() { return addedNode; } /** Return the value of parentNode. @return the parentNode. */ public Object getParentNode() { return parentNode; } }
1,554
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
RemoveEvent.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/event/RemoveEvent.java
package net.sourceforge.fidocadj.librarymodel.event; /** Remove event data on a library. This file is part of FidoCadJ. <pre> FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014 Kohta Ozaki </pre> */ public class RemoveEvent { final private Object removedNode; final private Object parentNode; /** Standard constructor. @param parentNode the node which is the parent to the removed node. @param removedNode the removed node. */ public RemoveEvent(Object parentNode,Object removedNode) { this.parentNode = parentNode; this.removedNode = removedNode; } /** Returns the value of removedNode. @return the value of removedNode. */ public Object getRemovedNode() { return removedNode; } /** Returns the value of parentNode. @return the value of parentNode. */ public Object getParentNode() { return parentNode; } }
1,611
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
RenameEvent.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/event/RenameEvent.java
package net.sourceforge.fidocadj.librarymodel.event; /** Rename event containing data. This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014 Kohta Ozaki */ public class RenameEvent { final private Object renamedNode; final private Object parentNode; final private String oldName; /** Standard constructor. @param parentNode the parent node to the renamed one. @param renamedNode the renamed node. @param oldName the old name of the renamed node. */ public RenameEvent(Object parentNode,Object renamedNode,String oldName) { this.parentNode = parentNode; this.renamedNode = renamedNode; this.oldName = oldName; } /** Returns the value of renamedNode. @return the value of renamedNode. */ public Object getRenamedNode() { return renamedNode; } /** Returns the value of parentNode. @return the value of parentNode. */ public Object getParentNode() { return parentNode; } /** Returns the value of oldName. @return the old name of the node. */ public String getOldName() { return oldName; } }
1,857
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
LibraryListener.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/event/LibraryListener.java
package net.sourceforge.fidocadj.librarymodel.event; /** Interface for a listener of events on library. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 Kohta Ozaki, Davide Bucci </pre> */ public interface LibraryListener { /** Called when a library has been loaded. */ void libraryLoaded(); /** Called when a node has been renamed. @param e information about the rename event. */ void libraryNodeRenamed(RenameEvent e); /** Called when a node has been removed. @param e information about the remove event. */ void libraryNodeRemoved(RemoveEvent e); /** Called when a node has been added. @param e information about the added event. */ void libraryNodeAdded(AddEvent e); /** Called when a key has been changed in a node @param e information about the key change event. */ void libraryNodeKeyChanged(KeyChangeEvent e); }
1,627
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
KeyChangeEvent.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/event/KeyChangeEvent.java
package net.sourceforge.fidocadj.librarymodel.event; /** Key changed during library operations. I.e. the action of changing the key of a macro. This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014 Kohta Ozaki */ public class KeyChangeEvent { final private Object keyChangedNode; final private Object parentNode; final private String oldKey; /** Standard constructor. @param parentNode node which will become the parent node. @param keyChangedNode node on which the key should be changed. @param oldKey the old key which was associated to the macro. */ public KeyChangeEvent(Object parentNode,Object keyChangedNode,String oldKey) { this.parentNode = parentNode; this.keyChangedNode = keyChangedNode; this.oldKey = oldKey; } /** Returns the value of keyChangedNode. @return the value of keyChangedNode. */ public Object getKeyChangedNode() { return keyChangedNode; } /** Returns the value of parentNode. @return the value of parentNode. */ public Object getParentNode() { return parentNode; } /** Returns the old key. @return the old key. */ public String getOldKey() { return oldKey; } }
1,961
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
LibraryListenerAdapter.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/net/sourceforge/fidocadj/librarymodel/event/LibraryListenerAdapter.java
package net.sourceforge.fidocadj.librarymodel.event; /** Adapter class of LibraryListener interface. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014 Kohta Ozaki </pre> */ public class LibraryListenerAdapter implements LibraryListener { /** Called when a library has been loaded. */ public void libraryLoaded() { // Nothing to do. } /** Called when a node has been renamed. @param e information about the rename event. */ public void libraryNodeRenamed(RenameEvent e) { // Nothing to do. } /** Called when a node has been removed. @param e information about the remove event. */ public void libraryNodeRemoved(RemoveEvent e) { // Nothing to do. } /** Called when a node has been added. @param e information about the added event. */ public void libraryNodeAdded(AddEvent e) { // Nothing to do. } /** Called when a key has been changed in a node @param e information about the key change event. */ public void libraryNodeKeyChanged(KeyChangeEvent e) { // Nothing to do. } }
1,858
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ToolbarTools.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/toolbars/ToolbarTools.java
package toolbars; import android.os.Bundle; import android.widget.ToggleButton; import android.widget.Button; import android.app.FragmentManager; import android.view.View.OnClickListener; import android.view.View; import android.app.Activity; import net.sourceforge.fidocadj.dialogs.DialogLayer; import net.sourceforge.fidocadj.*; import net.sourceforge.fidocadj.circuit.controllers.ElementsEdtActions; /** ANDROID VERSION. Handle the events on the toolbar present in the resources. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Davide Bucci </pre> */ public class ToolbarTools { private ToggleButton selection; private ToggleButton line; private ToggleButton advtext; private ToggleButton bezier; private ToggleButton polygon; private ToggleButton complexcurve; private ToggleButton ellipse; private ToggleButton rectangle; private ToggleButton connection; private ToggleButton pcbline; private ToggleButton pcbpad; private ToggleButton hand; private ToggleButton zoom; private Button layer; private Activity aaParent; private ElementsEdtActions eea; /** Create and add all the required listeners to the toggle buttons. */ public void activateListeners(Activity aa, ElementsEdtActions ee) { eea=ee; eea.setActionSelected(ElementsEdtActions.NONE); getButtons(aa); aaParent=aa; // Quite boring, but easy code. Each listener blanks the state // of all buttons, except the one which has been clicked and // sets the current selected state. selection.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(selection); if(!selection.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.SELECTION); } }); line.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(line); if(!line.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.LINE); } }); advtext.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(advtext); if(!advtext.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.TEXT); } }); bezier.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(bezier); if(!bezier.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.BEZIER); } }); polygon.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(polygon); if(!polygon.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.POLYGON); } }); complexcurve.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(complexcurve); if(!complexcurve.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.COMPLEXCURVE); } }); ellipse.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(ellipse); if(!ellipse.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.ELLIPSE); } }); rectangle.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(rectangle); if(!rectangle.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.RECTANGLE); } }); connection.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(connection); if(!connection.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.CONNECTION); } }); pcbline.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(pcbline); if(!pcbline.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.PCB_LINE); } }); pcbpad.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(pcbpad); if(!pcbpad.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.PCB_PAD); } }); hand.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(hand); if(!hand.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.HAND); } }); /* zoom.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { resetButtons(zoom); if(!zoom.isChecked()) eea.setActionSelected(ElementsEdtActions.NONE); else eea.setActionSelected(ElementsEdtActions.ZOOM); } });*/ layer.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // show layer dialog DialogLayer dl = new DialogLayer(); dl.show(aaParent.getFragmentManager(), ""); } }); } /** Reset the state of all buttons, except the one specified. @param exc the toggle button to exclude from the reset. It can be null, if all buttons should be reset. */ private void resetButtons(ToggleButton exc) { clear(exc); eea.setActionSelected(ElementsEdtActions.NONE); } /** Reset the state of all buttons, except the one specified. @param exc the toggle button to exclude from the reset. It can be null, if all buttons should be reset. */ public void clear(ToggleButton exc) { if(!selection.equals(exc)) selection.setChecked(false); if(!line.equals(exc)) line.setChecked(false); if(!advtext.equals(exc)) advtext.setChecked(false); if(!bezier.equals(exc)) bezier.setChecked(false); if(!polygon.equals(exc)) polygon.setChecked(false); if(!complexcurve.equals(exc)) complexcurve.setChecked(false); if(!ellipse.equals(exc)) ellipse.setChecked(false); if(!rectangle.equals(exc)) rectangle.setChecked(false); if(!connection.equals(exc)) connection.setChecked(false); if(!pcbline.equals(exc)) pcbline.setChecked(false); if(!pcbpad.equals(exc)) pcbpad.setChecked(false); if(!hand.equals(exc)) hand.setChecked(false); //if(!zoom.equals(exc)) zoom.setChecked(false); } /** Associate all the ToggleButtons present in the resources to internal variables. */ private void getButtons(Activity aa) { // get elements of the toolbars created in the resources selection = (ToggleButton) aa.findViewById(R.id.selection); line = (ToggleButton) aa.findViewById(R.id.line); advtext = (ToggleButton) aa.findViewById(R.id.advtext); bezier = (ToggleButton) aa.findViewById(R.id.bezier); polygon = (ToggleButton) aa.findViewById(R.id.polygon); complexcurve = (ToggleButton) aa.findViewById(R.id.complexcurve); ellipse = (ToggleButton) aa.findViewById(R.id.ellipse); rectangle = (ToggleButton) aa.findViewById(R.id.rectangle); connection = (ToggleButton) aa.findViewById(R.id.connection); pcbline = (ToggleButton) aa.findViewById(R.id.pcbline); pcbpad = (ToggleButton) aa.findViewById(R.id.pcbpad); hand = (ToggleButton) aa.findViewById(R.id.hand); layer = (Button) aa.findViewById(R.id.layer); //zoom = (ToggleButton) aa.findViewById(R.id.zoom); } }
8,370
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExplorerActivity.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/com/explorer/ExplorerActivity.java
package com.explorer; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import net.sourceforge.fidocadj.R; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; /** TODO: document class and public methods <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Cronos80, Davide Bucci </pre> */ public class ExplorerActivity extends ListActivity { public static String ROOT = IO.rootDir; public String curDir = ROOT; public String parentDir = ROOT; public static final String FILENAME = "filename"; public static final String DIRECTORY = "directory"; public static final int REQUEST_FILE = 0; public static final int REQUEST_FOLDER = 1; public static final int REQUEST_USER = 2; String _FILENAME = ""; String _DIRECTORY = ""; Context context = null; public boolean FOLDER_SELECTION = false; /** The starting point of the Activity. The file explorer can be used to select files or folder. When you call the activity you must specify the request that can be ExplorerActivity.REQUEST_FILE or ExplorerActivity.REQUEST_FOLDER. I.e.: <pre> myIntent = new Intent(this, ExplorerActivity.class); this.startActivityForResult(myIntent, ExplorerActivity.REQUEST_FILE); </pre> And then in the onActivityResult you need to manage what to do with the directory retrieved. <pre> @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { switch (requestCode) { case ExplorerActivity.REQUEST_FOLDER: // Put code here for handling a folder request dir = data.getExtras().getString( ExplorerActivity.DIRECTORY) break; case ExplorerActivity.REQUEST_FILE: // Put code here for handling a file request file = data.getExtras().getString( ExplorerActivity.FILENAME); default: break; } } } </pre> */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.explorer_list_view); ListView lv = getListView(); lv.setTextFilterEnabled(true); context = this; String path="FidoCadJ/Drawings"; File file = new File(Environment.getExternalStorageDirectory(), path); curDir=file.getAbsolutePath(); parentDir=curDir; FOLDER_SELECTION = getIntent().getBooleanExtra(DIRECTORY, false); if (!FOLDER_SELECTION) { LinearLayout ll=(LinearLayout)findViewById(R.id.explorer_layout); Button bt = (Button) findViewById(R.id.explorer_bt); ll.removeView(bt); } lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parentDir, View view, int position, long id) { String item = (String) ((TextView) view .findViewById(R.id.explorer_tv)).getText(); if (item == "." || item == "..") { if (item == ".") { showDir((new File(curDir)).getAbsolutePath()); } else { showDir((new File(curDir)).getParent()); } } else { File path = new File(curDir + "/" + item); if (path.isDirectory()) { showDir(path.getAbsolutePath()); } else { _FILENAME = path.getAbsolutePath(); doAction(); } } } }); showDir(curDir); } public void doAction() { Intent data = new Intent(); data.putExtra(FILENAME, _FILENAME); data.putExtra(DIRECTORY, _DIRECTORY); setResult(RESULT_OK, data); this.finish(); } protected void browseFile(String absolutePath) { Intent intent = new Intent(); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, 1); } /** Get all the files included in the current directory. @param dir the path of the directory to be listed @return an array containing all the contents of the given dir. */ public String[] getList(String dir) { String[] listDir = new String[] {}; File aDir = new File(dir); if (aDir.isDirectory()) { if (aDir.list() != null) { listDir = aDir.list(); } } if (FOLDER_SELECTION) { listDir = filterFiles(listDir); } String[] defDir = new String[listDir.length + 2]; defDir[0] = "."; // Refresh defDir[1] = ".."; // Up one level System.arraycopy(listDir, 0, defDir, 2, listDir.length); return defDir; } /** Eliminate all the elements in the given list, which correspond to files and not to directories. @param list the array containing the content of a directory @return a list where all the files have been filtered out (so that just the directories are present). */ public String[] filterFiles(String[] list) { List<String> filtered = new ArrayList<String>(); for (String f : list) { if (new File(curDir + "/" + f).isDirectory()) { filtered.add(f); } } return filtered.toArray(new String[] {}); } /** Sets the current dir to be shown. @param dir the dir to be shown. */ public void showDir(String dir) { curDir = dir; File path = new File(dir); setTitle(path.getAbsolutePath()); String[] listDir = getList(path.getAbsolutePath()); Arrays.sort(listDir, new Comparator<String>() { public int compare(String o1, String o2) { return o1.compareTo(o2); } }); setListAdapter(new ExplorerAdapter(this, listDir, path.getAbsolutePath())); } /** Perform a selection of a file. */ public void OnSelectClick(View view) { _DIRECTORY = curDir; Intent data = new Intent(); data.putExtra(FILENAME, _FILENAME); data.putExtra(DIRECTORY, _DIRECTORY); setResult(RESULT_OK, data); this.finish(); } }
6,666
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExplorerAdapter.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/com/explorer/ExplorerAdapter.java
package com.explorer; import java.io.File; import net.sourceforge.fidocadj.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; /** TODO: document class <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Cronos80 </pre> */ public class ExplorerAdapter extends ArrayAdapter<String> { private final Context context; private final String[] items; private final String parentDir; /** * Constructor * */ public ExplorerAdapter(Context context, String[] values, String parent) { super(context, R.layout.explorer_list_item, values); this.context = context; this.items = values; this.parentDir = parent; } /** * Manage the String[] data to populate the adapter * */ @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflater.inflate(R.layout.explorer_list_item, parent, false); TextView tv = (TextView) rowView.findViewById(R.id.explorer_tv); tv.setText(items[position]); TextView tv1 = (TextView) rowView.findViewById(R.id.explorer_count_tv); tv1.setText(""); ImageView iv = (ImageView) rowView.findViewById(R.id.explorer_iv); iv.setImageResource(R.drawable.file); File path = new File(parentDir + "/" + items[position]); if (path.isDirectory() || items[position] == "." || items[position] == "..") { iv.setImageResource(R.drawable.iron_folder); File[] listDir = new File(path.getAbsolutePath()).listFiles(); if (listDir != null && items[position] != "." && items[position] != ".." && listDir.length>0) { tv1.setText(""+listDir.length); } } return rowView; } }
2,628
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
Errors.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/com/explorer/Errors.java
package com.explorer; import java.io.FileNotFoundException; import java.io.IOException; import net.sourceforge.fidocadj.R; import android.content.Context; import android.widget.Toast; /**Manage the error log. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Cronos80 </pre> */ public class Errors { public static Context context=IO.context; /** Called on {@link FileNotFoundException}. * * @param e the {@link Exception} */ public static void FileNotFound(FileNotFoundException e) { Toast.makeText(context, R.string.ERROR_FILE_NOT_FOUND,Toast.LENGTH_SHORT).show(); e.printStackTrace(); } /** Called on {@link IOException}. * * @param e the {@link Exception} */ public static void IO(IOException e) { Toast.makeText(context, R.string.ERROR_IO,Toast.LENGTH_SHORT).show(); e.printStackTrace(); } /** Called on a general {@link Exception}. * * @param e the {@link Exception} */ public static void Unexpected(Exception e) { Toast.makeText(context, R.string.ERROR_UNEXPECTED,Toast.LENGTH_SHORT).show(); e.printStackTrace(); } /** Called on general {@link Exception} that has to be silent. * * @param e the {@link Exception} */ public static void Silent(Exception e) { //e.printStackTrace(); } }
1,925
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
IO.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/OSes/android/fidocadj/src/com/explorer/IO.java
package com.explorer; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import android.content.Context; import android.os.Environment; /** * Provides static functions for reading/writing file. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 by Cronos80 </pre> */ public class IO { public static String rootDir = android.os.Environment .getExternalStorageDirectory().getAbsolutePath(); public static Context context; /** * Read a file and return a {@link String} containing the text in the file. * * @param fileName * the file to open. * @return the {@link String} containing the text read. */ public static String readFile(String fileName) { FileInputStream fis = null; InputStreamReader isr = null; char[] inputBuffer = new char[255]; String data = ""; try { fis = context.openFileInput(fileName); } catch (FileNotFoundException e) { Errors.FileNotFound(e); return data; } isr = new InputStreamReader(fis); try { isr.read(inputBuffer); data = new String(inputBuffer); // Toast.makeText(context, // "Settings read",Toast.LENGTH_SHORT).show(); fis.close(); } catch (IOException e) { Errors.IO(e); } return data.trim(); } /** * Read a file and return a {@link String} containing the text in the file. * * @param fileName * the file to open. * @return the {@link String} containing the text read. */ public static String readFileFromSD(String fileName) { FileInputStream fis = null; String data = ""; byte[] buf = new byte[1024]; try { fis = new FileInputStream(new File(fileName)); while (fis.read(buf) != -1) { data += new String(buf); buf = new byte[1024]; } fis.close(); } catch (FileNotFoundException e) { Errors.FileNotFound(e); return null; } catch (IOException e) { Errors.IO(e); } return data.trim(); } /** * Write a {@link String} to a file. * * @param fileName * the file to write. * @param string * the {@link String} containing the text to write. */ public static void writeFile(String fileName, String string) { FileOutputStream fos = null; try { fos = context.openFileOutput(fileName, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close(); } catch (FileNotFoundException e) { Errors.FileNotFound(e); return; } catch (IOException e) { Errors.IO(e); } } /** * Write a {@link String} to a file. * * @param fileName * the file to write. * @param string * the {@link String} containing the text to write. */ public static void writeFileToSD(String fileName, String string) { FileOutputStream fos = null; try { fos = new FileOutputStream(new File(fileName)); fos.write(string.getBytes()); fos.close(); } catch (FileNotFoundException e) { Errors.FileNotFound(e); return; } catch (IOException e) { Errors.IO(e); } } /** * Check if the file exists in the current app directory. * * @param filename * the file to check. * @return true if the file exists, false otherwise. */ public static boolean checkFile(String filename) { File f = new File(context.getFilesDir(), filename); if (f.exists()) return true; return false; } /** * Check if the file exists. * * @param filename * the absolute path of the file to check. * @return true if the file exists, false otherwise. */ public static boolean checkSDFile(String filename) { File f = new File(filename); if (f.exists()) return true; return false; } public static boolean[] checkEsternalStorage() { boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but // all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } // System.out.println("storage status: "+ // mExternalStorageAvailable +" , " + mExternalStorageWriteable); return new boolean[] { mExternalStorageAvailable, mExternalStorageWriteable }; } public static String joinPath(String[] mList) { String result=""; for(String val : mList){ result+=val+File.separator; } return result.substring(0, result.length()-1); } }
5,737
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/package-info.java
/**<p> Main classes for the FidoCadJ project: FidoMain contains the entry point of the stand alone Swing application, FidoFrame contains the main window of the application. The other classes handle ancillary operations such as specific code dedicated to the user interface (MenuTools, ExportTools, etc...). FidoCadApplet is the launching code for FidoCadJ running in an applet (it is becoming obsolete by now).</p> */ package net.sourceforge.fidocadj;
480
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ScrollGestureRecognizer.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/ScrollGestureRecognizer.java
package net.sourceforge.fidocadj; import javax.swing.*; import java.awt.*; import java.awt.event.*; import net.sourceforge.fidocadj.circuit.CircuitPanel; import net.sourceforge.fidocadj.circuit.controllers.ElementsEdtActions; import net.sourceforge.fidocadj.toolbars.ChangeSelectionListener; /** Employed in FidoCadJ with the author's permission. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2007-2023 Santhosh Kumar T, Davide Bucci </pre> */ public final class ScrollGestureRecognizer implements AWTEventListener, ChangeSelectionListener { private int actionSelected; private boolean oldGesture=false; /* private ScrollGestureRecognizer instance = new ScrollGestureRecognizer(); */ Point location= new Point(); /** Constructor. */ public ScrollGestureRecognizer() { start(); } /** Get the current instance. @return the instance. */ public ScrollGestureRecognizer getInstance() { return this; } /** Start the scroll operation. */ void start() { Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_MOTION_EVENT_MASK); Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.MOUSE_EVENT_MASK); } /** Stop the scroll operation. */ void stop() { Toolkit.getDefaultToolkit().removeAWTEventListener(this); } /** Event dispatched (?) @param event the AWT event dispatched. */ @Override public void eventDispatched(AWTEvent event) { MouseEvent me = (MouseEvent)event; boolean isGesture = (SwingUtilities.isMiddleMouseButton(me) || actionSelected==ElementsEdtActions.HAND) && me.getID()==MouseEvent.MOUSE_DRAGGED; Component co=me.getComponent(); if (!(co instanceof CircuitPanel)) { return; } JViewport viewport = (JViewport)SwingUtilities.getAncestorOfClass(JViewport.class, me.getComponent()); if(viewport==null) { return; } JRootPane rootPane = SwingUtilities.getRootPane(viewport); if(rootPane==null) { return; } Point mouseLocation = SwingUtilities.convertPoint(me.getComponent(), me.getPoint(), rootPane.getGlassPane()); if(!oldGesture && !isGesture) { location=mouseLocation; } oldGesture=isGesture; if(!isGesture) { return; } int deltax = -(mouseLocation.x - location.x); int deltay = -(mouseLocation.y - location.y); location.x=mouseLocation.x; location.y=mouseLocation.y; Point p = viewport.getViewPosition(); p.translate(deltax, deltay); if(p.x<0) { p.x=0; } else if(p.x>=viewport.getView().getWidth()-viewport.getWidth()) { p.x = viewport.getView().getWidth()-viewport.getWidth(); } if(p.y<0) { p.y = 0; } else if(p.y>=viewport.getView().getHeight()-viewport.getHeight()) { p.y = viewport.getView().getHeight()-viewport.getHeight(); } viewport.setViewPosition(p); } /** ChangeSelectionListener interface implementation . @param s the selection state. @param macro the current macro key (if applicable). */ public void setSelectionState(int s, String macro) { actionSelected=s; } /** Set if the strict FidoCAD compatibility mode is active @param strict true if the compatibility with FidoCAD should be obtained. */ public void setStrictCompatibility(boolean strict) { // Nothing is needed here. } /** Get the current editing action (see the constants defined in this class) @return the current editing action */ public int getSelectionState() { return actionSelected; } }
4,661
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
FidoMain.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/FidoMain.java
package net.sourceforge.fidocadj; import javax.swing.*; import java.util.prefs.*; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.circuit.controllers.ParserActions; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.export.ExportGraphic; import net.sourceforge.fidocadj.geom.DrawingSize; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.globals.AccessResources; import net.sourceforge.fidocadj.globals.FileUtils; import net.sourceforge.fidocadj.layers.StandardLayers; import net.sourceforge.fidocadj.timer.MyTimer; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.DimensionG; /** FidoMain.java SWING App: The starting point of FidoCadJ. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class FidoMain { private static CommandLineParser clp; /** Ensure that this is an utility class. */ private FidoMain() {} /** The main method. Process the command line options and if necessary shows an instance of FidoFrame. @param args the command line arguments. */ public static void main(String... args) { clp = new CommandLineParser(); if (args.length>=1) { clp.processArguments(args); } applyOptimizationSettings(clp); // Now we proceed with all the operations: opening files, converting... if(clp.getHeadlessMode()) { // Creates a circuit object DrawingModel pP = new DrawingModel(); if("".equals(clp.getLoadFileName())) { System.err.println("You should specify a FidoCadJ file to"+ " read"); System.exit(1); } // Reads the standard libraries readLibrariesProbeDirectory(pP, false, clp.getLibDirectory()); pP.setLayers(StandardLayers.createStandardLayers()); ParserActions pa=new ParserActions(pP); MyTimer mt = new MyTimer(); try { String txt = FileUtils.readFile(clp.getLoadFileName()); // Here txt contains the new circuit: parse it! pa.parseString(new StringBuffer(txt)); } catch(IllegalArgumentException iae) { System.err.println("Illegal filename"); } catch(Exception e) { System.err.println("Unable to process: "+e); } if (clp.shouldConvertFile()) { doConvert(clp, pP, clp.shouldSplitLayers()); } if (clp.getHasToPrintSize()) { PointG o=new PointG(0,0); DimensionG d = DrawingSize.getImageSize(pP,1, true, o); System.out.println(""+d.width+" "+d.height); } if (clp.getHasToPrintTime()) { System.out.println("Elapsed time: "+mt.getElapsed()+" ms."); } } if (!clp.getCommandLineOnly()) { SwingUtilities.invokeLater(new CreateSwingInterface( clp.getLibDirectory(), clp.getLoadFileName(), clp.getWantedLocale())); } } /** Apply optimisation settings which are platform-dependent. @param clp command-line arguments may deactivate some optimisations. */ private static void applyOptimizationSettings(CommandLineParser clp) { if(!clp.getStripOptimization() && System.getProperty("os.name").startsWith("Mac")) { // CAREFUL************************************************** // In all MacOSX systems I tried, this greatly increases the // redrawing speed. *HOWEVER* the default value for Java 1.6 // as distributed by Apple is "false" (whereas it was "true" // for Java 1.5). This might mean that in a future this can // be not very useful, or worse slowdown the performances. // CAREFUL************************************************** // NOTE: this does not seem to have any effect! System.setProperty("apple.awt.graphics.UseQuartz", "true"); } /* if(!clp.getStripOptimization() && System.getProperty("os.name").toLowerCase().startsWith("linux")) { // CAREFUL************************************************** // Various sources reports that this option will increase // the redrawing speed using Linux. It might happen, however // that the performances can be somewhat degraded in some // systems. // CAREFUL************************************************** // We tested that in version 0.24.1. In fact, activating this // option renders the software inusable in some systems (Nvidia // graphic software?) So this option is definitively turned off. // System.setProperty("sun.java2d.opengl", "true"); // See for example this discussion: http://tinyurl.com/axoxqcb } */ } /** Perform a conversion into a graphic file, from command line parameters. A file should have already been loaded and parsed into pP. This routine also checks if the output file has a correct extension, coherent with the file format chosen. @param clp command-line arguments. @param pP the model containing the drawing. @param splitLayers split layers into different files when exporting. */ private static void doConvert(CommandLineParser clp, DrawingModel pP, boolean splitLayers) { if(!Globals.checkExtension(clp.getOutputFile(), clp.getExportFormat()) && !clp.getForceMode()) { System.err.println( "File extension is not coherent with the "+ "export output format! Use -f to skip this test."); System.exit(1); } try { if (clp.getResolutionBasedExport()) { ExportGraphic.export(new File(clp.getOutputFile()), pP, clp.getExportFormat(), clp.getResolution(), true,false,true, true, splitLayers); } else { ExportGraphic.exportSize(new File(clp.getOutputFile()), pP, clp.getExportFormat(), clp.getXSize(), clp.getYSize(), true,false,true,true, splitLayers); } System.out.println("Export completed"); } catch(IOException ioe) { System.err.println("Export error: "+ioe); } } /** Read all libraries, eventually by inspecting the directory specified by the user. There are three standard directories: IHRAM.FCL, FCDstdlib.fcl and PCB.fcl. If those files are found in the external directory specified, the internal version is not loaded. Other files on the external directory are loaded. @param pP the parsing class in which the libraries should be loaded @param englishLibraries a flag to specify if the internal libraries should be loaded in English or in Italian. @param libDirectoryO the path of the external directory. */ public static void readLibrariesProbeDirectory(DrawingModel pP, boolean englishLibraries, String libDirectoryO) { String libDirectory=libDirectoryO; ParserActions pa = new ParserActions(pP); synchronized(pP) { if (libDirectory == null || libDirectory.length()<3) { libDirectory = System.getProperty("user.home"); } readIHRAM(englishLibraries, libDirectory, pa); readFCDstdlib(englishLibraries, libDirectory, pa); readPCBlib(englishLibraries, libDirectory, pa); readEYLibraries(englishLibraries, libDirectory, pa); readElecLib(englishLibraries, libDirectory, pa); } } /** Read the internal IHRAM library, unless a file called IHRAM.FCL is present in the library directory @param libDirectory path where to search for the library. @param englishLibraries specify if the English version of the lib should be loaded instead of the Italian one. @param pa the object by which the library will be crunched. */ private static void readIHRAM(boolean englishLibraries, String libDirectory, ParserActions pa) { pa.loadLibraryDirectory(libDirectory); if (new File(Globals.createCompleteFileName( libDirectory,"IHRAM.FCL")).exists()) { System.out.println("IHRAM library got from external file"); } else { if(englishLibraries) { pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/IHRAM_en.FCL"), "ihram"); } else { pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/IHRAM.FCL"), "ihram"); } } } /** Read the internal FCDstdlib library, unless a file called FCDstdlib.fcl is present in the library directory @param libDirectory path where to search for the library. @param englishLibraries specify if the English version of the lib should be loaded instead of the Italian one. @param pa the object by which the library will be crunched. */ private static void readFCDstdlib(boolean englishLibraries, String libDirectory, ParserActions pa) { if (new File(Globals.createCompleteFileName( libDirectory,"FCDstdlib.fcl")).exists()) { System.out.println("Standard library got from external file"); } else { if(englishLibraries) { pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/FCDstdlib_en.fcl"), ""); } else { pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/FCDstdlib.fcl"), ""); } } } /** Read the internal PCB library, unless a file called PCB.fcl is present in the library directory @param libDirectory path where to search for the library. @param englishLibraries specify if the English version of the lib should be loaded instead of the Italian one. @param pa the object by which the library will be crunched. */ private static void readPCBlib(boolean englishLibraries, String libDirectory, ParserActions pa) { if (new File(Globals.createCompleteFileName( libDirectory,"PCB.fcl")).exists()) { System.out.println("Standard PCB library got from external file"); } else { if(englishLibraries) { pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/PCB_en.fcl"), "pcb"); } else { pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/PCB.fcl"), "pcb"); } } } /** Read the internal EYLibraries library, unless a file called EY_Libraries.fcl is present in the library directory @param libDirectory path where to search for the library. @param englishLibraries specify if the English version of the lib should be loaded instead of the Italian one. @param pa the object by which the library will be crunched. */ private static void readEYLibraries(boolean englishLibraries, String libDirectory, ParserActions pa) { if(!englishLibraries) { System.out.println("EY library is only available in english"); } if (new File(Globals.createCompleteFileName( libDirectory,"EY_Libraries.fcl")).exists()) { System.out.println("Standard EY_Libraries got from external file"); } else { pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/EY_Libraries.fcl"), "EY_Libraries"); } } /** Read the internal elettrotecnica library, unless a file called elettrotecnica.fcl is present in the library directory @param libDirectory path where to search for the library. @param englishLibraries specify if the English version of the lib should be loaded instead of the Italian one. @param pa the object by which the library will be crunched. */ private static void readElecLib(boolean englishLibraries, String libDirectory, ParserActions pa) { if (new File(Globals.createCompleteFileName( libDirectory,"elettrotecnica.fcl")).exists()) { System.out.println( "Electrotechnics library got from external file"); } else { if(englishLibraries) { pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/elettrotecnica_en.fcl"), "elettrotecnica"); } else { pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/elettrotecnica.fcl"), "elettrotecnica"); } } } } /** Creates the Swing elements needed for the interface. */ class CreateSwingInterface implements Runnable { String libDirectory; String loadFile; Locale currentLocale; /** Constructor where we specify some details concerning the library directory, the file to load (if needed) as well as the locale. @param ld the library directory @param lf the file to load @param ll the locale. */ public CreateSwingInterface (String ld, String lf, Locale ll) { libDirectory = ld; loadFile = lf; currentLocale =ll; } /** Standard constructor. */ public CreateSwingInterface () { libDirectory = ""; loadFile = ""; } /** Run the thread. */ @Override public void run() { /******************************************************************* PLATFORM SELECTION AND CONFIGURATION CODE GOES IN THIS SECTION *******************************************************************/ if (System.getProperty("os.name").startsWith("Mac")) { AccessResources g=new AccessResources(); Preferences.userNodeForPackage(g.getClass()); Globals.weAreOnAMac =true; // These settings allows to obtain menus on the right place System.setProperty("com.apple.macos.useScreenMenuBar","true"); // This is for JVM < 1.5 It won't harm on higher versions. System.setProperty("apple.laf.useScreenMenuBar","true"); // This is for having the good application name in the menu System.setProperty( "com.apple.mrj.application.apple.menu.about.name", "FidoCadJ"); try { System.out.println("Trying to activate VAqua11"); UIManager.setLookAndFeel( "org.violetlib.aqua.AquaLookAndFeel"); System.out.println("VAqua11 look and feel active"); } catch (Exception e) { // Quaqua is not active. Just continue! System.out.println( "The Quaqua look and feel is not available"); System.out.println( "I will continue with the basic Apple l&f"); } } else if (System.getProperty("os.name").startsWith("Win")) { /* If the host system is a window system, select the Windows look and feel. This is a way to encourage people to use FidoCadJ even on a Windows system, forgotting about Java. */ try { UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception eE) { System.out.println("Could not load the Windows Look and feel!"); } } // Un-comment to try to use the Metal LAF /* try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); Globals.weAreOnAMac =false; } catch (Exception E) {} */ /******************************************************************* END OF THE PLATFORM SELECTION CODE *******************************************************************/ // This substitutes the AppleSpecific class for Java >=9 and it is a // much more general and desirable solution. Globals.desktopInt=new ADesktopIntegration(); Globals.desktopInt.registerActions(); // Here we create the main window object FidoFrame popFrame=new FidoFrame(true, currentLocale); if (!"".equals(libDirectory)) { popFrame.libDirectory = libDirectory; } popFrame.init(); // We begin by showing immediately the window. This improves the // perception of speed given to the user, since the libraries // are not yet loaded popFrame.setVisible(true); // We load the libraries (this does not take so long in modern // systems). popFrame.loadLibraries(); // If a file should be loaded, load it now, since popFrame has been // created and initialized. if(!"".equals(loadFile)) { popFrame.getFileTools().load(loadFile); } // We force a global validation of the window size, by including // this time the tree containing the various libraries and the // macros. popFrame.setVisible(true); } }
18,571
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MenuTools.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/MenuTools.java
package net.sourceforge.fidocadj; import javax.swing.*; import javax.swing.event.*; import java.awt.event.*; import java.io.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.circuit.controllers.SelectionActions; import net.sourceforge.fidocadj.circuit.controllers.ElementsEdtActions; import net.sourceforge.fidocadj.circuit.controllers.ParserActions; import net.sourceforge.fidocadj.circuit.controllers.CopyPasteActions; import net.sourceforge.fidocadj.circuit.controllers.EditorActions; import net.sourceforge.fidocadj.circuit.ImageAsCanvas; import net.sourceforge.fidocadj.circuit.CircuitPanel; import net.sourceforge.fidocadj.dialogs.DialogAttachImage; import net.sourceforge.fidocadj.dialogs.DialogAbout; import net.sourceforge.fidocadj.dialogs.DialogLayer; import net.sourceforge.fidocadj.dialogs.EnterCircuitFrame; import net.sourceforge.fidocadj.clipboard.TextTransfer; import net.sourceforge.fidocadj.geom.ChangeCoordinatesListener; /** MenuTools.java Class creating and handling the main menu of FidoCadJ. It contains the methods to create the menu, as well as an event handling system for menu-related operatixons. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see<a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2015-2023 by Davide Bucci </pre> @author Davide Bucci */ public class MenuTools implements MenuListener { JCheckBoxMenuItem libs=new JCheckBoxMenuItem(); /** Create all the menus and associate to them all the needed listeners. @param al the action listener to associate to the menu elements. @return the menu bar. */ public JMenuBar defineMenuBar(ActionListener al) { // Menu creation JMenuBar menuBar=new JMenuBar(); menuBar.add(defineFileMenu(al)); menuBar.add(defineEditMenu(al)); menuBar.add(defineViewMenu(al)); menuBar.add(defineCircuitMenu(al)); // On a MacOSX system, this menu is associated to preferences menu // in the application menu. We do not need to show it in bar. // This needs the AppleSpecific extensions to be active. JMenu about = defineAboutMenu(al); if(!Globals.desktopInt.handleAbout) { menuBar.add(about); } return menuBar; } /** The menuSelected method, useful for the MenuListener interface. @param evt the menu event object. */ @Override public void menuSelected(MenuEvent evt) { // does nothing } /** The menuDeselected method, useful for the MenuListener interface. @param evt the menu event object. */ @Override public void menuDeselected(MenuEvent evt) { // does nothing } /** The menuCanceled method, useful for the MenuListener interface. @param evt the menu event object. */ @Override public void menuCanceled(MenuEvent evt) { // does nothing } /** Create the main File menu. @param al the action listener to associate to the menu. @return the menu. */ public JMenu defineFileMenu(ActionListener al) { JMenu fileMenu=new JMenu(Globals.messages.getString("File")); JMenuItem fileNew = new JMenuItem(Globals.messages.getString("New")); fileNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, Globals.shortcutKey)); JMenuItem fileOpen = new JMenuItem(Globals.messages.getString("Open")); fileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, Globals.shortcutKey)); JMenuItem fileSave = new JMenuItem(Globals.messages.getString("Save")); fileSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Globals.shortcutKey)); JMenuItem fileSaveName = new JMenuItem(Globals.messages.getString("SaveName")); fileSaveName.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Globals.shortcutKey | InputEvent.SHIFT_MASK)); JMenuItem fileSaveNameSplit = new JMenuItem(Globals.messages.getString("Save_split")); JMenuItem fileExport = new JMenuItem(Globals.messages.getString("Export")); fileExport.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, Globals.shortcutKey)); JMenuItem filePrint = new JMenuItem(Globals.messages.getString("Print")); filePrint.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, Globals.shortcutKey)); JMenuItem fileClose = new JMenuItem(Globals.messages.getString("Close")); fileClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, Globals.shortcutKey)); JMenuItem options = new JMenuItem(Globals.messages.getString("Circ_opt")); // Add the items in the file menu. fileMenu.add(fileNew); fileMenu.add(fileOpen); fileMenu.add(fileSave); fileMenu.add(fileSaveName); fileMenu.addSeparator(); fileMenu.add(fileSaveNameSplit); fileMenu.addSeparator(); fileMenu.add(fileExport); fileMenu.add(filePrint); fileMenu.addSeparator(); // On a MacOSX system, options is associated to preferences menu // in the application menu. We do not need to show it in File. // This needs the AppleSpecific extensions to be active. if(!Globals.desktopInt.handlePreferences) { fileMenu.add(options); fileMenu.addSeparator(); } fileMenu.add(fileClose); // Define all the action listeners fileNew.addActionListener(al); fileOpen.addActionListener(al); fileExport.addActionListener(al); filePrint.addActionListener(al); fileClose.addActionListener(al); fileSave.addActionListener(al); fileSaveName.addActionListener(al); fileSaveNameSplit.addActionListener(al); options.addActionListener(al); return fileMenu; } /** Define the Edit main menu. @param al the action listener to associate to the menu. @return the menu. */ public JMenu defineEditMenu(ActionListener al) { JMenu editMenu = new JMenu(Globals.messages.getString("Edit_menu")); JMenuItem editUndo = new JMenuItem(Globals.messages.getString("Undo")); editUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Globals.shortcutKey)); //editUndo.setEnabled(false); JMenuItem editRedo = new JMenuItem(Globals.messages.getString("Redo")); editRedo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Globals.shortcutKey | InputEvent.SHIFT_MASK)); //editRedo.setEnabled(false); JMenuItem editCut = new JMenuItem(Globals.messages.getString("Cut")); editCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Globals.shortcutKey)); JMenuItem editCopy = new JMenuItem(Globals.messages.getString("Copy")); editCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Globals.shortcutKey)); JMenuItem editCopySplit = new JMenuItem(Globals.messages.getString("Copy_split")); editCopySplit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, Globals.shortcutKey)); JMenuItem editCopyImage = new JMenuItem(Globals.messages.getString("Copy_as_image")); editCopySplit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, Globals.shortcutKey)); JMenuItem editPaste = new JMenuItem(Globals.messages.getString("Paste")); editPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Globals.shortcutKey)); JMenuItem clipboardCircuit = new JMenuItem(Globals.messages.getString("DefineClipboard")); JMenuItem editSelectAll = new JMenuItem(Globals.messages.getString("SelectAll")); editSelectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, Globals.shortcutKey)); JMenuItem editDuplicate = new JMenuItem(Globals.messages.getString("Duplicate")); editDuplicate.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, Globals.shortcutKey)); JMenuItem editRotate = new JMenuItem(Globals.messages.getString("Rotate")); editRotate.setAccelerator(KeyStroke.getKeyStroke("R")); JMenuItem editMirror = new JMenuItem(Globals.messages.getString("Mirror_E")); editMirror.setAccelerator(KeyStroke.getKeyStroke("S")); editUndo.addActionListener(al); editRedo.addActionListener(al); editCut.addActionListener(al); editCopy.addActionListener(al); editCopySplit.addActionListener(al); editCopyImage.addActionListener(al); editPaste.addActionListener(al); editSelectAll.addActionListener(al); editDuplicate.addActionListener(al); editMirror.addActionListener(al); editRotate.addActionListener(al); clipboardCircuit.addActionListener(al); editMenu.add(editUndo); editMenu.add(editRedo); editMenu.addSeparator(); editMenu.add(editCut); editMenu.add(editCopy); editMenu.add(editCopySplit); editMenu.add(editCopyImage); editMenu.add(editPaste); editMenu.add(clipboardCircuit); editMenu.add(editDuplicate); editMenu.addSeparator(); editMenu.add(editSelectAll); editMenu.addSeparator(); editMenu.add(editRotate); editMenu.add(editMirror); return editMenu; } /** Define the main View menu. @param al the action listener to associate to the menu. @return the menu. */ public JMenu defineViewMenu(ActionListener al) { JMenu viewMenu=new JMenu(Globals.messages.getString("View")); JMenuItem layerOptions = new JMenuItem(Globals.messages.getString("Layer_opt")); layerOptions.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, Globals.shortcutKey)); layerOptions.addActionListener(al); viewMenu.add(layerOptions); JMenuItem attachImage = new JMenuItem(Globals.messages.getString("Attach_image_menu")); attachImage.addActionListener(al); viewMenu.add(attachImage); viewMenu.addSeparator(); libs = new JCheckBoxMenuItem(Globals.messages.getString("Libs")); viewMenu.add(libs); libs.addActionListener(al); return viewMenu; } /** Define the main Circuit menu. @param al the action listener to associate to the menu. @return the menu. */ public JMenu defineCircuitMenu(ActionListener al) { JMenu circuitMenu=new JMenu(Globals.messages.getString("Circuit")); JMenuItem defineCircuit = new JMenuItem(Globals.messages.getString("Define")); defineCircuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, Globals.shortcutKey)); circuitMenu.add(defineCircuit); JMenuItem updateLibraries = new JMenuItem(Globals.messages.getString("LibraryUpdate")); updateLibraries.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, Globals.shortcutKey)); circuitMenu.add(updateLibraries); defineCircuit.addActionListener(al); updateLibraries.addActionListener(al); return circuitMenu; } /** Change the state of the show libs toggle menu item. @param s the state of the item. */ public void setShowLibsState(boolean s) { libs.setState(s); } /** Define the main About menu. @param al the action listener to associate to the menu. @return the menu. */ public JMenu defineAboutMenu(ActionListener al) { JMenu about = new JMenu(Globals.messages.getString("About")); JMenuItem aboutMenu = new JMenuItem(Globals.messages.getString("About_menu")); about.add(aboutMenu); aboutMenu.addActionListener(al); return about; } /** Process the menu events. @param evt the event. @param fff the frame in which the menu is present. @param coordL the coordinate listener to show messages if needed. */ public void processMenuActions(ActionEvent evt, FidoFrame fff, ChangeCoordinatesListener coordL) { ExportTools et = fff.getExportTools(); et.setCoordinateListener(coordL); PrintTools pt = fff.getPrintTools(); CircuitPanel cc = fff.cc; String arg=evt.getActionCommand(); EditorActions edt=cc.getEditorActions(); CopyPasteActions cpa=cc.getCopyPasteActions(); ElementsEdtActions eea = cc.getContinuosMoveActions(); SelectionActions sa = cc.getSelectionActions(); ParserActions pa = cc.getParserActions(); // Edit the FidoCadJ code of the drawing if (arg.equals(Globals.messages.getString("Define"))) { EnterCircuitFrame circuitDialog=new EnterCircuitFrame(fff, cc.getParserActions().getText(!cc.extStrict).toString()); circuitDialog.setVisible(true); pa.parseString(new StringBuffer(circuitDialog.getStringCircuit())); cc.getUndoActions().saveUndoState(); fff.repaint(); } else if (arg.equals(Globals.messages.getString("LibraryUpdate"))) { // Update libraries fff.loadLibraries(); fff.show(); } else if (arg.equals(Globals.messages.getString("Circ_opt"))) { // Options for the current drawing fff.showPrefs(); } else if (arg.equals(Globals.messages.getString("Layer_opt"))) { // Options for the layers DialogLayer layerDialog=new DialogLayer(fff,cc.dmp.getLayers()); layerDialog.setVisible(true); // It is important that we force a complete recalculation of // all details in the drawing, otherwise the buffered setup // will not be responsive to the changes in the layer editing. cc.dmp.setChanged(true); fff.repaint(); } else if(arg.equals(Globals.messages.getString("Libs"))) { fff.showLibs(!fff.areLibsVisible()); libs.setState(fff.areLibsVisible()); } else if (arg.equals(Globals.messages.getString("Print"))) { // Print the current drawing pt.associateToCircuitPanel(cc); pt.printDrawing(fff); } else if (arg.equals(Globals.messages.getString("SaveName"))) { // Save with name fff.getFileTools().saveWithName(false); } else if (arg.equals(Globals.messages.getString("Save_split"))) { // Save with name, split non standard macros fff.getFileTools().saveWithName(true); } else if (arg.equals(Globals.messages.getString("Save"))) { // Save with the current name (if available) fff.getFileTools().save(false); } else if (arg.equals(Globals.messages.getString("New"))) { // New drawing fff.createNewInstance(); } else if (arg.equals(Globals.messages.getString("Undo"))) { // Undo the last action cc.getUndoActions().undo(); fff.repaint(); } else if (arg.equals(Globals.messages.getString("Redo"))) { // Redo the last action cc.getUndoActions().redo(); fff.repaint(); } else if (arg.equals(Globals.messages.getString("About_menu"))) { // Show the about menu DialogAbout d=new DialogAbout(fff); d.setVisible(true); } else if (arg.equals(Globals.messages.getString("Open"))) { // Open a file OpenFile openf=new OpenFile(); openf.setParam(fff); /* The following code would require a thread safe implementation of some of the inner classes (such as CircuitModel), which was indeed not the case... Now, yes! */ SwingUtilities.invokeLater(openf); } else if (arg.equals(Globals.messages.getString("Export"))) { // Export the current drawing et.launchExport(fff, cc, fff.getFileTools().openFileDirectory); } else if (arg.equals(Globals.messages.getString("SelectAll"))) { // Select all elements in the current drawing sa.setSelectionAll(true); // Even if the drawing is not changed, a repaint operation is // needed since all selected elements are rendered in green. fff.repaint(); } else if (arg.equals(Globals.messages.getString("Copy"))) { // Copy all selected elements in the clipboard cpa.copySelected(!cc.extStrict, false); } else if (arg.equals(Globals.messages.getString("Copy_split"))) { // Copy elements, splitting non standard macros cpa.copySelected(!cc.extStrict, true); } else if (arg.equals(Globals.messages.getString("Copy_as_image"))) { // Display a dialog similar to the Export menu and create an image // that is stored in the clipboard, using a bitmap or vector //format. et.exportAsCopiedImage(fff, cc); } else if (arg.equals(Globals.messages.getString("Cut"))) { // Cut all the selected elements cpa.copySelected(!cc.extStrict, false); edt.deleteAllSelected(true); fff.repaint(); } else if (arg.equals(Globals.messages.getString("Mirror_E"))) { // Mirror all the selected elements if(eea.isEnteringMacro()) { eea.mirrorMacro(); } else { edt.mirrorAllSelected(); } fff.repaint(); } else if (arg.equals(Globals.messages.getString("Rotate"))) { // 90 degrees rotation of all selected elements if(eea.isEnteringMacro()) { eea.rotateMacro(); } else { edt.rotateAllSelected(); } fff.repaint(); } else if (arg.equals(Globals.messages.getString("Duplicate"))) { // Duplicate cpa.copySelected(!cc.extStrict, false); cpa.paste(cc.getMapCoordinates().getXGridStep(), cc.getMapCoordinates().getYGridStep()); fff.repaint(); } else if (arg.equals(Globals.messages.getString("DefineClipboard"))) { // Paste as a new circuit TextTransfer textTransfer = new TextTransfer(); //FidoFrame popFrame; if(cc.getUndoActions().getModified()) { fff.createNewInstance(); } pa.parseString( new StringBuffer(textTransfer.getClipboardContents())); fff.repaint(); } else if (arg.equals(Globals.messages.getString("Paste"))) { // Paste some graphical elements cpa.paste(cc.getMapCoordinates().getXGridStep(), cc.getMapCoordinates().getYGridStep()); fff.repaint(); } else if (arg.equals(Globals.messages.getString("Close"))) { // Close the current window if(!fff.getFileTools().checkIfToBeSaved()) { return; } fff.closeThisFrame(); } else if(arg.equals(Globals.messages.getString("Attach_image_menu"))){ // Show the attach image dialog. ImageAsCanvas ii=fff.cc.getAttachedImage(); DialogAttachImage di = new DialogAttachImage(fff); di.setFilename(ii.getFilename()); di.setCorner(ii.getCornerX(),ii.getCornerY()); di.setResolution(ii.getResolution()); di.setVisible(true); if(di.shouldAttach()) { try{ if(di.getShowImage()) { ii.loadImage(di.getFilename()); } else { ii.removeImage(); } ii.setResolution(di.getResolution()); ii.setCorner(di.getCornerX(),di.getCornerY()); } catch (IOException e) { JOptionPane.showMessageDialog(fff, Globals.messages.getString("Can_not_attach_image"), "", JOptionPane.INFORMATION_MESSAGE); } } } } }
21,381
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
FileTools.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/FileTools.java
package net.sourceforge.fidocadj; import java.io.*; import java.util.prefs.*; import javax.swing.*; import java.awt.*; import java.util.Locale; import net.sourceforge.fidocadj.circuit.CircuitPanel; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.export.ExportGraphic; /** FileTools.java Class performing high level user interface operation involving files. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2015-2023 by Davide Bucci </pre> @author Davide Bucci */ public class FileTools { final private FidoFrame fff; final private Preferences prefs; // Open/save default properties public String openFileDirectory; /** Standard constructor. @param f the frame which should be associated to those file operations. @param p the preferences where to read/write settings (or null if they should not be saved). */ public FileTools (FidoFrame f, Preferences p) { fff=f; prefs=p; openFileDirectory = ""; } /** Read the preferences associated to file behaviour (if a preference element is available). */ public void readPrefs() { // The open file directory if (prefs!=null) { openFileDirectory = prefs.get("OPEN_DIR", ""); } } /** Ask the user if the current file should be saved and do it if yes. @return true if the window should be closed or false if the closing action has been cancelled. */ public boolean checkIfToBeSaved() { boolean shouldExit = true; if (fff.cc.getUndoActions().getModified()) { Object[] options = { Globals.messages.getString("Save"), Globals.messages.getString("Do_Not_Save"), Globals.messages.getString("Cancel_btn")}; // We try to show in the title bar of the dialog the file name of // the drawing to which the dialog refers to. If not, we just // write Warning! String filename=Globals.messages.getString("Warning"); if(!"".equals(fff.cc.getParserActions().openFileName)) { filename=fff.cc.getParserActions().openFileName; } int choice=JOptionPane.showOptionDialog(fff, Globals.messages.getString("Warning_unsaved"), Globals.prettifyPath(filename,35), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, //the titles of buttons options[0]); //default button title) // Those constant names does not reflect the actual // message shown on the buttons. if(choice==JOptionPane.YES_OPTION) { // Save and exit //System.out.println("Save and exit."); if(!save(false)) { shouldExit=false; } } else if (choice==JOptionPane.CANCEL_OPTION) { // Don't exit shouldExit = false; } } if(shouldExit) { fff.cc.getUndoActions().doTheDishes(); } return shouldExit; } /** Open the current file. @throws IOException if the file can not be opened. */ public void openFile() throws IOException { BufferedReader bufRead = null; StringBuffer txt = new StringBuffer(); try { bufRead = new BufferedReader( new InputStreamReader(new FileInputStream( fff.cc.getParserActions().openFileName), Globals.encoding)); String line = bufRead.readLine(); while (line != null) { txt.append(line); txt.append("\n"); line = bufRead.readLine(); } } finally { if(bufRead!=null) { bufRead.close(); } } // Here txt contains the new circuit: draw it! fff.cc.getParserActions().parseString( new StringBuffer(txt.toString())); // Calculate the zoom to fit fff.zoomToFit(); fff.cc.getUndoActions().saveUndoState(); fff.cc.getUndoActions().setModified(false); fff.repaint(); } /** Show the file dialog and save with a new name name. This routine makes use of the standard dialogs (either the Swing or the native one, depending on the host operating system), in order to let the user choose a new name for the file to be saved. @return true if the save operation has gone well. @param splitNonStandardMacroS decides whether the non standard macros should be split during the save operation. */ public boolean saveWithName(boolean splitNonStandardMacroS) { String fin; String din; if(Globals.useNativeFileDialogs) { // File chooser provided by the host system. // Vastly better on MacOSX, but probably not such on other // operating systems. FileDialog fd = new FileDialog(fff, Globals.messages.getString("SaveName"), FileDialog.SAVE); fd.setDirectory(openFileDirectory); fd.setFilenameFilter(new FilenameFilter(){ @Override public boolean accept(File dir, String name) { return name.toLowerCase(Locale.US).endsWith(".fcd"); } }); fd.setVisible(true); fin=fd.getFile(); din=fd.getDirectory(); } else { // File chooser provided by Swing. // Better on Linux JFileChooser fc = new JFileChooser(); fc.setFileFilter(new javax.swing.filechooser.FileFilter(){ @Override public boolean accept(File f) { return f.getName().toLowerCase(Locale.US).endsWith(".fcd") || f.isDirectory(); } @Override public String getDescription() { return "FidoCadJ (.fcd)"; } }); // Set the current working directory as well as the file name. fc.setCurrentDirectory(new File(openFileDirectory)); fc.setDialogTitle(Globals.messages.getString("SaveName")); if(fc.showSaveDialog(fff)!=JFileChooser.APPROVE_OPTION) { return false; } fin=fc.getSelectedFile().getName(); din=fc.getSelectedFile().getParentFile().getPath(); } if(fin== null) { return false; } else { fff.cc.getParserActions().openFileName= Globals.createCompleteFileName(din, fin); fff.cc.getParserActions().openFileName = Globals.adjustExtension( fff.cc.getParserActions().openFileName, Globals.DEFAULT_EXTENSION); if (prefs!=null) { prefs.put("OPEN_DIR", din); } openFileDirectory=din; // Here everything is ready for saving the current drawing. return save(splitNonStandardMacroS); } } /** Save the current file. @param splitNonStandardMacroS decides whether the non standard macros should be split during the save operation. @return true if the save operation has gone well. */ public boolean save(boolean splitNonStandardMacroS) { CircuitPanel cc=fff.cc; // If there is not a name currently defined, we use instead the // save with name function. if("".equals(cc.getParserActions().openFileName)) { return saveWithName(splitNonStandardMacroS); } try { if (splitNonStandardMacroS) { /* In fact, splitting the nonstandard macro when saving a file is indeed an export operation. This ease the job, since while exporting in a vector graphic format one has indeed to split macros. */ ExportGraphic.export(new File( cc.getParserActions().openFileName), cc.dmp, "fcd", 1.0,true,false, !cc.extStrict, false,false); cc.getUndoActions().setModified(false); } else { // Create file BufferedWriter output = null; try { output= new BufferedWriter(new OutputStreamWriter(new FileOutputStream( cc.getParserActions().openFileName), Globals.encoding)); output.write("[FIDOCAD]\n"); output.write( cc.getParserActions().getText(!cc.extStrict) .toString()); } finally { if(output!=null) { output.close(); } } cc.getUndoActions().setModified(false); } } catch (IOException fnfex) { JOptionPane.showMessageDialog(fff, Globals.messages.getString("Save_error")+fnfex); return false; } return true; } /** Load the given file @param s the name of the file to be loaded. */ public void load(String s) { fff.cc.getParserActions().openFileName= s; try { openFile(); } catch (IOException fnfex) { JOptionPane.showMessageDialog(fff, Globals.messages.getString("Open_error")+fnfex); } } }
10,486
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
CommandLineParser.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/CommandLineParser.java
package net.sourceforge.fidocadj; import java.util.Locale; import net.sourceforge.fidocadj.globals.Globals; /** CommandLineParser.java Parse the command line recognizing options, commands and files. Only the parsing is done. The operations needed should be then be done by checking the state of an instance of this object after that the options have been parsed. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2015-2023 by Davide Bucci </pre> @author Davide Bucci */ public class CommandLineParser { // If this is true, the GUI will not be loaded and FidoCadJ will run as // a command line utility: private boolean commandLineOnly = false; // Force FidoCadJ to skip some sanity tests during the command line // option processing. private boolean forceMode=false; // The following variable will be true if one requests to convert a // file: private boolean convertFile = false; private int totx=0; private int toty=0; private String exportFormat=""; private String outputFile=""; private boolean headlessMode = false; private boolean resolutionBasedExport = false; private boolean printSize=false; private boolean printTime=false; private boolean splitLayers=false; private double resolution=1; private Locale currentLocale=null; // Filename to open or a particular library directory to be considered private String loadFile=""; private String libDirectory=""; // The standard behavior implies that FidoCadJ tries to activate some // optimizations or settings which depends on the platform and should // increase things such as the redrawing speed and other stuff. In some // cases ("-p" option) they might be deactivated: private static boolean stripOptimization=false; /** Get the value of the strip optimization flag. @return true if platform-dependent optimizations should not be applied. */ public boolean getStripOptimization() { return stripOptimization; } /** Get the name (completed with the given path) of the filename to read. @return the file name, or "" if no file has been given */ public String getLoadFileName() { return loadFile; } /** Get the name (completed with the given path) of the directory containing the libraries to be loaded. @return the path, or "" if no dir has been given. */ public String getLibDirectory() { return libDirectory; } /** Read the current command line arguments and parse it. @param orArgs the command line arguments, as provided to the main. */ public void processArguments(String... orArgs) { int i; boolean loaded=false; boolean nextLib=false; String[] args=orArgs; // called by jnlp if ("-print".equalsIgnoreCase(args[0])) { // TODO: verify if this can happen in a operating system // with case sensitive file system! Windows only code? String filename = args[1].toLowerCase(Locale.US).replace(".fcd", ""); if (filename.lastIndexOf(System.getProperty("file.separator"))>0) { filename = filename.substring(filename.lastIndexOf( System.getProperty("file.separator"))+1); } args = ("-n -c r72 pdf "+filename+".pdf " // NOPMD +args[1]).split(" "); // NOPMD suppressed PMD false positive } for(i=0; i<args.length; ++i) { if (args[i].startsWith("-")) { // It is an option // phylum if ("-open".equalsIgnoreCase(args[i].trim())) { continue; } if (args[i].startsWith("-k")) { // -k: show the current locale System.out.println("Detected locale: "+ Locale.getDefault().getLanguage()); } else if (args[i].startsWith("-n")) { // -n indicates that FidoCadJ should run only with // the command line interface, without showing any // GUI. commandLineOnly=true; System.setProperty("java.awt.headless", "true"); } else if (args[i].startsWith("-d")) { // -d indicates that the following argument is the path // of the library directory. The previous library // directory will be ignored. nextLib=true; } else if (args[i].startsWith("-f")) { // -f forces FidoCadJ to skip some of the sanity checks // for example in file extensions while exporting. forceMode=true; } else if (args[i].startsWith("-m")) { // -m indicates that during export multiple layers should // be exported towards multiple files. splitLayers=true; } else if (args[i].startsWith("-c")) { // -c indicates that FidoCadJ should read and convert // the given file. The structure of the command must // be as follows: // -c 800 600 png test.png // which is the total width and height in pixel, the // format required (SVG, EPS, PGF, PNG, PDF, EPS, SCH) // and the file name to be used. // The second possibility is that the -c option is // followed by the r option, followed by a number // specifying the number of pixels for logical units. try { ++i; if (args[i].startsWith("r")) { resolution = Double.parseDouble( args[i].substring(1)); resolutionBasedExport = true; if (resolution<=0) { System.err.println("Resolution should be"+ " a positive real number"); System.exit(1); } } else { totx=Integer.parseInt(args[i]); toty=Integer.parseInt(args[++i]); } exportFormat=args[++i]; outputFile=args[++i]; convertFile=true; headlessMode = true; } catch (Exception eE) { System.err.println("Unable to read the parameters"+ " given to -c"); System.exit(1); } convertFile=true; } else if (args[i].startsWith("-h")) { // Zu Hilfe! showCommandLineHelp(); System.exit(0); } else if (args[i].startsWith("-s")) { // Get size headlessMode = true; printSize=true; } else if (args[i].startsWith("-t")) { // Timer printTime=true; } else if (args[i].startsWith("-p")) { // No optimizations stripOptimization=true; } else if (args[i].startsWith("-l")) { // Locale // Extract the code corresponding to the wanted locale String loc; if(args[i].length()==2) { // In this case, the -l xx form is used, where // xx indicates the wanted locale. A space // separates "-l" from the wanted locale. // At first, check if the user forgot the locale if(i==args.length-1 || args[i+1].startsWith("-")) { System.err.println("-l option requires a "+ "locale language code."); System.exit(1); } loc=args[++i]; } else { // In this case, the -lxx form is used, where // xx indicates the wanted locale. No space is // used. loc=args[i].substring(2); } currentLocale=new Locale(loc); } else { System.err.println("Unrecognized option: "+args[i]); showCommandLineHelp(); System.exit(1); } } else { // We should process now the arguments of the different // options (if it applies). if (nextLib) { // This is -d: read the new library directory libDirectory= args[i]; System.out.println("Changed the library directory: " +args[i]); } else { if (loaded) { System.err.println("Only one file can be"+ " specified in the command line"); } // We can not load the file now, since the main frame // has not been initialized yet. loadFile=args[i]; loaded=true; } nextLib=false; } } } /** Print a short summary of each option available for launching FidoCadJ. */ public void showCommandLineHelp() { // Here, exceptionally, the lenght of the code lines might exceed // 80 characters. //CHECKSTYLE.OFF: LineLength String help = "\nThis is FidoCadJ, version "+Globals.version+".\n"+ "By the FidoCadJ team, 2007-2020.\n\n"+ "Use: java -jar fidocadj-0.24.8.jar [-options] [file] \n"+ "where options include:\n\n"+ " -n Do not start the graphical user interface (headless mode)\n\n"+ " -d Set the extern library directory\n"+ " Usage: -d dir\n"+ " where 'dir' is the path of the directory you want to use.\n\n"+ " -c Convert the given file to a graphical format.\n"+ " Usage: -c sx sy eps|pdf|svg|png|jpg|fcd|sch outfile\n"+ " If you use this command line option, you *must* specify a FidoCadJ\n"+ " file to convert.\n"+ " An alternative is to specify the resolution in pixels per logical unit\n"+ " by preceding it by the letter 'r' (without spaces), instead of giving\n"+ " sx and sy.\n"+ " NOTE: the correctness of the file extension is checked, unless the -f\n"+ " option is specified.\n\n"+ " -m if a file export is done towards a vector graphic file format, split\n"+ " the layers and write one file for each layer. The file name will be\n"+ " obtained by appending _ followed by the layer number to the specified\n"+ " file name. For example, the following command will create files\n"+ " test_0.svg, test_1.svg ... from the drawing contained in test.fcd:\n\n"+ " java -jar fidocadj.jar -n -m -c r2 svg test.svg test.fcd\n\n"+ " -s Print the size of the specified file in logical units.\n\n"+ " -h Print this help and exit.\n\n"+ " -t Print the time used by FidoCadJ for the specified operation.\n\n"+ " -p Do not activate some platform-dependent optimizations. You might try\n"+ " this option if FidoCadJ hangs or is painfully slow.\n\n"+ " -l Force FidoCadJ to use a certain locale (the code might follow\n"+ " immediately or be separated by an optional space).\n\n"+ " -k Show the current locale.\n\n"+ " -f Force FidoCadJ to skip some sanity tests on the input data.\n\n"+ " [file] The optional (except if you use the -d or -s options) FidoCadJ file to\n"+ " load at startup time.\n\n"+ "Example: load and convert a FidoCadJ drawing to a 800x600 pixel png file\n"+ " without using the GUI.\n"+ " java -jar fidocadj.jar -n -c 800 600 png out1.png test1.fcd\n\n"+ "Example: load and convert a FidoCadJ drawing to a png file without using the\n"+ " graphic user interface (the so called headless mode).\n"+ " Each FidoCadJ logical unit will be converted in 2 pixels on the image.\n"+ " java -jar fidocadj.jar -n -c r2 png out2.png test2.fcd\n\n"+ "Example: load FidoCadJ forcing the locale to simplified Chinese (zh).\n"+ " java -jar fidocadj.jar -l zh\n\n"; //CHECKSTYLE.ON: LineLength System.out.println(help); } /** Check if layers must be split into different files when exporting into a vector file format. @return true if it's the case. */ public boolean shouldSplitLayers() { return splitLayers; } /** Check if a file conversion (export) should be done. @return true if an export should be done. */ public boolean shouldConvertFile() { return convertFile; } /** Return a string describing the file format. @return the description of the file format, as provided by the user, or "" if nothing has been specified. */ public String getExportFormat() { return exportFormat; } /** Get the name of the output file @return the name of the output file, or "" if nothing has been specified. */ public String getOutputFile() { return outputFile; } /** Get the width of the export @return the width in pixels of the image to be exported. */ public int getXSize() { return totx; } /** Get the height of the export @return the heght in pixels of the image to be exported. */ public int getYSize() { return toty; } /** Check if the headless mode (no UI) should be active. @return true if the Java headless mode should be activated. */ public boolean getHeadlessMode() { return headlessMode; } /** Check if the export should be done on a resolution based and not by creating an image of a given height and width. @return true if the export should be done calculating the image size by taking into account the desired resolution. */ public boolean getResolutionBasedExport() { return resolutionBasedExport; } /** Get the wanted locale. @return the wanted locale object, or null if no hint about it has been given in the command line. */ public Locale getWantedLocale() { return currentLocale; } /** Check if the size of the drawing (in logical units) has to be printed. @return true if the size has to be printed. */ public boolean getHasToPrintSize() { return printSize; } /** Check if the time employed to perform an action has to be printed. @return true if the time has to be printed. */ public boolean getHasToPrintTime() { return printTime; } /** Get the resolution to be employed for the graphic export. @return the resolution in pixels for logical unit. */ public double getResolution() { return resolution; } /** Check if some sanity checks over the options should be skipped. @return true if the command line should be interpreted as is, even it contains something strange such as a wrong file extension and so on. */ public boolean getForceMode() { return forceMode; } /** Check if only the command line interface should be used. @return true if only the command line interface is to be used (i.e. no GUI will be started). */ public boolean getCommandLineOnly() { return commandLineOnly; } }
17,308
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExportTools.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/ExportTools.java
package net.sourceforge.fidocadj; import javax.swing.*; import java.util.prefs.*; import java.io.*; import java.awt.*; import java.awt.image.*; import javax.imageio.*; import java.awt.datatransfer.*; import net.sourceforge.fidocadj.circuit.CircuitPanel; import net.sourceforge.fidocadj.dialogs.DialogCopyAsImage; import net.sourceforge.fidocadj.dialogs.DialogExport; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.geom.ChangeCoordinatesListener; /** ExportTools.java Class performing interface operations for launching export operations. It also reads and stores preferences. This class also contains code to export a drawing as a picture, then load the exported image in the clipboard. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2015-2023 by Davide Bucci </pre> @author Davide Bucci */ public class ExportTools implements ClipboardOwner { // Export default properties private String exportFilename; private String exportFormat; private boolean exportBlackWhite; private double exportUnitPerPixel; private double exportMagnification; private int exportXsize; private int exportYsize; private boolean exportResolutionBased; private boolean splitLayers; final private Preferences prefs; private ChangeCoordinatesListener coordL; /** Standard constructor. @param p the preferences object which will be used to save or retrieve the settings. If null, preferences will not be stored. */ public ExportTools(Preferences p) { exportFilename=""; exportMagnification=1.0; prefs=p; exportBlackWhite=false; exportFormat = ""; splitLayers=false; } /** Read the preferences regarding the export. */ public void readPrefs() { if(prefs!=null) { exportFormat = prefs.get("EXPORT_FORMAT", "png"); exportUnitPerPixel= Double.parseDouble( prefs.get("EXPORT_UNITPERPIXEL", "1")); exportMagnification = Double.parseDouble( prefs.get("EXPORT_MAGNIFICATION", "1")); exportBlackWhite = "true".equals(prefs.get("EXPORT_BW", "false")); exportXsize = Integer.parseInt( prefs.get("EXPORT_XSIZE", "800")); exportYsize = Integer.parseInt( prefs.get("EXPORT_YSIZE", "600")); exportResolutionBased = "true".equals( prefs.get("EXPORT_RESOLUTION_BASED","false")); splitLayers = "true".equals(prefs.get("EXPORT_SPLIT_LAYERS", "false")); } } /** Show a dialog for exporting the current drawing in the clipboard. @param fff the parent frame which will be used for dialogs and message boxes. @param cC the CircuitPanel containing the drawing to be exported. */ public void exportAsCopiedImage(JFrame fff, CircuitPanel cC) { // At first, we create and configure the dialog allowing the user // to choose the exporting options DialogCopyAsImage dcai=new DialogCopyAsImage(fff, cC.getDrawingModel()); dcai.setAntiAlias(true); dcai.setXsizeInPixels(exportXsize); dcai.setYsizeInPixels(exportYsize); dcai.setResolutionBasedExport(exportResolutionBased); dcai.setUnitPerPixel(exportUnitPerPixel); dcai.setBlackWhite(exportBlackWhite); // Once configured, we show the modal dialog dcai.setVisible(true); if (dcai.shouldExport()) { exportUnitPerPixel=dcai.getUnitPerPixel(); exportBlackWhite=dcai.getBlackWhite(); exportResolutionBased=dcai.getResolutionBasedExport(); try { exportXsize=dcai.getXsizeInPixels(); exportYsize=dcai.getYsizeInPixels(); } catch (NumberFormatException eE) { JOptionPane.showMessageDialog(null, Globals.messages.getString("Format_invalid"), Globals.messages.getString("Warning"), JOptionPane.INFORMATION_MESSAGE ); exportXsize=100; exportYsize=100; } // We do the export RunExport doExport = new RunExport(); doExport.setCoordinateListener(coordL); try { File fexp=File.createTempFile("FidoCadJ",".png"); doExport.setParam(fexp, cC.dmp, "png", exportUnitPerPixel, dcai.getAntiAlias(),exportBlackWhite,!cC.extStrict, exportResolutionBased, exportXsize, exportYsize, false, fff); doExport.run(); BufferedImage img = null; img = ImageIO.read(fexp); setClipboard(img); } catch (IOException eE) { System.err.println("Issues reading image: "+eE); } if(prefs!=null) { prefs.put("EXPORT_UNITPERPIXEL", ""+exportUnitPerPixel); prefs.put("EXPORT_MAGNIFICATION", ""+exportMagnification); prefs.put("EXPORT_BW", exportBlackWhite?"true":"false"); prefs.put("EXPORT_RESOLUTION_BASED", exportResolutionBased?"true":"false"); prefs.put("EXPORT_XSIZE", ""+exportXsize); prefs.put("EXPORT_YSIZE", ""+exportYsize); } } } /** Show a dialog for exporting the current drawing. @param fff the parent frame which will be used for dialogs and message boxes. @param cC the CircuitPanel containing the drawing to be exported. @param openFileDirectory the directory where to search if no file name has been already defined for the export (for example, because it is the first time an export is done). */ public void launchExport(JFrame fff, CircuitPanel cC, String openFileDirectory) { // At first, we create and configure the dialog allowing the user // to choose the exporting options DialogExport export=new DialogExport(fff, cC.getDrawingModel()); export.setAntiAlias(true); export.setFormat(exportFormat); export.setXsizeInPixels(exportXsize); export.setYsizeInPixels(exportYsize); export.setResolutionBasedExport(exportResolutionBased); export.setSplitLayers(splitLayers); // The default export directory is the same where the FidoCadJ file // are opened. if("".equals(exportFilename)) { exportFilename=openFileDirectory; } export.setFilename(exportFilename); export.setUnitPerPixel(exportUnitPerPixel); export.setBlackWhite(exportBlackWhite); export.setMagnification(exportMagnification); // Once configured, we show the modal dialog export.setVisible(true); if (export.shouldExport()) { exportFilename=export.getFilename(); exportFormat=export.getFormat(); // The resolution based export should be used only for bitmap // file formats if("png".equals(exportFormat) || "jpg".equals(exportFormat)) { exportResolutionBased=export.getResolutionBasedExport(); exportUnitPerPixel=export.getUnitPerPixel(); } else { exportResolutionBased=true; exportUnitPerPixel = export.getMagnification(); } exportBlackWhite=export.getBlackWhite(); exportMagnification = export.getMagnification(); splitLayers=export.getSplitLayers(); try { exportXsize=export.getXsizeInPixels(); exportYsize=export.getYsizeInPixels(); } catch (NumberFormatException eE) { JOptionPane.showMessageDialog(null, Globals.messages.getString("Format_invalid"), Globals.messages.getString("Warning"), JOptionPane.INFORMATION_MESSAGE ); exportXsize=100; exportYsize=100; } File f = new File(exportFilename); // We first check if the file is a directory if(f.isDirectory()) { JOptionPane.showMessageDialog(null, Globals.messages.getString("Warning_noname"), Globals.messages.getString("Warning"), JOptionPane.INFORMATION_MESSAGE ); return; } int selection; // We first check if the file name chosen by the user has a correct // file extension, coherent with the file format chosen. if(!Globals.checkExtension(exportFilename, exportFormat)) { selection = JOptionPane.showConfirmDialog(null, Globals.messages.getString("Warning_extension"), Globals.messages.getString("Warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); // If useful, we correct the extension. if(selection==JOptionPane.OK_OPTION) { exportFilename = Globals.adjustExtension( exportFilename, exportFormat); } f = new File(exportFilename); } // If the file already exists, we asks for confirmation if(f.exists()) { selection = JOptionPane.showConfirmDialog(null, Globals.messages.getString("Warning_overwrite"), Globals.messages.getString("Warning"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if(selection!=JOptionPane.OK_OPTION) { return; } } // We do the export RunExport doExport = new RunExport(); doExport.setCoordinateListener(coordL); // Here we use the multithreaded structure of Java. doExport.setParam(new File(exportFilename), cC.dmp, exportFormat, exportUnitPerPixel, export.getAntiAlias(),exportBlackWhite,!cC.extStrict, exportResolutionBased, exportXsize, exportYsize, splitLayers, fff); SwingUtilities.invokeLater(doExport); if(prefs!=null) { prefs.put("EXPORT_FORMAT", exportFormat); prefs.put("EXPORT_UNITPERPIXEL", ""+exportUnitPerPixel); prefs.put("EXPORT_MAGNIFICATION", ""+exportMagnification); prefs.put("EXPORT_BW", exportBlackWhite?"true":"false"); prefs.put("EXPORT_RESOLUTION_BASED", exportResolutionBased?"true":"false"); prefs.put("EXPORT_XSIZE", ""+exportXsize); prefs.put("EXPORT_YSIZE", ""+exportYsize); prefs.put("EXPORT_SPLIT_LAYERS", splitLayers?"true":"false"); } /* The following code would require a thread safe implementation of some of the inner classes (such as CircuitModel), which is indeed not the case... Thread thread = new Thread(doExport); thread.setDaemon(true); // Start the thread thread.start(); */ } } /** Called by the system when the application looses ownership over the clipboard contents. This is here because an export operation is done when the "Copy as a picture" operation is performed. @param clip the current clipboard object. @param trans tha object to be transfered. */ @Override public void lostOwnership(Clipboard clip, Transferable trans) { // There is no need to do something in particular. } /** Set the coordinate listener which is employed here for showing message in a non-invasive way. @param c the listener. */ public void setCoordinateListener(ChangeCoordinatesListener c) { coordL=c; } /** This method writes a image to the system clipboard. @param image the image to be loaded in the clipboard. */ public void setClipboard(Image image) { TransferableImage imgSel = new TransferableImage(image); Toolkit.getDefaultToolkit().getSystemClipboard().setContents( imgSel, this); } /** Origin of this code: https://stackoverflow.com/questions/4552045/copy-bufferedimage-to-clipboard DB: I checked it, it seems reasonable and robust and it works well. Using macOS, I noticed that the system was not working for Java version 1.7. The types of the object copied in the clipboard were not those that standard macOS applications expect. I updated to Java 14 and it started to work flawlessly. */ private static class TransferableImage implements Transferable { final Image i; public TransferableImage(Image i) { this.i = i; } @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (flavor.equals(DataFlavor.imageFlavor) && i != null) { return i; } else { throw new UnsupportedFlavorException(flavor); } } @Override public DataFlavor[] getTransferDataFlavors() { DataFlavor[] flavors = new DataFlavor[1]; flavors[0] = DataFlavor.imageFlavor; return flavors; } @Override public boolean isDataFlavorSupported(DataFlavor flavor) { DataFlavor[] flavors = getTransferDataFlavors(); for (DataFlavor f: flavors) { if (flavor.equals(f)) { return true; } } return false; } } }
14,954
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DragDropTools.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/DragDropTools.java
package net.sourceforge.fidocadj; import java.io.*; import java.awt.dnd.*; import java.awt.datatransfer.*; /** DragDropTools.java Class handling the drag and drop operations. TODO: improve the descriptions in the Javadoc comments. Sometimes are cryptical or uninformative. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2015-2023 by Davide Bucci </pre> @author Davide Bucci */ public class DragDropTools implements DropTargetListener { FidoFrame fff; /** Constructor. @param f the frame to which the drag and drop tools should be associated. */ public DragDropTools(FidoFrame f) { fff=f; } /** This implementation of the DropTargetListener interface is heavily inspired on the example given here: http://www.java-tips.org/java-se-tips/javax.swing/how-to-implement-drag- drop-functionality-in-your-applic.html @param dtde the drop target drag event */ @Override public void dragEnter(DropTargetDragEvent dtde) { // does nothing } /** Exit from the drag target. @param dte the drop target event. */ @Override public void dragExit(DropTargetEvent dte) { // does nothing } /** Drag over the target. @param dtde the drop target drag event. */ @Override public void dragOver(DropTargetDragEvent dtde) { // does nothing } /** Drop action changed. @param dtde the drop target drag event. */ @Override public void dropActionChanged(DropTargetDragEvent dtde) { // does nothing } /** This routine is called when a drag and drop of an useful file is done on an open instance of FidoCadJ. The difficulty is that depending on the operating system flavor, the files are handled differently. For that reason, we check a few things and we need to differentiate several cases. @param dtde the drop target event. */ @Override public void drop(DropTargetDropEvent dtde) { try { Transferable tr = dtde.getTransferable(); DataFlavor[] flavors = tr.getTransferDataFlavors(); if (flavors==null) { return; } for (DataFlavor df : flavors) { // try to avoid problematic situations if(df==null) { return; } // check the correct type of the drop flavor if (df.isFlavorJavaFileListType()) { // Great! Accept copy drops... dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); // And add the list of file names to our text area java.util.List list = (java.util.List)tr.getTransferData(df); FidoFrame popFrame; if(fff.cc.getUndoActions().getModified()) { popFrame = fff.createNewInstance(); } else { popFrame=fff; } // Only the first file of the list will be opened popFrame.cc.getParserActions().openFileName= ((File)list.get(0)).getAbsolutePath(); popFrame.getFileTools().openFile(); // If we made it this far, everything worked. dtde.dropComplete(true); return; } // Ok, is it another Java object? else if (df.isFlavorSerializedObjectType()) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); Object o = tr.getTransferData(df); // If there is a valid FidoCad code, try to draw it. FidoFrame popFrame; if(fff.cc.getUndoActions().getModified()) { popFrame = fff.createNewInstance(); } else { popFrame=fff; } popFrame.cc.getParserActions().parseString( new StringBuffer(o.toString())); popFrame.cc.getUndoActions().saveUndoState(); popFrame.cc.getUndoActions().setModified(false); dtde.dropComplete(true); popFrame.cc.repaint(); return; } // How about an input stream? In some Linux flavors, it contains // the file name, with a few substitutions. else if (df.isRepresentationClassInputStream()) { // Everything seems to be ok here, so we proceed handling // the file InputStreamReader reader=null; BufferedReader in=null; dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); try { reader=new InputStreamReader( (InputStream)tr.getTransferData(df)); in=new BufferedReader(reader); String line=""; int k; line = in.readLine(); while (line != null) { k=line.indexOf("file://"); if (k>=0) { FidoFrame popFrame; if(fff.cc.getUndoActions().getModified()) { popFrame=fff.createNewInstance(); } else { popFrame=fff; } popFrame.cc.getParserActions().openFileName = line.substring(k+7); // Deprecated! It should indicate the encoding, // but WE WANT the encoding using being the // same of the host system. It may be // deprecated, but it is the correct behaviour, // here. popFrame.cc.getParserActions().openFileName = java.net.URLDecoder.decode( popFrame.cc.getParserActions(). openFileName); // After we set the current file name, we just // open it. popFrame.getFileTools().openFile(); popFrame.cc.getUndoActions().saveUndoState(); popFrame.cc.getUndoActions().setModified(false); break; } line = in.readLine(); } } finally { if(in!=null) { in.close(); } if(reader!=null) { reader.close(); } } fff.cc.repaint(); dtde.dropComplete(true); return; } } // Hmm, the user must not have dropped a file list System.out.println("Drop failed: " + dtde); dtde.rejectDrop(); } catch (Exception e) { e.printStackTrace(); dtde.rejectDrop(); } } }
8,257
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrintTools.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/PrintTools.java
package net.sourceforge.fidocadj; import javax.swing.*; import javax.print.attribute.*; import javax.print.attribute.standard.*; import java.awt.print.*; import java.awt.*; import java.util.*; import java.awt.geom.*; import net.sourceforge.fidocadj.circuit.CircuitPanel; import net.sourceforge.fidocadj.dialogs.print.DialogPrint; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.DrawingSize; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.swing.Graphics2DSwing; import net.sourceforge.fidocadj.graphic.swing.ColorSwing; import net.sourceforge.fidocadj.layers.LayerDesc; /** PrintTools.java Class performing interface operations for launching print operations. It also reads and stores preferences. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2015-2023 by Davide Bucci </pre> @author Davide Bucci */ public class PrintTools implements Printable { // Settings related to the printing modes. private boolean printMirror; // Mirror the printed output. private boolean printFitToPage; // Fit to the page. private boolean printLandscape; // Put the page in the landscape mode. private boolean printBlackWhite; // Black and white. private int currentLayerSelected; // Layer to print. If negative=all. // Margins private double topMargin=-1; private double bottomMargin=-1; private double leftMargin=-1; private double rightMargin=-1; private CircuitPanel cc; private boolean showMargins; private final static double MULT=16.0; // Multiplying 72dp times MULT private final static double INCH=2.54; // in cm private final static double NATIVERES=72.0; // in dpi /** Standard constructor. */ public PrintTools() { // some standard configurations printMirror = false; printFitToPage = false; printLandscape = false; adjustMargins(PrinterJob.getPrinterJob().defaultPage()); showMargins = false; currentLayerSelected=-1; } /** If the values of the margins are negative, they will be adjusted in such a way that the printable area will be covered in the most efficient way. */ private void adjustMargins(PageFormat pf) { final double correction=0.01; // Start of the imageable region, in centimeters. if(leftMargin<0.0) { leftMargin=pf.getImageableX()/NATIVERES*INCH+correction; } if(topMargin<0.0) { topMargin=pf.getImageableY()/NATIVERES*INCH+correction; } if(rightMargin<0.0) { rightMargin=(pf.getWidth()-pf.getImageableX() -pf.getImageableWidth())/NATIVERES*INCH+correction; } if(bottomMargin<0.0) { bottomMargin=(pf.getHeight()-pf.getImageableY() -pf.getImageableHeight())/NATIVERES*INCH+correction; } } /** Determine if the margins should be shown or not. @param sm true if the margins should be shown (for example, in a print preview operation). */ public void setShowMargins(boolean sm) { showMargins=sm; } /** Set the size of the margins, in centimeters. The orientation of those margins should correspond to the page in the portrait orientation. @param tm top margin. @param bm bottom margin. @param lm left margin. @param rm right margin. */ public void setMargins(double tm, double bm, double lm, double rm) { if(tm>0.0) { topMargin=tm; } if(bm>0.0) { bottomMargin=bm; } if(lm>0.0) { leftMargin=lm; } if(rm>0.0) { rightMargin=rm; } } /** Associate to a given CircuitPanel containing the circuit to be printed. @param rCC the CircuitPanel containing the drawing to be exported. */ public void associateToCircuitPanel(CircuitPanel rCC) { cc=rCC; } /** Show a dialog for printing the current drawing. @param fff the parent frame which will be used for dialogs and message boxes. */ public void printDrawing(JFrame fff) { PrinterJob job = PrinterJob.getPrinterJob(); PageFormat pp = job.defaultPage(); DialogPrint dp=new DialogPrint(fff, cc.getDrawingModel(), pp); dp.setMirror(printMirror); dp.setFit(printFitToPage); dp.setBW(printBlackWhite); dp.setLandscape(printLandscape); dp.setMaxMargins(pp.getWidth()/NATIVERES*INCH, pp.getHeight()/NATIVERES*INCH); dp.setMargins(topMargin, bottomMargin, leftMargin, rightMargin); boolean noexit; do { // Show the (modal) dialog. dp.setVisible(true); noexit=configurePrinting(dp, pp,true); if (!dp.shouldPrint()) { return; } } while (noexit); try { // Launch printing. executePrinting(job); } catch (PrinterException ex) { // The job did not successfully complete JOptionPane.showMessageDialog(fff, Globals.messages.getString("Print_uncomplete")); } } /** Configure the printing object by reading the current settings of the DialogPrint employed for the user interaction. @param dp the printing dialog. @param pp the standard page format. @param checkMarginSize if true, the size of the margins is checked and an error message is issued in case of problems. @return true if the printing operation should not be done and the dialog should be shown again. */ public boolean configurePrinting(DialogPrint dp, PageFormat pp, boolean checkMarginSize) { boolean noexit=false; if (!dp.shouldPrint() && checkMarginSize) { return true; } // Get some information about the printing options. printMirror = dp.getMirror(); printFitToPage = dp.getFit(); printLandscape = dp.getLandscape(); printBlackWhite=dp.getBW(); try { topMargin=dp.getTMargin(); bottomMargin=dp.getBMargin(); leftMargin=dp.getLMargin(); rightMargin=dp.getRMargin(); } catch (NumberFormatException n) { System.out.println( Globals.messages.getString("Format_invalid")); } if(checkMarginSize && (topMargin/INCH*NATIVERES<pp.getImageableY() || bottomMargin/INCH*NATIVERES<pp.getHeight() -pp.getImageableHeight()-pp.getImageableY() || leftMargin/INCH*NATIVERES<pp.getImageableX() || rightMargin/INCH*NATIVERES<pp.getWidth() -pp.getImageableWidth()-pp.getImageableX())) { int answer = JOptionPane.showConfirmDialog(dp, Globals.messages.getString("Print_outside_regions"), "",JOptionPane.YES_NO_OPTION); if(answer!= JOptionPane.YES_OPTION) { noexit=true; } } currentLayerSelected=dp.getSingleLayerToPrint(); // Deselect all elements. cc.getSelectionActions().setSelectionAll(false); return noexit; } /** Low level printing operations. @param job the current printing job. */ private void executePrinting(PrinterJob job) throws PrinterException { job.setPrintable(this); if (job.printDialog()) { PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); // Set the correct printing orientation. if (printLandscape) { aset.add(OrientationRequested.LANDSCAPE); } else { aset.add(OrientationRequested.PORTRAIT); } job.print(aset); } } /** The printing interface (prints one page). @param g the graphic context. @param pf the page format. @param page the page number. @return PAGE_EXISTS if the page has to be printed. @throws PrinterException if a printing error occurs. */ @Override public int print(Graphics g, PageFormat pf, int page) throws PrinterException { // This is not a "real" margin, but just a tiny amount which ensures // that even when the calculations are rounded up, the printout does // not span erroneously over multiple pages. int security=5; // This might be explained as follows: // 1 - The Java printing system normally works with an internal // resolution which is 72 dpi (probably inspired by Postscript). // 2 - To have a sufficient resolution, this is increased by 16 times, // by using the scale method of the graphic object associated to the // printer. This gives a 72 dpi * 16=1152 dpi resolution. // 3 - The 0.127 mm pitch used in FidoCadJ corresponds to a 200 dpi // resolution. Calculating 1152 dpi / 200 dpi gives the 5.76 constant // for the zoom. double xscale = 1.0/MULT; // Set 1152 logical units for an inch double yscale = 1.0/MULT; // as the standard resolution is 72 double zoom = NATIVERES*MULT/200.0;// in a 1152 dpi resolution is 1:1 double shownWidth; // Printed region (taking into account double shownHeight; // margins). Graphics2D g2d = (Graphics2D)g; AffineTransform oldTransform = g2d.getTransform(); // Mark with a light red the unprintable area of the sheet. if(showMargins) { g2d.setColor(new Color(255,200,200)); g2d.fillRect(0,0, (int)pf.getImageableX(), (int)pf.getHeight()); g2d.fillRect(0,0, (int)pf.getWidth(), (int)pf.getImageableY()); g2d.fillRect((int)(pf.getImageableX()+pf.getImageableWidth()), 0, (int)pf.getImageableX(), (int)pf.getHeight()); g2d.fillRect(0, (int)(pf.getImageableY()+pf.getImageableHeight()), (int)pf.getWidth(), (int)(pf.getHeight()- pf.getImageableHeight()-pf.getImageableY())); } // User (0,0) is typically outside the imageable area, so we must // translate by the X and Y values in the PageFormat to avoid clipping, // taking into account the margins which are needed. if (printMirror) { g2d.translate(pf.getWidth()-rightMargin/INCH*NATIVERES, topMargin/INCH*NATIVERES); g2d.scale(-xscale,yscale); } else { g2d.translate(leftMargin/INCH*NATIVERES, topMargin/INCH*NATIVERES); g2d.scale(xscale,yscale); } shownWidth=(pf.getWidth()- (leftMargin+rightMargin)/INCH*NATIVERES)*MULT; shownHeight=(pf.getHeight()- (topMargin+bottomMargin)/INCH*NATIVERES)*MULT; // The current margins are shown with a dashed black line. Rectangle2D.Double border = new Rectangle2D.Double(0, 0, shownWidth-2*security, shownHeight-2*security); if(showMargins) { float dashBorder[] = {150.0f}; BasicStroke dashed = new BasicStroke(50.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dashBorder, 0.0f); g2d.setStroke(dashed); g2d.setColor(Color.black); g2d.draw(border); } // Clip the drawing inside the borders. g2d.clip(border); MapCoordinates m; // Perform an adjustement if we need to fit the drawing to the page. if (printFitToPage) { MapCoordinates n = DrawingSize.calculateZoomToFit( cc.getDrawingModel(), (int)((pf.getWidth()-(leftMargin+rightMargin) /INCH*NATIVERES)*MULT) -2*security, (int)((pf.getHeight()-(topMargin+bottomMargin) /INCH*NATIVERES)*MULT) -2*security, true); zoom=n.getXMagnitude(); } m=new MapCoordinates(); m.setMagnitudes(zoom, zoom); PointG o=new PointG(0,0); DimensionG dim = DrawingSize.getImageSize( cc.getDrawingModel(), zoom, true, o); int imageWidth = dim.width; int imageHeight = dim.height; // Calculate how many pages are needed in the horisontal and in the // vertical dimensions. The printout will be organized as a mosaic. int npagesx = (int)Math.ceil(imageWidth/(double)shownWidth); int npagesy = (int)Math.ceil(imageHeight/(double)shownHeight); // Calculate the total number of pages. int npages=npagesx*npagesy; // Current pages of the mosaic. int pagex=page % npagesx; int pagey=page / npagesx; if(printFitToPage) { g2d.translate(-o.x,-o.y); } // Check if printing is finished. if(page>=npages) { g2d.setTransform(oldTransform); return NO_SUCH_PAGE; } // Check if we need more than one page if (page>0) { g2d.translate(-(shownWidth*pagex),0); g2d.translate(0,-(shownHeight*pagey)); } java.util.List<LayerDesc> ol=cc.dmp.getLayers(); // Check if only one layer should be printed. if(currentLayerSelected>=0) { cc.dmp.drawOnlyLayer=currentLayerSelected; } // Check if the drawing should be black and white if(printBlackWhite) { java.util.List<LayerDesc> v=new Vector<LayerDesc>(); // Here we create an alternative array of layers in // which all colors are pitch black. This may be // useful for PCB's. for (int i=0; i<LayerDesc.MAX_LAYERS;++i) { v.add(new LayerDesc(new ColorSwing(Color.black), ((LayerDesc)ol.get(i)).getVisible(), "B/W",((LayerDesc)ol.get(i)).getAlpha())); } cc.dmp.setLayers(v); } Graphics2DSwing graphicSwing = new Graphics2DSwing(g2d); // This is important for taking into account the dashing size graphicSwing.setZoom(m.getXMagnitude()); // Now we perform our rendering cc.drawingAgent.draw(graphicSwing, m); if(currentLayerSelected>=0) { cc.dmp.setDrawOnlyPads(true); cc.drawingAgent.draw(new Graphics2DSwing(g2d), m); cc.dmp.setDrawOnlyPads(false); cc.dmp.drawOnlyLayer=-1; } cc.dmp.setLayers(ol); g2d.setTransform(oldTransform); /* tell the caller that this page is part of the printed document */ return PAGE_EXISTS; } }
15,733
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ADesktopIntegration.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/ADesktopIntegration.java
package net.sourceforge.fidocadj; import java.awt.*; import java.awt.desktop.*; import javax.swing.*; import net.sourceforge.fidocadj.dialogs.DialogAbout; import net.sourceforge.fidocadj.globals.Globals; /** The class ADesktopIntegration implements a few mechanism for interacting with the operating system. This class requires Java 9 at least, with the (much welcomed from my part) java.awt.Desktop object. Previously, the integration with the OS was handled only on MacOSX, thanks to a class called AppleSpecific, relying on the obsolete com.apple.eawt package. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2020-2023 by Davide Bucci </pre> */ public class ADesktopIntegration implements AboutHandler, PreferencesHandler, QuitHandler, OpenFilesHandler { public boolean handleAbout; // True if the About action is handled public boolean handlePreferences; // True if the Pref action is handled ADesktopIntegration() { // Empty constructor. } /** Check if some actions are made available by the operating system and if it is the case, register them. For example, MacOS usually inserts the About and Preferences menus in a specific place in the "FidoCadJ" menu, that does not exist in other platforms. This means that the OS needs to know what to call when one of those two actions is selected. This is given to the operating system by this routine. */ public void registerActions() { if(!Desktop.isDesktopSupported()) { return; } handleAbout=true; handlePreferences=true; Desktop d=Desktop.getDesktop(); try { d.setOpenFileHandler(this); d.setQuitHandler(this); } catch(UnsupportedOperationException eE) { // This can be ignored, we are going to live without it. System.err.println( "Warning: unsupported exception while setting handlers."); } try { d.setAboutHandler(this); } catch(UnsupportedOperationException eE) { handleAbout=false; } try { d.setPreferencesHandler(this); } catch(UnsupportedOperationException eE) { handlePreferences=false; } } /** Respond to an user double clicking on a FCD file @param e event referring for application. */ @Override public void openFiles (OpenFilesEvent e) { String file = e.getFiles().get(0).getAbsolutePath(); ((FidoFrame)Globals.activeWindow).getFileTools().load(file); } /** Respond to an user clicking on an About menu. @param e event referring for application. */ @Override public void handleAbout (AboutEvent e) { DialogAbout d=new DialogAbout((JFrame)Globals.activeWindow); d.setVisible(true); } /** Respond to an user clicking on the Preferences menu. @param e event referring for application. */ @Override public void handlePreferences (PreferencesEvent e) { ((FidoFrame)Globals.activeWindow).showPrefs(); } /** Ask for confirmation when quitting. @param e event referring for application. @param response the type of the response (quit or abort). */ @Override public void handleQuitRequestWith(QuitEvent e, QuitResponse response) { boolean ca = true; // I tried with an iterator, but when closing windows the map is // changed and the iterator does not like that at all. // This method seems safer and avoids raising exception // java.util.ConcurrentModificationException (#179). Object[] windowArray=Globals.openWindows.toArray(); FidoFrame fff; /* for(int i=0; i<windowArray.length;++i) { */ for(Object ff : windowArray) { fff=(FidoFrame)ff; if(fff.getFileTools().checkIfToBeSaved()) { fff.closeThisFrame(); } else { ca = false; } } if(ca) { response.performQuit(); } else { response.cancelQuit(); } } }
4,914
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
RunExport.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/RunExport.java
package net.sourceforge.fidocadj; import javax.swing.*; import java.io.*; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.export.ExportGraphic; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.geom.ChangeCoordinatesListener; /** The RunExport class implements a runnable class which can be employed to perform all exporting operations in a separate thread from the main user interface one. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2012-2023 by Davide Bucci </pre> @author Davide Bucci */ class RunExport implements Runnable { private File file; private DrawingModel dmp; private String format; private double unitPerPixel; private boolean antiAlias; private boolean blackWhite; private boolean ext; private boolean resBased; private boolean splitLayers; private int xsize; private int ysize; private JFrame parent; private ChangeCoordinatesListener coordL; /** Setting up the parameters needed for the export @param tfile the file name @param tP the DrawingModel object containing the drawing to be exported @param tformat the file format to be used @param tunitPerPixel the magnification factor to be used for the export (used only if resb is true). @param tantiAlias the application of anti alias for bitmap export @param tblackWhite black and white export. @param text export advanced FidoCadJ code (if applicable). @param resb if true, the export is based on the resolution. @param xs the x size of the drawing (used only if resb is false). @param ys the y size of the drawing (used only if resb is false). @param splitL if true split layers in different files. @param text the extensions to be activated or not */ public void setParam(File tfile, DrawingModel tP, String tformat, double tunitPerPixel, boolean tantiAlias, boolean tblackWhite, boolean text, boolean resb, int xs, int ys, boolean splitL, JFrame tparent) { file=tfile; dmp = tP; format = tformat; unitPerPixel = tunitPerPixel; antiAlias= tantiAlias; blackWhite=tblackWhite; ext=text; xsize=xs; ysize=ys; resBased=resb; parent=tparent; splitLayers=splitL; } /** Set the coordinate listener which is employed here for showing message in a non-invasive way. @param c the listener. */ public void setCoordinateListener(ChangeCoordinatesListener c) { coordL=c; } /** Launch the export (in a new thread). */ @Override public void run() { try { if(resBased) { ExportGraphic.export(file, dmp, format, unitPerPixel, antiAlias, blackWhite, ext, true, splitLayers); } else { ExportGraphic.exportSize(file, dmp, format, xsize, ysize, antiAlias, blackWhite, ext, true, splitLayers); } // It turns out (Issue #117) that this dialog is too disruptive. // If we can, we opt for a much less invasive message if(coordL==null) { // Needed for thread safety! SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(parent, Globals.messages.getString("Export_completed")); } }); } else { // Needed for thread safety! // Much les disruptive version of the message. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { coordL.changeInfos( Globals.messages.getString("Export_completed")); } }); } } catch(final IOException ioe) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(parent, Globals.messages.getString("Export_error")+ioe); } }); } catch(IllegalArgumentException iae) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(parent, Globals.messages.getString("Illegal_filename")); } }); } catch(OutOfMemoryError|NegativeArraySizeException om) { // It is not entirely clear to me (DB) why a negative array size // exception occours when there are memory issues creating the // images. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(parent, Globals.messages.getString("Eport_Memory_Error")); } }); } } }
6,001
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
OpenFile.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/OpenFile.java
package net.sourceforge.fidocadj; import javax.swing.*; import net.sourceforge.fidocadj.globals.Globals; import java.io.*; import java.awt.*; import java.util.Locale; /** OpenFile.java <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2012-2023 by Davide Bucci </pre> The OpenFile class allows to open a new file by using threads. @author Davide Bucci */ class OpenFile implements Runnable { private FidoFrame parent=null; /** Set up the parent window object @param tparent the FidoFrame parent asking for a file open. */ public void setParam(FidoFrame tparent) { parent=tparent; } /** Open a new file, eventually in a new window if the current one contains some unsaved elements. We pay attention to show the file chooser dialog which appears to be the best looking one on each operating system. */ @Override public void run() { String fin; String din; if(Globals.useNativeFileDialogs) { // File chooser provided by the host system. // Vastly better on MacOSX FileDialog fd = new FileDialog(parent, Globals.messages.getString("Open")); fd.setDirectory(parent.getFileTools().openFileDirectory); fd.setFilenameFilter(new FilenameFilter(){ @Override public boolean accept(File dir, String name) { return name.toLowerCase( parent.getLocale()).endsWith(".fcd"); } }); fd.setVisible(true); fin=fd.getFile(); din=fd.getDirectory(); } else { // File chooser provided by Swing. // Better on Linux JFileChooser fc = new JFileChooser(); fc.setCurrentDirectory( new File(parent.getFileTools().openFileDirectory)); fc.setDialogTitle(Globals.messages.getString("Open")); fc.setFileFilter(new javax.swing.filechooser.FileFilter(){ @Override public boolean accept(File f) { return f.getName().toLowerCase(Locale.US) .endsWith(".fcd")||f.isDirectory(); } @Override public String getDescription() { return "FidoCadJ (.fcd)"; } }); if(fc.showOpenDialog(parent)!=JFileChooser.APPROVE_OPTION) { return; } fin=fc.getSelectedFile().getName(); din=fc.getSelectedFile().getParentFile().getPath(); } // We now have the directory as well as the file name, so we can // open it! if(fin!= null) { File f=new File(Globals.createCompleteFileName(din, fin)); // We first check if the file name chosen by the user has a correct // file extension, coherent with the file format chosen. // In reality, a confirm is asked to the user only if the selected // file exists and if it has a non standard extension. if(!Globals.checkExtension(fin, Globals.DEFAULT_EXTENSION)) { int selection; if(f.exists()) { selection = JOptionPane.showConfirmDialog(null, Globals.messages.getString("Warning_extension"), Globals.messages.getString("Warning"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); } else { selection=JOptionPane.OK_OPTION; } // If useful, we correct the extension. if(selection==JOptionPane.OK_OPTION) { fin = Globals.adjustExtension( fin, Globals.DEFAULT_EXTENSION); } } try { // DOUBT: this might be done not on a new thread, but in the // normal Swing one. FidoFrame popFrame; if(parent.cc.getUndoActions().getModified() || !parent.cc.dmp.isEmpty()) { // Here we create a new window in order to display // the file. popFrame=new FidoFrame(parent.runsAsApplication, parent.getLocale()); popFrame.init(); popFrame.setBounds(parent.getX()+20, parent.getY()+20, popFrame.getWidth(), popFrame.getHeight()); popFrame.loadLibraries(); popFrame.setVisible(true); } else { // Here we do not create the new window and we // reuse the current one to load and display the // file to be loaded popFrame=parent; } popFrame.cc.getParserActions().openFileName= Globals.createCompleteFileName(din, fin); if (parent.runsAsApplication) { parent.prefs.put("OPEN_DIR", din); } popFrame.getFileTools().openFileDirectory=din; popFrame.getFileTools().openFile(); popFrame.cc.getUndoActions().saveUndoState(); popFrame.cc.getUndoActions().setModified(false); } catch (IOException fnfex) { JOptionPane.showMessageDialog(parent, Globals.messages.getString("Open_error")+fnfex); } } } }
6,381
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
FidoFrame.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/FidoFrame.java
package net.sourceforge.fidocadj; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; import java.awt.event.InputEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowFocusListener; import javax.swing.*; import java.io.*; import java.util.*; import java.net.*; import java.util.prefs.*; import net.sourceforge.fidocadj.dialogs.DialogUtil; import net.sourceforge.fidocadj.dialogs.DialogOptions; import net.sourceforge.fidocadj.dialogs.DialogAbout; import net.sourceforge.fidocadj.geom.DrawingSize; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.globals.AccessResources; import net.sourceforge.fidocadj.globals.Utf8ResourceBundle; import net.sourceforge.fidocadj.globals.LibUtils; import net.sourceforge.fidocadj.circuit.HasChangedListener; import net.sourceforge.fidocadj.circuit.CircuitPanel; import net.sourceforge.fidocadj.circuit.controllers.CopyPasteActions; import net.sourceforge.fidocadj.circuit.controllers.AddElements; import net.sourceforge.fidocadj.circuit.controllers.ParserActions; import net.sourceforge.fidocadj.circuit.controllers.ElementsEdtActions; import net.sourceforge.fidocadj.toolbars.ToolbarZoom; import net.sourceforge.fidocadj.toolbars.ToolbarTools; import net.sourceforge.fidocadj.toolbars.ZoomToFitListener; import net.sourceforge.fidocadj.macropicker.MacroTree; import net.sourceforge.fidocadj.librarymodel.LibraryModel; import net.sourceforge.fidocadj.layermodel.LayerModel; import net.sourceforge.fidocadj.layers.StandardLayers; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.librarymodel.utils.CircuitPanelUpdater; import net.sourceforge.fidocadj.librarymodel.utils.LibraryUndoExecutor; /** FidoFrame.java The class describing the main frame in which FidoCadJ runs. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> The FidoFrame class describes a frame which is used to trace schematics and printed circuit boards. @author Davide Bucci */ public final class FidoFrame extends JFrame implements ActionListener, ZoomToFitListener, HasChangedListener, WindowFocusListener { // Interface elements parts of FidoFrame // The circuit panel... public CircuitPanel cc; // ... which is contained in a scroll pane. private JScrollPane sc; // ... which at its turn is in a split pane. private JSplitPane splitPane; // Macro picker component MacroTree macroLib; // Macro library model private LibraryModel libraryModel; // Objects which regroup a certain number of actions somewhat related // to the FidoFrame object in different domains. final private ExportTools et; final private PrintTools pt; final private MenuTools mt; //final private DragDropTools dt; final private FileTools ft; // Libraries properties public String libDirectory; public Preferences prefs; // Toolbar properties // The toolbar dedicated to the available tools (the first one under // thewindow title). private ToolbarTools toolBar; // The second toolbar dedicated to the zoom factors and other niceties // (the second one under the window title). ToolbarZoom toolZoom; // Text description under icons private boolean textToolbar; // Small (16x16 pixel) icons instead of standard (32x32 pixel) private boolean smallIconsToolbar; // Locale settings public Locale currentLocale; // Runs as an application or an applet. public boolean runsAsApplication; /** The standard constructor: create the frame elements and set up all variables. Note that the constructor itself is not sufficient for using the frame. You need to call the init procedure after you have set the configuration variables available for FidoFrame. @param appl should be true if FidoCadJ is run as a stand alone application or false if it is run as an applet. In this case, some local settings are not accessed because they would raise an exception. @param loc the locale which should be used. If it is null, the current locale is automatically determined and FidoCadJ will try to use it for its user interface. */ public FidoFrame (boolean appl, Locale loc) { super("FidoCadJ "+Globals.version); runsAsApplication = appl; currentLocale = registerLocale(loc); getRootPane().putClientProperty("Aqua.windowStyle", "combinedToolBar"); prepareLanguageResources(); Globals.configureInterfaceDetailsFromPlatform(InputEvent.META_MASK, InputEvent.CTRL_MASK); DialogUtil.center(this, .75,.75,800,500); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); // We need to keep track of the number of open windows. If the last // one is closed, we exit from the program. ++Globals.openWindowsNumber; Globals.openWindows.add(this); setIconForApplication(); if (runsAsApplication) { // Prepare the preferences associated to the FidoFrame class prefs = Preferences.userNodeForPackage(this.getClass()); } else { // If we can not access to the preferences, we inizialize those // configuration variables with default values. libDirectory = System.getProperty("user.home"); smallIconsToolbar = false; textToolbar = true; prefs=null; } et = new ExportTools(prefs); pt = new PrintTools(); mt = new MenuTools(); new DragDropTools(this); ft = new FileTools(this, prefs); readPreferences(); // In practice, we need to restore the size of the open current window // only for the first window. if (Globals.openWindowsNumber==1) { restorePosition(); } } /** By implementing writeObject method, // we can prevent // subclass from serialization */ private void writeObject(ObjectOutputStream out) throws IOException { throw new NotSerializableException(); } /* By implementing readObject method, // we can prevent // subclass from de-serialization */ private void readObject(ObjectInputStream in) throws IOException { throw new NotSerializableException(); } /** Store location & size of UI. vaguely based on: http://stackoverflow.com/questions/7777640/\ best-practice-for-setting-jframe-locations */ public void savePosition() { if (!runsAsApplication) { return; } int state=getExtendedState(); // restore the frame from 'full screen' first! setExtendedState(NORMAL); Rectangle r = getBounds(); int x = (int)r.getX(); int y = (int)r.getY(); int w = (int)r.getWidth(); int h = (int)r.getHeight(); prefs.put("FRAME_POSITION_X", "" + x); prefs.put("FRAME_POSITION_Y", "" + y); prefs.put("FRAME_WIDTH", "" + w); prefs.put("FRAME_HEIGHT", "" + h); prefs.put("FRAME_STATE", ""+state); } /** Restore location & size of UI */ public void restorePosition() { if (!runsAsApplication) { return; } try{ int x = Integer.parseInt(prefs.get("FRAME_POSITION_X","no")); int y = Integer.parseInt(prefs.get("FRAME_POSITION_Y","no")); int w = Integer.parseInt(prefs.get("FRAME_WIDTH","no")); int h = Integer.parseInt(prefs.get("FRAME_HEIGHT","no")); int state=Integer.parseInt(prefs.get("FRAME_STATE","no")); if((state & MAXIMIZED_HORIZ)!=0 || (state & MAXIMIZED_VERT)!=0) { setExtendedState(state); } else { Rectangle r = new Rectangle(x,y,w,h); setBounds(r); } } catch (NumberFormatException eE) { System.out.println("Choosing default values for frame size"); } } /** Obtain the language resources associated to the current locale. If the current locale is available, then load the appropriate LanguageResources file. If the current locale is not found, the en-US language resources file is employed, thus showing an interface in American English. */ private void prepareLanguageResources() { try { // Try to load the messages resources with the current locale Globals.messages = new AccessResources (Utf8ResourceBundle.getBundle("MessagesBundle", currentLocale)); } catch(MissingResourceException mre) { try { // If it does not work, try to use the standard English Globals.messages = new AccessResources (ResourceBundle.getBundle("MessagesBundle", new Locale("en", "US"))); System.out.println("No locale available, sorry... "+ "interface will be in English"); } catch(MissingResourceException mre1) { // Give up!!! JOptionPane.showMessageDialog(null, "Unable to find any language localization files: " + mre1); System.exit(1); } } } /** Retrieve the program icon and associate it to the window. */ private void setIconForApplication() { URL url=DialogAbout.class.getResource( "icona_fidocadj_128x128.png"); if (url == null) { System.err.println("Could not retrieve the FidoCadJ icon!"); } else { Image icon = Toolkit.getDefaultToolkit().getImage(url); setIconImage(icon); } } /** Check if a locale has been specified. If not, get the operating system's locale and employ this as the current locale. @param loc the desired locale, or null if the system one has to be employed. */ private Locale registerLocale(Locale loc) { String systemLanguage = Locale.getDefault().getLanguage(); Locale newLocale; if(loc==null) { // Make sort that only the language is used for the current newLocale = new Locale(systemLanguage); } else { newLocale = loc; if(!loc.getLanguage().equals(systemLanguage)) { System.out.println("Forcing the locale to be: " +loc+ " instead of: "+systemLanguage); } } return newLocale; } /** Get the locale employed by this instance. @return the current locale. */ @Override public Locale getLocale() { return currentLocale; } /** Get the ExportTools object (containing the code related to interface for exporting files). @return the ExportTools object. */ public ExportTools getExportTools() { return et; } /** Get the PrintTools object (containing the code related to interface for printing drawings). @return the PrintTools object. */ public PrintTools getPrintTools() { return pt; } /** Get the FileTools object (containing the code related to interface for loading and saving drawings). @return the FileTools object. */ public FileTools getFileTools() { return ft; } /** Read the preferences settings (mainly at startup or when a new editing window is created. If no preferences settings are accessible, does nothing. */ public void readPreferences() { if(prefs==null) { return; } // The library directory libDirectory = prefs.get("DIR_LIBS", ""); // The icon size String defaultSize=""; // Check the screen resolution. Now (April 2015), a lot of very high // resolution screens begin to be widespread. So, if the pixel // density is greater than 150 dpi, bigger icons are used by at the // very first time FidoCadJ is run. /*if(java.awt.Toolkit.getDefaultToolkit().getScreenResolution()>150) { defaultSize="false"; } else { defaultSize="true"; }*/ // 2020 I suspect the best result is now obtained with "false". defaultSize="false"; smallIconsToolbar = "true".equals(prefs.get("SMALL_ICON_TOOLBAR", defaultSize)); // Presence of the text description in the toolbar textToolbar = "true".equals(prefs.get("TEXT_TOOLBAR", "true")); // Read export preferences et.readPrefs(); // Read file preferences ft.readPrefs(); // Element sizes Globals.lineWidth=Double.parseDouble( prefs.get("STROKE_SIZE_STRAIGHT", "0.5")); Globals.lineWidthCircles=Double.parseDouble( prefs.get("STROKE_SIZE_OVAL", "0.35")); Globals.diameterConnection=Double.parseDouble( prefs.get("CONNECTION_SIZE", "2.0")); } /** Load the saved configuration for the grid. */ public void readGridSettings() { cc.getMapCoordinates().setXGridStep(Integer.parseInt( prefs.get("GRID_SIZE", "5"))); cc.getMapCoordinates().setYGridStep(Integer.parseInt( prefs.get("GRID_SIZE", "5"))); } /** Load the saved configuration for the drawing primitives and zoom. */ public void readDrawingSettings() { CopyPasteActions cpa = cc.getCopyPasteActions(); // Shift elements when copy/pasting them. cpa.setShiftCopyPaste("true".equals(prefs.get("SHIFT_CP","true"))); AddElements ae = cc.getContinuosMoveActions().getAddElements(); // Default PCB sizes (pad/line) ae.pcbPadSizeX = Integer.parseInt(prefs.get("PCB_pad_sizex", "10")); ae.pcbPadSizeY = Integer.parseInt(prefs.get("PCB_pad_sizey", "10")); ae.pcbPadStyle = Integer.parseInt(prefs.get("PCB_pad_style", "0")); ae.pcbPadDrill = Integer.parseInt(prefs.get("PCB_pad_drill", "5")); ae.pcbThickness = Integer.parseInt(prefs.get("PCB_thickness", "5")); MapCoordinates mc=cc.getMapCoordinates(); double z=Double.parseDouble(prefs.get("CURRENT_ZOOM","4.0")); mc.setMagnitudes(z,z); } /** Load the standard libraries according to the locale. */ public void loadLibraries() { // Check if we are using the english libraries. Basically, since the // only other language available other than english is italian, I // suppose that people are less uncomfortable with the current Internet // standard... boolean englishLibraries = !currentLocale.getLanguage().equals(new Locale("it", "", "").getLanguage()); // This is useful if this is not the first time that libraries are // being loaded. cc.dmp.resetLibrary(); ParserActions pa=cc.getParserActions(); if(runsAsApplication) { FidoMain.readLibrariesProbeDirectory(cc.dmp, englishLibraries, libDirectory); } else { // This code is useful when FidoCadJ is used whithout having access // to the user file system, for example because it is run as an // applet. In this case, the only accesses will be internal to // the jar file in order to respect security restrictions. if(englishLibraries) { // Read the english version of the libraries pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/IHRAM_en.FCL"), "ihram"); pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/FCDstdlib_en.fcl"), ""); pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/PCB_en.fcl"), "pcb"); pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/elettrotecnica_en.fcl"), "elettrotecnica"); pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/EY_Libraries.fcl"), "EY_Libraries"); } else { // Read the italian version of the libraries pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/IHRAM.FCL"), "ihram"); pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/FCDstdlib.fcl"), ""); pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/PCB.fcl"), "pcb"); pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/elettrotecnica.fcl"), "elettrotecnica"); pa.loadLibraryInJar(FidoFrame.class.getResource( "lib/EY_Libraries.fcl"), "EY_Libraries"); } } libraryModel.forceUpdate(); } /** Perform some initialization tasks: in particular, it reads the library directory and it creates the user interface. */ public void init() { Container contentPane=getContentPane(); cc=new CircuitPanel(true); cc.getParserActions().openFileName = ""; // Useful for automatic scrolling in panning mode. ScrollGestureRecognizer sgr; // If FidoCadJ runs as a standalone application, we must read the // content of the current library directory. // at the same time, we see if we should maintain a strict FidoCad // compatibility. if (runsAsApplication) { cc.dmp.setTextFont(prefs.get("MACRO_FONT", Globals.defaultTextFont), Integer.parseInt(prefs.get("MACRO_SIZE", "3")), cc.getUndoActions()); readGridSettings(); readDrawingSettings(); } cc.setStrictCompatibility(false); // Here we set the approximate size of the control at startup. This is // useful, since the scroll panel (created just below) use those // settings for specifying the behaviour of scroll bars. cc.setPreferredSize(new Dimension(1000,1000)); sc= new JScrollPane((Component)cc); cc.father=sc; sc.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); sc.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); if (runsAsApplication) { sgr = new ScrollGestureRecognizer(); cc.addScrollGestureSelectionListener(sgr); sgr.getInstance(); } sc.getVerticalScrollBar().setUnitIncrement(20); sc.getHorizontalScrollBar().setUnitIncrement(20); cc.profileTime=false; cc.antiAlias=true; // Create the layer vector. Basically, this is a rather standard // attribution in which only the first layers are attributed to // something that is circuit-related. // I followed the FidoCAD tradition on this. java.util.List<LayerDesc> layerDesc= StandardLayers.createStandardLayers(); cc.dmp.setLayers(layerDesc); toolBar = new ToolbarTools(textToolbar,smallIconsToolbar); toolZoom = new ToolbarZoom(layerDesc); toolBar.addSelectionListener(cc); toolZoom.addLayerListener(cc); toolZoom.addGridStateListener(cc); toolZoom.addZoomToFitListener(this); cc.addChangeZoomListener(toolZoom); cc.addChangeSelectionListener(toolBar); cc.getContinuosMoveActions().addChangeCoordinatesListener(toolZoom); toolZoom.addChangeZoomListener(cc); Box b=Box.createVerticalBox(); b.add(toolBar); b.add(toolZoom); toolZoom.setFloatable(false); toolZoom.setRollover(false); JMenuBar menuBar=mt.defineMenuBar(this); setJMenuBar(menuBar); // The initial state is the selection one. cc.setSelectionState(ElementsEdtActions.SELECTION, ""); contentPane.add(b,"North"); libraryModel = new LibraryModel(cc.dmp); LayerModel layerModel = new LayerModel(cc.dmp); macroLib = new MacroTree(libraryModel,layerModel); macroLib.setSelectionListener(cc); libraryModel.setUndoActorListener(cc.getUndoActions()); libraryModel.addLibraryListener(new CircuitPanelUpdater(this)); cc.getUndoActions().setLibraryUndoListener( new LibraryUndoExecutor(this,libraryModel)); try { LibUtils.saveLibraryState(cc.getUndoActions()); } catch (IOException e) { System.out.println("Exception: "+e); } splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); // Useful for Quaqua with MacOSX. //splitPane.putClientProperty("Quaqua.SplitPane.style","bar"); splitPane.putClientProperty("JSplitPane.style","thick"); Dimension windowSize = getSize(); cc.setPreferredSize(new Dimension(windowSize.width*85/100,100)); splitPane.setTopComponent(sc); macroLib.setPreferredSize(new Dimension(450,200)); splitPane.setBottomComponent(macroLib); splitPane.setResizeWeight(.8); contentPane.add(splitPane,"Center"); cc.getUndoActions().setHasChangedListener(this); cc.setFocusable(true); sc.setFocusable(true); /* Add a window listener to close the application when the frame is closed. This behavior is platform dependent, for example a Macintosh application can be made run without a visible frame. There would anyway the need to customize the menu bar, in order to allow the user to open a new FidoFrame, when it has been closed once. The easiest solution to implement is therefore to make the application close when the user closes the last frame. */ addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if(!ft.checkIfToBeSaved()) { return; } closeThisFrame(); } }); addWindowFocusListener(this); Globals.activeWindow=this; // This is WAY too invasive!!! cc.getUndoActions().setModified(false); if(runsAsApplication) { // Show the library tab or not. boolean s="true".equals(prefs.get("SHOW_LIBS","true")); showLibs(s); s="true".equals(prefs.get("SHOW_GRID","true")); cc.setGridVisibility(s); toolZoom.setShowGrid(s); s="true".equals(prefs.get("SNAP_GRID","true")); cc.setSnapState(s); toolZoom.setSnapGrid(s); } } /** Procedure to close the current frame, check if there are other open frames, and exit the program if there are no frames remaining. Ensure that the configuration settings are properly saved. */ public void closeThisFrame() { setVisible(false); cc.getUndoActions().doTheDishes(); savePosition(); // Save the zoom factor. There is no reason to save the other // coordinate mapping data as this will be used for an empty drawing. MapCoordinates mc=cc.getMapCoordinates(); prefs.put("CURRENT_ZOOM",""+mc.getXMagnitude()); if(areLibsVisible()) { prefs.put("SHOW_LIBS","true"); } else { prefs.put("SHOW_LIBS","false"); } if(cc.getGridVisibility()) { prefs.put("SHOW_GRID","true"); } else { prefs.put("SHOW_GRID","false"); } if(cc.getSnapState()) { prefs.put("SNAP_GRID","true"); } else { prefs.put("SNAP_GRID","false"); } dispose(); Globals.openWindows.remove(this); --Globals.openWindowsNumber; if (Globals.openWindowsNumber<1 && runsAsApplication) { System.exit(0); } } /** The action listener. Recognize menu events and behaves consequently. @param evt the event to be processed. */ @Override public void actionPerformed(ActionEvent evt) { // Recognize and handle menu events if(evt.getSource() instanceof JMenuItem) { mt.processMenuActions(evt, this, toolZoom); } } /** Create a new instance of the window. @return the created instance */ public FidoFrame createNewInstance() { FidoFrame popFrame=new FidoFrame(runsAsApplication, currentLocale); popFrame.setBounds(getX()+30, getY()+30, popFrame.getWidth(), popFrame.getHeight()); popFrame.init(); popFrame.loadLibraries(); popFrame.setExtendedState(getExtendedState()); popFrame.setVisible(true); return popFrame; } /** Show the FidoCadJ preferences panel */ public void showPrefs() { String oldDirectory = libDirectory; CopyPasteActions cpa = cc.getCopyPasteActions(); ElementsEdtActions eea = cc.getContinuosMoveActions(); AddElements ae =eea.getAddElements(); // At first, we create the preference panel. This kind of code is // probably not very easy to read and reutilize. This is probably // justified, since the preference panel is after all very specific // to the particular program to which it is referred, i.e. in this // case FidoCadJ... DialogOptions options=new DialogOptions(this, cc.getMapCoordinates().getXMagnitude(), cc.profileTime,cc.antiAlias, cc.getMapCoordinates().getXGridStep(), libDirectory, textToolbar, smallIconsToolbar, ae.getPcbThickness(), ae.getPcbPadSizeX(), ae.getPcbPadSizeY(), ae.getPcbPadDrill(), cc.getStrictCompatibility(), cc.dmp.getTextFont(), Globals.lineWidth, Globals.diameterConnection, cc.dmp.getTextFontSize(), cpa.getShiftCopyPaste()); // The panel is now made visible. Its properties will be updated only // if the user clicks on "Ok". options.setVisible(true); // Now, we can update the properties. cc.profileTime=options.profileTime; cc.antiAlias=options.antiAlias; textToolbar=options.textToolbar; smallIconsToolbar=options.smallIconsToolbar; cc.getMapCoordinates().setMagnitudes(options.zoomValue, options.zoomValue); cc.getMapCoordinates().setXGridStep(options.gridSize); cc.getMapCoordinates().setYGridStep(options.gridSize); ae.setPcbThickness(options.pcblinewidth_i); ae.setPcbPadSizeX(options.pcbpadwidth_i); ae.setPcbPadSizeY(options.pcbpadheight_i); ae.setPcbPadDrill(options.pcbpadintw_i); cc.dmp.setTextFont(options.macroFont, options.macroSize_i, cc.getUndoActions()); cc.setStrictCompatibility(options.extStrict); toolBar.setStrictCompatibility(options.extStrict); cpa.setShiftCopyPaste(options.shiftCP); libDirectory=options.libDirectory; Globals.lineWidth = options.stroke_size_straight_i; Globals.lineWidthCircles = options.stroke_size_straight_i; Globals.diameterConnection = options.connectionSize_i; // We know that this code will be useful only when FidoCadJ will run as // a standalone application. If it is used as an applet, this would // cause the application crash when the applet security model is active. // In this way, we can still use FidoCadJ as an applet, even with the // very restrictive security model applied by default to applets. if (runsAsApplication) { prefs.put("DIR_LIBS", libDirectory); prefs.put("MACRO_FONT", cc.dmp.getTextFont()); prefs.put("MACRO_SIZE", ""+cc.dmp.getTextFontSize()); prefs.put("STROKE_SIZE_STRAIGHT", ""+Globals.lineWidth); prefs.put("STROKE_SIZE_OVAL", ""+Globals.lineWidthCircles); prefs.put("CONNECTION_SIZE", ""+Globals.diameterConnection); prefs.put("SMALL_ICON_TOOLBAR", smallIconsToolbar?"true":"false"); prefs.put("TEXT_TOOLBAR", textToolbar?"true":"false"); prefs.put("GRID_SIZE", ""+cc.getMapCoordinates().getXGridStep()); // Save default PCB characteristics prefs.put("pcbPadSizeX", ""+ae.pcbPadSizeX); prefs.put("pcbPadSizeY", ""+ae.pcbPadSizeY); prefs.put("pcbPadStyle", ""+ae.pcbPadStyle); prefs.put("pcbPadDrill", ""+ae.pcbPadDrill); prefs.put("pcbThickness", ""+ae.pcbThickness); prefs.put("SHIFT_CP", cpa.getShiftCopyPaste()?"true":"false"); } if(!libDirectory.equals(oldDirectory)) { loadLibraries(); show(); } repaint(); } /** Set the current zoom to fit */ public void zoomToFit() { //double oldz=cc.getMapCoordinates().getXMagnitude(); // We calculate the zoom to fit factor here. MapCoordinates m=DrawingSize.calculateZoomToFit(cc.dmp, sc.getViewport().getExtentSize().width-35, sc.getViewport().getExtentSize().height-35, true); double z=m.getXMagnitude(); // We apply the zoom factor to the coordinate transform cc.getMapCoordinates().setMagnitudes(z, z); // We make the scroll pane show the interesting part of // the drawing. Rectangle r= new Rectangle((int)m.getXCenter(), (int)m.getYCenter(), sc.getViewport().getExtentSize().width, sc.getViewport().getExtentSize().height); cc.updateSizeOfScrollBars(r); } /** We notify the user that something has changed by putting an asterisk in the file name. We also show here in the titlebar the (eventually shortened) file name of the drawing being modified or shown. */ public void somethingHasChanged() { if (Globals.weAreOnAMac) { // Apparently, this does not work as expected in MacOSX 10.4 Tiger. // Those are MacOSX >= 10.5 Leopard features. // We thus leave also the classic Window-based asterisk when // the file has been modified. getRootPane().putClientProperty("Window.documentModified", Boolean.valueOf(cc.getUndoActions().getModified())); toolBar.setTitle( Globals.prettifyPath(cc.getParserActions().openFileName,45)); } else { setTitle("FidoCadJ "+Globals.version+" "+ Globals.prettifyPath(cc.getParserActions().openFileName,45)+ (cc.getUndoActions().getModified()?" *":"")); } } /** The current window has gained focus. @param e the window event. */ @Override public void windowGainedFocus(WindowEvent e) { Globals.activeWindow = this; // This should fix #182 cc.requestFocusInWindow(); } /** The current window has lost focus. @param e the window event. */ @Override public void windowLostFocus(WindowEvent e) { // Nothing to do } /** Control the presence of the libraries and the preview on the right of the frame. @param s true if the libs have to be shown. */ public void showLibs(boolean s) { splitPane.setBottomComponent(s?macroLib:null); toolZoom.setShowLibsState(areLibsVisible()); mt.setShowLibsState(areLibsVisible()); if(s) { splitPane.setDividerLocation(0.75); } splitPane.revalidate(); } /** Determine if the libraries are visible or not. @return true if the libs are visible. */ public boolean areLibsVisible() { return splitPane.getBottomComponent()!=null; } }
33,373
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/layermodel/package-info.java
/** Package for providing a model (database) for layers. Classes in the "layers" package will be moved here. */ package net.sourceforge.fidocadj.layermodel;
161
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
LayerModel.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/layermodel/LayerModel.java
// This file is part of FidoCadJ. // // FidoCadJ is 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, either version 3 of the License, or // (at your option) any later version. // // FidoCadJ 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 FidoCadJ. If not, // @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. // // Copyright 2014-2023 Kohta Ozaki package net.sourceforge.fidocadj.layermodel; import java.util.*; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.layers.LayerDesc; /** * Model for providing layers.<BR> * @author Kohta Ozaki */ public class LayerModel { private final DrawingModel drawingModel; /** Standard constructor. @param dm the drawing model to be used. */ public LayerModel(DrawingModel dm) { this.drawingModel = dm; } /** Get the layer description from the drawing model. @return the array of layers. */ public List<LayerDesc> getAllLayers() { return drawingModel.getLayers(); } }
1,435
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/package-info.java
/** Export filters for FidoCadJ drawings. They are implementations of the ExportGraphic interface. The class ExportGraphic contains some general use methods related to the export, but not only (such as calculating image size and so on). */ package net.sourceforge.fidocadj.export;
297
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExportSVG.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/ExportSVG.java
package net.sourceforge.fidocadj.export; import java.util.*; import java.io.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.Arrow; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.graphic.ColorInterface; import net.sourceforge.fidocadj.graphic.DecoratedText; import net.sourceforge.fidocadj.graphic.PointDouble; import net.sourceforge.fidocadj.graphic.TextInterface; /** Export drawing in the Scalable Vector Graphics format. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class ExportSVG implements ExportInterface, TextInterface { //private File fileExp; final private OutputStreamWriter fstream; private BufferedWriter out; private List layerV; private ColorInterface c; // Current colour (used in advText export) private double strokeWidth; private String sDash[]; private float dashPhase; private float currentPhase=-1; private float currentFontSize=0; private DecoratedText dt; private String fontname; // Some info about the font is stored private float textx; // This is used in sub-sup scripts position private float texty; private boolean isItalic; private boolean isBold; // A graphic interface object is used here to get information about the // size of the different glyphs in the font. private final GraphicsInterface gi; /* static final String dash[]={"2.5,5", "1.25,1.25", "0.5,0.5", "0.5,1.25", "0.5,1.25,1.25,1.25"};*/ /** Set the multiplication factor to be used for the dashing. @param u the factor. */ public void setDashUnit(double u) { sDash = new String[Globals.dashNumber]; // If the line width has been changed, we need to update the // stroke table // The first entry is non dashed sDash[0]=""; // Resize the dash sizes depending on the current zoom size. String dashArrayStretched; // Then, the dashed stroke styles are created. for(int i=1; i<Globals.dashNumber; ++i) { // Prepare the resized dash array. dashArrayStretched = ""; for(int j=0; j<Globals.dash[i].length;++j) { dashArrayStretched+=(Globals.dash[i][j]*(float)u/2.0f); if(j<Globals.dash[i].length-1) { dashArrayStretched+=","; } } sDash[i]=dashArrayStretched; } } /** Set the "phase" in output units of the dashing style. For example, if a dash style is composed by a line followed by a space of equal size, a phase of 0 indicates that the dash starts with the line. @param p the phase, in output units. */ public void setDashPhase(float p) { dashPhase=p; } private double cLe(double l) { //return (int)(l*sizeMagnification); return Math.round(l*100.0)/100.0; } /** Constructor. @param f the File object in which the export should be done. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public ExportSVG (File f, GraphicsInterface g) throws IOException { gi=g; fstream = new OutputStreamWriter(new FileOutputStream(f), Globals.encoding); dt = new DecoratedText(this); } /** Called at the beginning of the export phase. Ideally, in this routine there should be the code to write the header of the file on which the drawing should be exported. @param totalSize the size of the image. Useful to calculate for example the bounding box. @param la a vector describing the attributes of each layer. @param grid the grid size. This is useful when exporting to another drawing program having some kind of grid concept. You might use this value to synchronize FidoCadJ's grid with the one used by the target. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportStart(DimensionG totalSize, List<LayerDesc> la, int grid) throws IOException { // We need to save layers informations, since we will use them later. layerV=la; out = new BufferedWriter(fstream); //numberPath=0; int wi=(int)totalSize.width; int he=(int)totalSize.height; // A dumb, basic header of the SVG file // Globals.encoding out.write("<?xml version=\"1.0\" encoding=\""+"UTF-8"+"\" " + "standalone=\"no\"?> \n<!DOCTYPE svg PUBLIC"+ " \"-//W3C//Dtd SVG 1.1//EN\" " + "\"http://www.w3.org/Graphics/SVG/1.1/Dtd/svg11.dtd\">\n"+ "<svg width=\""+cLe(wi)+"\" height=\""+cLe(he)+ "\" version=\"1.1\" " + "xmlns=\"http://www.w3.org/2000/svg\" " + "xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n"+ "<!-- Created by FidoCadJ ver. "+Globals.version+ ", export filter by Davide Bucci -->\n"); } /** Called at the end of the export phase. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportEnd() throws IOException { out.write("</svg>"); out.close(); } /** Called when exporting an Advanced Text primitive. @param x the x position of the beginning of the string to be written. @param y the y position of the beginning of the string to be written. @param sizex the x size of the font to be used. @param sizey the y size of the font to be used. @param fontname the font to be used. @param isBold true if the text should be written with a boldface font. @param isMirrored true if the text should be mirrored. @param isItalic true if the text should be written with an italic font. @param orientation angle of orientation (degrees). @param layer the layer that should be used. @param text the text that should be written. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportAdvText (int x, int y, int sizex, int sizey, String fontname, boolean isBold, boolean isMirrored, boolean isItalic, int orientation, int layer, String text) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); c=l.getColor(); this.isItalic=isItalic; this.isBold=isBold; this.fontname=fontname; /* THIS VERSION OF TEXT EXPORT IS NOT COMPLETE! IN PARTICULAR, MIRRORING EFFECTS, ANGLES AND A PRECISE SIZE CONTROL IS NOT HANDLED */ out.write("<g transform=\"translate("+cLe(x)+","+cLe(y)+")"); double xscale = sizex/22.0/sizey*38.0; setFontSize(sizey); if(orientation !=0) { double alpha= isMirrored?orientation:-orientation; out.write(" rotate("+alpha+") "); } if(isMirrored) { xscale=-xscale; } out.write(" scale("+xscale+",1) "); out.write("\">"); textx=x; texty=y; dt.drawString(text,x,y); out.write("</g>\n"); } /** Called when exporting a Bézier primitive. @param x1 the x position of the first point of the trace. @param y1 the y position of the first point of the trace. @param x2 the x position of the second point of the trace. @param y2 the y position of the second point of the trace. @param x3 the x position of the third point of the trace. @param y3 the y position of the third point of the trace. @param x4 the x position of the fourth point of the trace. @param y4 the y position of the fourth point of the trace. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param sW the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportBezier (int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double sW) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); c=l.getColor(); strokeWidth=sW; if (arrowStart) { PointPr p=exportArrow(x1, y1, x2, y2, arrowLength, arrowHalfWidth, arrowStyle); // This fixes issue #172 // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if(arrowLength>0) { x1=(int)Math.round(p.x); y1=(int)Math.round(p.y); } } if (arrowEnd) { PointPr p=exportArrow(x4, y4, x3, y3, arrowLength, arrowHalfWidth, arrowStyle); // Fix #172 if(arrowLength>0) { x4=(int)Math.round(p.x); y4=(int)Math.round(p.y); } } out.write("<path d=\"M "+cLe(x1)+","+cLe(y1)+" C "+ cLe(x2)+ ","+cLe(y2)+" "+cLe(x3)+","+cLe(y3)+" "+cLe(x4)+ ","+cLe(y4)+"\" "); checkColorAndWidth("fill=\"none\"", dashStyle); } /** Called when exporting a Connection primitive. @param x the x position of the position of the connection. @param y the y position of the position of the connection. @param layer the layer that should be used. @param nodeSize the size of the connection in logical units. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportConnection (int x, int y, int layer, double nodeSize) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); c=l.getColor(); strokeWidth = cLe(0.33); out.write("<circle cx=\""+cLe(x)+"\" cy=\""+cLe(y)+"\""+ " r=\""+cLe(nodeSize/2.0)+"\" style=\"stroke:#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+";stroke-width:"+strokeWidth+ "\" fill=\"#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+"\"/>\n"); } /** Called when exporting a Line primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param sW the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportLine (double x1, double y1, double x2, double y2, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double sW) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); c=l.getColor(); strokeWidth=sW; double xstart=x1; double ystart=y1; double xend=x2; double yend=y2; if (arrowStart) { PointPr p=exportArrow(x1, y1, x2, y2, arrowLength, arrowHalfWidth, arrowStyle); // This fixes issue #172 // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if(arrowLength>0) { xstart=p.x; ystart=p.y; } } if (arrowEnd) { PointPr p=exportArrow(x2, y2, x1, y1, arrowLength, arrowHalfWidth, arrowStyle); // Fix #172 if(arrowLength>0) { xend=p.x; yend=p.y; } } out.write("<line x1=\""+cLe(xstart)+"\" y1=\""+cLe(ystart)+"\" x2=\""+ cLe(xend)+"\" y2=\""+cLe(yend)+"\" "); checkColorAndWidth("fill=\"none\"", dashStyle); } /** Called when exporting a Macro call. This function can just return false, to indicate that the macro should be rendered by means of calling the other primitives. Please note that a macro does not have a reference layer, since it is defined by its components. @param x the x position of the position of the macro. @param y the y position of the position of the macro. @param isMirrored true if the macro is mirrored. @param orientation the macro orientation in degrees. @param macroName the macro name. @param macroDesc the macro description, in the FidoCad format. @param name the shown name. @param xn coordinate of the shown name. @param yn coordinate of the shown name. @param value the shown value. @param xv coordinate of the shown value. @param yv coordinate of the shown value. @param font the used font. @param fontSize the size of the font to be used. @param m the library. @return true if the export is handled by this function, false if the macro has to be expanded into primitives. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public boolean exportMacro(int x, int y, boolean isMirrored, int orientation, String macroName, String macroDesc, String name, int xn, int yn, String value, int xv, int yv, String font, int fontSize, Map m) throws IOException { // The macro will be expanded into primitives. return false; } /** Called when exporting an Oval primitive. Specify the bounding box. @param x1 the x position of the first corner. @param y1 the y position of the first corner. @param x2 the x position of the second corner. @param y2 the y position of the second corner. @param isFilled it is true if the oval should be filled. @param layer the layer that should be used. @param dashStyle dashing style. @param sW the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportOval(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double sW) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); c=l.getColor(); String fillPattern=""; strokeWidth=sW; if(isFilled) { fillPattern="fill=\"#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+"\""; } else { fillPattern="fill=\"none\""; } out.write("<ellipse cx=\""+cLe((x1+x2)/2.0)+"\" cy=\""+ cLe((y1+y2)/2.0)+ "\" rx=\""+cLe(Math.abs(x2-x1)/2.0)+"\" ry=\""+ cLe(Math.abs(y2-y1)/2.0)+"\" "); checkColorAndWidth(fillPattern, dashStyle); } /** Called when exporting a PCBLine primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param width the width ot the line. @param layer the layer that should be used. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPCBLine(int x1, int y1, int x2, int y2, int width, int layer) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); c=l.getColor(); out.write("<line x1=\""+cLe(x1)+"\" y1=\""+cLe(y1)+"\" x2=\""+ cLe(x2)+"\" y2=\""+cLe(y2)+"\" style=\"stroke:#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+ ";stroke-linejoin:round;stroke-linecap:round"+ ";stroke-width:"+width+ "\"/>\n"); } /** Called when exporting a PCBPad primitive. @param x the x position of the pad.s @param y the y position of the pad. @param style the style of the pad (0: oval, 1: square, 2: rounded square). @param six the x size of the pad. @param siy the y size of the pad. @param indiam the hole internal diameter. @param layer the layer that should be used. @param onlyHole true if only the hole has to be exported. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPCBPad(int x, int y, int style, int six, int siy, int indiam, int layer, boolean onlyHole) throws IOException { double xdd; double ydd; strokeWidth=0.33; LayerDesc l=(LayerDesc)layerV.get(layer); c=l.getColor(); if(onlyHole) { // ... then, drill the hole! out.write("<circle cx=\""+cLe(x)+"\" cy=\""+cLe(y)+"\""+ " r=\""+cLe(indiam/2.0)+ "\" style=\"stroke:white;stroke-width:"+strokeWidth+ "\" fill=\"white\"/>\n"); } else { // At first, draw the pad... switch (style) { case 1: // Square pad xdd=cLe((double)x-six/2.0); ydd=cLe((double)y-siy/2.0); out.write("<rect x=\""+xdd+"\" y=\""+ ydd+ "\" rx=\"0\" ry=\"0\" "+ "width=\""+cLe(six)+"\" height=\""+ cLe(siy)+"\" style=\"stroke:#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+ ";stroke-width:"+strokeWidth+"\" fill=\"#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+"\"/>\n"); break; case 2: // Rounded pad xdd=cLe((double)x-six/2.0); ydd=cLe((double)y-siy/2.0); double rd = cLe(2.5); out.write("<rect x=\""+xdd+"\" y=\""+ydd+ "\" rx=\""+rd+"\" ry=\""+rd+"\" "+ "width=\""+cLe(six)+"\" height=\""+ cLe(siy)+"\" style=\"stroke:#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+ ";stroke-width:"+strokeWidth+"\" fill=\"#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+"\"/>\n"); break; case 0: // Oval pad default: out.write("<ellipse cx=\""+cLe(x)+"\" cy=\""+cLe(y)+"\""+ " rx=\""+cLe(six/2.0)+"\" ry=\""+cLe(siy/2.0)+ "\" style=\"stroke:#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+";stroke-width:"+ cLe(strokeWidth)+ "\" fill=\"#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+"\"/>\n"); break; } } } /** Called when exporting a Polygon primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param layer the layer that should be used. @param dashStyle dashing style. @param sW the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPolygon(PointDouble[] vertices, int nVertices, boolean isFilled, int layer, int dashStyle, double sW) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); c=l.getColor(); String fillPattern=""; strokeWidth=sW; if(isFilled) { fillPattern="fill=\"#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+"\""; } else { fillPattern="fill=\"none\""; } int i; //LayerDesc l=(LayerDesc)layerV.get(layer); out.write("<polygon points=\""); for (i=0; i<nVertices; ++i) { out.write(""+cLe(vertices[i].x)+","+cLe(vertices[i].y)+" "); } out.write("\" "); checkColorAndWidth(fillPattern, dashStyle); } /** Called when exporting a Curve primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param isClosed true if the curve is closed. @param layer the layer that should be used. @param arrowStart true if an arrow should be drawn at the start point. @param arrowEnd true if an arrow should be drawn at the end point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param sW the width of the pen to be used when drawing. @return false if the curve should be rendered using a polygon, true if it is handled by the function. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public boolean exportCurve(PointDouble[] vertices, int nVertices, boolean isFilled, boolean isClosed, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double sW) throws IOException { return false; } /** Called when exporting a Rectangle primitive. @param x1 the x position of the first corner. @param y1 the y position of the first corner. @param x2 the x position of the second corner. @param y2 the y position of the second corner. @param isFilled it is true if the rectangle should be filled. @param layer the layer that should be used. @param dashStyle dashing style. @param sW the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportRectangle(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double sW) throws IOException { strokeWidth=sW; LayerDesc l=(LayerDesc)layerV.get(layer); c=l.getColor(); String fillPattern=""; if(isFilled) { fillPattern="fill=\"#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+"\""; } else { fillPattern="fill=\"none\""; } out.write("<rect x=\""+cLe(Math.min(x1,x2))+"\" y=\""+ cLe(Math.min(y1,y2))+ "\" rx=\"0\" ry=\"0\" "+ "width=\""+cLe(Math.abs(x2-x1))+"\" height=\""+ cLe(Math.abs(y2-y1))+"\" "); checkColorAndWidth(fillPattern, dashStyle); } /** Just be sure that the HEX values are given with two digits... NOT a speed sensitive context. */ private String convertToHex2(int v) { String s=Integer.toHexString(v); if (s.length()==1) { s="0"+s; } return s; } //private Color oc; //private double owl; //private String ofp; //private int ods; /** This routine ensures that the following items will be drawn with the correct stroke pattern and color. TODO: it is not currently working. Improve this. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ private void checkColorAndWidth(String fillPattern, int dashStyle) throws IOException { // Write only if necessary, to save space. // It does not work... //if(oc!=c || owl!=wl || !fillPattern.equals(ofp) || ods!=dashStyle) { //if(true) { { out.write("style=\"stroke:#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())); if (dashStyle>0) { out.write(";stroke-dasharray: "+sDash[dashStyle]); } if (currentPhase!=dashPhase) { currentPhase=dashPhase; out.write(";stroke-dashoffset: "+dashPhase); } out.write(";stroke-width:"+strokeWidth+ ";fill-rule: evenodd;\" " + fillPattern + "/>\n"); } } /** Called when exporting an arrow. @param x position of the tip of the arrow. @param y position of the tip of the arrow. @param xc direction of the tip of the arrow. @param yc direction of the tip of the arrow. @param l length of the arrow. @param h width of the arrow. @param style style of the arrow. @return the coordinates of the base of the arrow. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public PointPr exportArrow(double x, double y, double xc, double yc, double l, double h, int style) throws IOException { double alpha; double x0; double y0; double x1; double y1; double x2; double y2; // At first we need the angle giving the direction of the arrow // a little bit of trigonometry :-) if (x==xc) { alpha = Math.PI/2.0+(y-yc<0.0?0.0:Math.PI); } else { alpha = Math.atan((double)(y-yc)/(double)(x-xc)); } alpha += x-xc>0.0?0.0:Math.PI; String fillPattern; // Then, we calculate the points for the polygon x0 = x - l*Math.cos(alpha); y0 = y - l*Math.sin(alpha); x1 = x0 - h*Math.sin(alpha); y1 = y0 + h*Math.cos(alpha); x2 = x0 + h*Math.sin(alpha); y2 = y0 - h*Math.cos(alpha); out.write("<polygon points=\""); out.write(""+Globals.roundTo(x)+"," +Globals.roundTo(y)+" "); out.write(""+Globals.roundTo(x1)+"," +Globals.roundTo(y1)+" "); out.write(""+Globals.roundTo(x2)+"," +Globals.roundTo(y2)+"\" "); if ((style & Arrow.flagEmpty) == 0) { fillPattern="fill=\"#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+"\""; } else { fillPattern="fill=\"none\""; } checkColorAndWidth(fillPattern,0); if ((style & Arrow.flagLimiter) != 0) { double x3; double y3; double x4; double y4; x3 = x - h*Math.sin(alpha); y3 = y + h*Math.cos(alpha); x4 = x + h*Math.sin(alpha); y4 = y - h*Math.cos(alpha); out.write("<line x1=\""+cLe(x3)+"\" y1=\""+cLe(y3)+"\" x2=\""+ cLe(x4)+"\" y2=\""+cLe(y4)+"\" "); checkColorAndWidth("fill=\"none\"", 0); } return new PointPr(x0,y0); } // Functions required for the TextInterface. /** Get the font size. @return the font size. */ public double getFontSize() { return currentFontSize; } /** Set the font size. @param size the font size. */ public void setFontSize(double size) { currentFontSize=(float)size; } /** Get the width of the given string with the current font. @param s the string to be used. @return the width of the string, in pixels. */ public int getStringWidth(String s) { gi.setFont(fontname,currentFontSize); return gi.getStringWidth(s); } /** Draw a string on the current graphic context. @param str the string to be drawn. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. */ public void drawString(String str, int x, int y) { try{ out.write("<text x=\""+(x-textx)+"\" y=\"" +cLe(currentFontSize+y-texty) +"\" font-family=\""+ fontname+"\" font-size=\""+cLe(currentFontSize)+ "\" font-style=\""+ (isItalic?"italic":"")+"\" font-weigth=\""+ (isBold?"bold":"")+"\" "+ "fill=\"#"+ convertToHex2(c.getRed())+ convertToHex2(c.getGreen())+ convertToHex2(c.getBlue())+"\""+ ">"); // Substitute potentially dangerous characters (issue #162) String outtxt=str.replace("&", "&amp;"); outtxt=outtxt.replace("<", "&lt;"); outtxt=outtxt.replace(">", "&gt;"); outtxt=outtxt.replace("\"", "&quot;"); outtxt=outtxt.replace("'", "&apos;"); out.write(outtxt); out.write("</text>\n"); } catch(IOException e) { System.err.println("Can not write to file in SVG export."); } } }
32,561
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExportPGF.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/ExportPGF.java
package net.sourceforge.fidocadj.export; import java.util.*; import java.io.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.Arrow; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.ColorInterface; import net.sourceforge.fidocadj.graphic.PointDouble; /** Export in a LaTeX drawing using the pgf (Portable Graphic File) packet. The file should be compatible with at least the 0.65 version of the pgf packet. Here is an example of a file inclusion, in LaTeX:<br> ------------------------------------------------- <pre> \\documentclass[10pt,a4paper]{scrreprt} \\usepackage[italian]{babel} \\usepackage{pgf} \\begin{document} \\input{prova.pgf} \\end{document} </pre> -------------------------------------------------<br> since the prova.pgf file (generated by FidoCadJ) already contains the \begin{pgfpicture} and \end{pgfpicture} commands in order to work in the correct environment. The text is not formatted, since the user should be able to use LaTeX commands inside FidoCadJ to be parsed when the exported pgf file is included and compiled with LaTeX or pdfLaTeX. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class ExportPGF implements ExportInterface { private final FileWriter fstream; private BufferedWriter out; private List layerV; private ColorInterface actualColor; private int currentDash; private double actualWidth; private float dashPhase; private float currentPhase=-1; // Dash patterns private String sDash[]; /* static final String dash[]={"{5.0pt}{10pt}", "{2.5pt}{2.5pt}", "{1.0pt}{1.0pt}", "{1.0pt}{2.5pt}", "{1.0pt}{2.5pt}{2.5pt}{2.5pt}"}; */ /** Set the multiplication factor to be used for the dashing. @param u the factor. */ public void setDashUnit(double u) { sDash = new String[Globals.dashNumber]; // If the line width has been changed, we need to update the // stroke table // The first entry is non dashed sDash[0]=""; // Resize the dash sizes depending on the current zoom size. String dashArrayStretched; // Then, the dashed stroke styles are created. for(int i=1; i<Globals.dashNumber; ++i) { // Prepare the resized dash array. dashArrayStretched = ""; for(int j=0; j<Globals.dash[i].length;++j) { dashArrayStretched+=(Globals.dash[i][j]*(float)u/2.0f); if(j<Globals.dash[i].length-1) { dashArrayStretched+="pt}{"; } } sDash[i]="{"+dashArrayStretched+"pt}"; } } /** Set the "phase" in output units of the dashing style. For example, if a dash style is composed by a line followed by a space of equal size, a phase of 0 indicates that the dash starts with the line. @param p the phase, in output units. */ public void setDashPhase(float p) { dashPhase=p; } /** Constructor @param f the File object in which the export should be done. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public ExportPGF (File f) throws IOException { actualColor=null; fstream = new FileWriter(f); } /** Called at the beginning of the export phase. Ideally, in this routine there should be the code to write the header of the file on which the drawing should be exported. @param totalSize the size of the image. Useful to calculate for example the bounding box. @param la a vector describing the attributes of each layer. @param grid the grid size. This is useful when exporting to another drawing program having some kind of grid concept. You might use this value to synchronize FidoCadJ's grid with the one used by the target. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportStart(DimensionG totalSize, List<LayerDesc> la, int grid) throws IOException { // We need to save layers informations, since we will use them later. layerV=la; int i; out = new BufferedWriter(fstream); LayerDesc l; ColorInterface c; int wi=totalSize.width; int he=totalSize.height; // A basic header of the PGF file out.write("\\begin{pgfpicture}{0cm}{0cm}{"+wi+ "pt}{"+he+"pt}\n" +"% Created by FidoCadJ ver. "+Globals.version +", export filter by Davide Bucci\n"); out.write("\\pgfsetxvec{\\pgfpoint{"+1+"pt}{0pt}}\n"); out.write("\\pgfsetyvec{\\pgfpoint{0pt}{"+1+"pt}}\n"); out.write("\\pgfsetroundjoin \n\\pgfsetroundcap\n"); out.write("\\pgftranslateto{\\pgfxy(0,"+he+")}\n"); out.write("\\begin{pgfmagnify}{1}{-1}\n"); out.write("% Layer color definitions\n"); for(i=0; i<layerV.size();++i) { l=(LayerDesc)layerV.get(i); c=l.getColor(); out.write("\\definecolor{layer"+i+"}{rgb}{"+ +Math.round(100.0*c.getRed()/255.0)/100.0+"," +Math.round(100.0*c.getGreen()/255.0)/100.0+ "," +Math.round(100.0*c.getBlue()/255.0)/100.0 +"}\n"); } out.write("% End of color definitions\n"); actualColor=null; } /** Called at the end of the export phase. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportEnd() throws IOException { out.write("\\end{pgfmagnify}\n"); out.write("\\end{pgfpicture}"); out.close(); } /** Called when exporting an Advanced Text primitive. @param x the x position of the beginning of the string to be written. @param y the y position of the beginning of the string to be written. @param sizex the x size of the font to be used. @param sizey the y size of the font to be used. @param fontname the font to be used. @param isBold true if the text should be written with a boldface font. @param isMirrored true if the text should be mirrored. @param isItalic true if the text should be written with an italic font. @param orientation angle of orientation (degrees). @param layer the layer that should be used. @param text the text that should be written. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportAdvText (int x, int y, int sizex, int sizey, String fontname, boolean isBold, boolean isMirrored, boolean isItalic, int orientation, int layer, String text) throws IOException { registerColorSize(layer, -1.0); /* THIS VERSION OF TEXT EXPORT IS NOT COMPLETE! IN PARTICULAR, MIRRORING EFFECTS, ANGLES AND A PRECISE SIZE CONTROL IS NOT HANDLED at ALL! This is somehow wanted, since the main use of the PGF export is for inserting LaTeX commands inside drawings meant for use in a LaTeX documents. So this is something LaTeX should do, and it is not a businnes for FidoCadJ. */ out.write("\\begin{pgfmagnify}{1}{-1}\n"); out.write("\\pgfputat{\\pgfxy("+x+","+(-y)+")}{\\pgfbox[left,top]{"); out.write(text); out.write("}}\n"); out.write("\\end{pgfmagnify}\n"); } /** Called when exporting a Bézier primitive. @param x1 the x position of the first point of the trace. @param y1 the y position of the first point of the trace. @param x2 the x position of the second point of the trace. @param y2 the y position of the second point of the trace. @param x3 the x position of the third point of the trace. @param y3 the y position of the third point of the trace. @param x4 the x position of the fourth point of the trace. @param y4 the y position of the fourth point of the trace. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportBezier (int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { registerColorSize(layer, strokeWidth); registerDash(dashStyle); if (arrowStart) { PointPr p=exportArrow(x1, y1, x2, y2, arrowLength, arrowHalfWidth, arrowStyle); // This fixes issue #172 // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if(arrowLength>0) { x1=(int)Math.round(p.x); y1=(int)Math.round(p.y); } } if (arrowEnd) { PointPr p=exportArrow(x4, y4, x3, y3, arrowLength, arrowHalfWidth, arrowStyle); // Fix #172 if(arrowLength>0) { x4=(int)Math.round(p.x); y4=(int)Math.round(p.y); } } out.write("\\pgfmoveto{\\pgfxy("+x1+","+y1+")} \n"+ "\\pgfcurveto{\\pgfxy("+x2+","+y2+")}{\\pgfxy("+x3+","+y3+ ")}{\\pgfxy("+x4+","+y4+")}\n"+ "\\pgfstroke\n"); } /** Called when exporting a Connection primitive. @param x the x position of the position of the connection. @param y the y position of the position of the connection. @param layer the layer that should be used. @param nodeSize the sieze of the connection in logical units. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportConnection (int x, int y, int layer, double nodeSize) throws IOException { registerColorSize(layer, .33); out.write("\\pgfcircle[fill]{\\pgfxy("+x+","+y+")}{"+ nodeSize/2.0+"pt}"); } /** Called when exporting a Line primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportLine (double x1, double y1, double x2, double y2, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { registerColorSize(layer, strokeWidth); registerDash(dashStyle); double xstart=x1; double ystart=y1; double xend=x2; double yend=y2; if (arrowStart) { PointPr p=exportArrow(x1, y1, x2, y2, arrowLength, arrowHalfWidth, arrowStyle); // This fixes issue #172 // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if(arrowLength>0) { xstart=p.x; ystart=p.y; } } if (arrowEnd) { PointPr p=exportArrow(x2, y2, x1, y1, arrowLength, arrowHalfWidth, arrowStyle); // Fix #172 if(arrowLength>0) { xend=p.x; yend=p.y; } } out.write("\\pgfline{\\pgfxy("+xstart+","+ystart+")}{\\pgfxy("+ xend+","+yend+")}\n"); } /** Called when exporting an arrow. @param x position of the tip of the arrow. @param y position of the tip of the arrow. @param xc direction of the tip of the arrow. @param yc direction of the tip of the arrow. @param l length of the arrow. @param h width of the arrow. @param style style of the arrow. @return the coordinates of the base of the arrow. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public PointPr exportArrow(double x, double y, double xc, double yc, double l, double h, int style) throws IOException { double alpha; double x0; double y0; double x1; double y1; double x2; double y2; // At first we need the angle giving the direction of the arrow // a little bit of trigonometry :-) if (x==xc) { alpha = Math.PI/2.0+(y-yc<0?0:Math.PI); } else { alpha = Math.atan((double)(y-yc)/(double)(x-xc)); } alpha += x-xc>0?0:Math.PI; // Then, we calculate the points for the polygon x0 = x - l*Math.cos(alpha); y0 = y - l*Math.sin(alpha); x1 = x0 - h*Math.sin(alpha); y1 = y0 + h*Math.cos(alpha); x2 = x0 + h*Math.sin(alpha); y2 = y0 - h*Math.cos(alpha); out.write("\\pgfmoveto{\\pgfxy("+x+","+ y+")}\n"); out.write("\\pgflineto{\\pgfxy("+x1+","+y1+")}\n"); out.write("\\pgflineto{\\pgfxy("+x2+","+y2+")}\n"); out.write("\\pgfclosepath \n"); if ((style & Arrow.flagEmpty) == 0) { out.write("\\pgffill \n"); } else { out.write("\\pgfqstroke \n"); } if ((style & Arrow.flagLimiter) != 0) { double x3; double y3; double x4; double y4; x3 = x - h*Math.sin(alpha); y3 = y + h*Math.cos(alpha); x4 = x + h*Math.sin(alpha); y4 = y - h*Math.cos(alpha); out.write("\\pgfline{\\pgfxy("+x3+","+y3+")}{\\pgfxy("+ x4+","+y4+")}\n"); } return new PointPr(x0,y0); } /** Called when exporting a Macro call. This function can just return false, to indicate that the macro should be rendered by means of calling the other primitives. Please note that a macro does not have a reference layer, since it is defined by its components. @param x the x position of the position of the macro. @param y the y position of the position of the macro. @param isMirrored true if the macro is mirrored. @param orientation the macro orientation in degrees. @param macroName the macro name. @param macroDesc the macro description, in the FidoCad format. @param name the shown name. @param xn coordinate of the shown name. @param yn coordinate of the shown name. @param value the shown value. @param xv coordinate of the shown value. @param yv coordinate of the shown value. @param font the used font. @param fontSize the size of the font to be used. @param m the library. @return true if the export is done by the function, false if the macro should be expanded into primitives. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public boolean exportMacro(int x, int y, boolean isMirrored, int orientation, String macroName, String macroDesc, String name, int xn, int yn, String value, int xv, int yv, String font, int fontSize, Map m) throws IOException { // The macro will be expanded into primitives. return false; } /** Called when exporting an Oval primitive. Specify the bounding box. @param x1 the x position of the first corner @param y1 the y position of the first corner @param x2 the x position of the second corner @param y2 the y position of the second corner @param isFilled it is true if the oval should be filled @param layer the layer that should be used @param dashStyle dashing style @param strokeWidth the width of the pen to be used when drawing @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportOval(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { registerColorSize(layer, strokeWidth); registerDash(dashStyle); out.write("\\pgfellipse["+(isFilled?"fillstroke":"stroke")+ "]{\\pgfxy("+(x1+x2)/2.0+","+(y1+y2)/2.0+")}{\\pgfxy("+ Math.abs(x2-x1)/2.0+",0)}{\\pgfxy(0,"+Math.abs(y2-y1)/2.0+")}\n"); } /** Called when exporting a PCBLine primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param width the width ot the line. @param layer the layer that should be used. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPCBLine(int x1, int y1, int x2, int y2, int width, int layer) throws IOException { registerColorSize(layer, width); // This avoids that some of the exported lines are dashed! registerDash(0); out.write("\\pgfline{\\pgfxy("+x1+","+y1+")}{\\pgfxy("+ x2+","+y2+")}\n"); } /** Called when exporting a PCBPad primitive. @param x the x position of the pad. @param y the y position of the pad. @param style the style of the pad (0: oval, 1: square, 2: rounded square.) @param six the x size of the pad. @param siy the y size of the pad. @param indiam the hole internal diameter. @param layer the layer that should be used. @param onlyHole true if only the hole should be exported. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPCBPad(int x, int y, int style, int six, int siy, int indiam, int layer, boolean onlyHole) throws IOException { double xdd; double ydd; if(onlyHole) { // ... then, drill the hole! if(!actualColor.equals(actualColor.white())) { actualColor=actualColor.white(); out.write("\\color{white}\n"); } out.write("\\pgfellipse[fillstroke"+ "]{\\pgfxy("+x+","+y+")}{\\pgfxy("+ (indiam/2)+",0)}{\\pgfxy(0,"+ (indiam/2)+")}\n"); } else { // At first, draw the pad... registerColorSize(layer, .33); switch (style) { case 1: // Square pad xdd=(double)x-six/2.0; ydd=(double)y-siy/2.0; out.write("\\pgfrect[fillstroke"+ "]{\\pgfxy("+xdd+","+ydd+")}{\\pgfxy("+ six+","+ siy+")}\n"); break; case 2: // Rounded pad xdd=(double)x-six/2.0; ydd=(double)y-siy/2.0; out.write("\\pgfrect[fillstroke"+ "]{\\pgfxy("+xdd+","+ydd+")}{\\pgfxy("+ six+","+ siy+")}\n"); break; case 0: // Oval pad default: out.write("\\pgfellipse[fillstroke"+ "]{\\pgfxy("+x+","+y+")}{\\pgfxy("+ (six/2.0)+",0)}{\\pgfxy(0,"+ (siy/2.0)+")}\n"); break; } } } /** Called when exporting a Polygon primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPolygon(PointDouble[] vertices, int nVertices, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { registerColorSize(layer, strokeWidth); registerDash(dashStyle); out.write("\\pgfmoveto{\\pgfxy("+vertices[0].x+","+ vertices[0].y+")}\n"); for (int i=1; i<nVertices; ++i) { out.write("\\pgflineto{\\pgfxy("+vertices[i].x+ ","+vertices[i].y+")}\n"); } out.write("\\pgfclosepath \n"); if(isFilled) { out.write("\\pgffill \n"); } else { out.write("\\pgfqstroke \n"); } } /** Called when exporting a Curve primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param isClosed true if the curve is closed. @param layer the layer that should be used. @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @return false if the curve should be rendered using a polygon, true if it is handled by the function. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public boolean exportCurve(PointDouble[] vertices, int nVertices, boolean isFilled, boolean isClosed, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { return false; } /** Called when exporting a Rectangle primitive. @param x1 the x position of the first corner. @param y1 the y position of the first corner. @param x2 the x position of the second corner. @param y2 the y position of the second corner. @param isFilled it is true if the rectangle should be filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportRectangle(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { registerColorSize(layer, strokeWidth); registerDash(dashStyle); out.write("\\pgfmoveto{\\pgfxy("+x1+","+y1+")}\n"); out.write("\\pgflineto{\\pgfxy("+x2+","+y1+")}\n"); out.write("\\pgflineto{\\pgfxy("+x2+","+y2+")}\n"); out.write("\\pgflineto{\\pgfxy("+x1+","+y2+")}\n"); out.write("\\pgfclosepath \n"); if(isFilled) { out.write("\\pgffill \n"); } else { out.write("\\pgfqstroke \n"); } } /** Check if there has been a change in the actual color and stroke width. if yes, change accordingly. @param layer the layer number (used for the color specification). @param strokeWidth (nothing is specified if non positive). @throws IOException if a disaster happens, i.e. a file can not be accessed. */ private void registerColorSize(int layer, double strokeWidth) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); if(!c.equals(actualColor)) { actualColor=c; out.write("\\color{layer"+layer+"}\n"); } if (strokeWidth > 0 && actualWidth!=strokeWidth) { out.write("\\pgfsetlinewidth{"+strokeWidth +"pt}\n"); actualWidth = strokeWidth; } } /** Check if there has been a change in the actual dash style if yes, change accordingly. @param dashStyle the wanted dashing style. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ private void registerDash(int dashStyle) throws IOException { if(currentDash!=dashStyle ||currentPhase!=dashPhase) { currentDash=dashStyle; currentPhase=dashPhase; if(dashStyle==0) { out.write("\\pgfsetdash{}{0pt}\n"); } else { out.write("\\pgfsetdash{"+sDash[dashStyle]+"}{"+dashPhase+ "pt}\n"); } } } }
27,632
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExportInterface.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/ExportInterface.java
package net.sourceforge.fidocadj.export; import java.util.*; import java.io.*; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.MacroDesc; import net.sourceforge.fidocadj.graphic.PointDouble; import net.sourceforge.fidocadj.graphic.DimensionG; /** ExportInterface.java Interface which allows to export a FidoCad draw under an arbitrary format. The primitive handling system of FidoCadJ will call each primitive export function and provide every informations about the primitive state. Each coordinate is given in FidoCadJ coordinate space, which means that normally one unit corresponds to 5 mils (127 microns). I do not consider the export phase as a speed sensitive context. For this reason, I try to write that interface in order to achieve the maximum ease of use of the various parameters involving each primitive. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public interface ExportInterface { /** Called at the beginning of the export phase. Ideally, in this routine there should be the code to write the header of the file on which the drawing should be exported. @param totalSize the size of the image. Useful to calculate for example the bounding box. @param la a vector describing the attributes of each layer. @param grid the grid size. This is useful when exporting to another drawing program having some kind of grid concept. You might use this value to synchronize FidoCadJ's grid with the one used by the target. @throws IOException if an error occurs. */ void exportStart(DimensionG totalSize, List<LayerDesc> la, int grid) throws IOException; /** Called at the end of the export phase. @throws IOException if an error occurs. */ void exportEnd() throws IOException; /** Set the multiplication factor to be used for the dashing. @param u the factor. */ void setDashUnit(double u); /** Set the "phase" in output units of the dashing style. For example, if a dash style is composed by a line followed by a space of equal size, a phase of 0 indicates that the dash starts with the line. @param p the phase, in output units. */ void setDashPhase(float p); /** Called when exporting an Advanced Text primitive. @param x the x position of the beginning of the string to be written. @param y the y position of the beginning of the string to be written. @param sizex the x size of the font to be used. @param sizey the y size of the font to be used. @param fontname the font to be used. @param isBold true if the text should be written with a boldface font. @param isMirrored true if the text should be mirrored. @param isItalic true if the text should be written with an italic font. @param orientation angle of orientation (degrees). @param layer the layer that should be used. @param text the text that should be written. @throws IOException if an error occurs. */ void exportAdvText (int x, int y, int sizex, int sizey, String fontname, boolean isBold, boolean isMirrored, boolean isItalic, int orientation, int layer, String text) throws IOException; /** Called when exporting a Bézier primitive. @param x1 the x position of the first point of the trace. @param y1 the y position of the first point of the trace. @param x2 the x position of the second point of the trace. @param y2 the y position of the second point of the trace. @param x3 the x position of the third point of the trace. @param y3 the y position of the third point of the trace. @param x4 the x position of the fourth point of the trace. @param y4 the y position of the fourth point of the trace. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if an error occurs. */ void exportBezier (int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException; /** Called when exporting a Connection primitive. @param x the x position of the position of the connection. @param y the y position of the position of the connection. @param size the size of the connection in logical units. @param layer the layer that should be used. @throws IOException if an error occurs. */ void exportConnection (int x, int y, int layer, double size) throws IOException; /** Called when exporting a Line primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if an error occurs. */ void exportLine (double x1, double y1, double x2, double y2, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException; /** Called when exporting a Macro call. This function can just return false, to indicate that the macro should be rendered by means of calling the other primitives. Please notice that a macro does not have a reference layer, since it is defined by its components. @param x the x position of the position of the macro. @param y the y position of the position of the macro. @param isMirrored true if the macro is mirrored. @param orientation the macro orientation in degrees. @param macroName the macro name. @param macroDesc the macro description, in the FidoCad format. @param name the shown name. @param xn coordinate of the shown name. @param yn coordinate of the shown name. @param value the shown value. @param xv coordinate of the shown value. @param yv coordinate of the shown value. @param font the used font. @param fontSize the size of the font to be used. @param m the library. @return false if the macro is exported in this function, true if it has to be split into primitives. @throws IOException if an error occurs. */ boolean exportMacro(int x, int y, boolean isMirrored, int orientation, String macroName, String macroDesc, String name, int xn, int yn, String value, int xv, int yv, String font, int fontSize, Map<String, MacroDesc> m) throws IOException; /** Called when exporting an Oval primitive. Specify the bounding box. @param x1 the x position of the first corner @param y1 the y position of the first corner @param x2 the x position of the second corner @param y2 the y position of the second corner @param isFilled it is true if the oval should be filled @param layer the layer that should be used @param dashStyle dashing style @param strokeWidth the width of the pen to be used when drawing @throws IOException if an error occurs. */ void exportOval(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException; /** Called when exporting a PCBLine primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param width the width ot the line. @param layer the layer that should be used. @throws IOException if an error occurs. */ void exportPCBLine(int x1, int y1, int x2, int y2, int width, int layer) throws IOException; /** Called when exporting a PCBPad primitive. @param x the x position of the pad. @param y the y position of the pad. @param style the style of the pad (0: oval, 1: square, 2: rounded square). @param six the x size of the pad. @param siy the y size of the pad. @param indiam the hole internal diameter. @param layer the layer that should be used. @param onlyHole true if only the hole should be exported. @throws IOException if an error occurs. */ void exportPCBPad(int x, int y, int style, int six, int siy, int indiam, int layer, boolean onlyHole) throws IOException; /** Called when exporting a Polygon primitive. @param vertices array containing the position of each vertex @param nVertices number of vertices @param isFilled true if the polygon is filled @param layer the layer that should be used @param dashStyle dashing style @param strokeWidth the width of the pen to be used when drawing @throws IOException if an error occurs. */ void exportPolygon(PointDouble[] vertices, int nVertices, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException; /** Called when exporting a Curve primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param isClosed true if the curve is closed. @param layer the layer that should be used. @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @return false if the curve should be rendered using a polygon, true if it is handled by the function. @throws IOException if an error occurs. */ boolean exportCurve(PointDouble[] vertices, int nVertices, boolean isFilled, boolean isClosed, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException; /** Called when exporting a Rectangle primitive. @param x1 the x position of the first corner. @param y1 the y position of the first corner. @param x2 the x position of the second corner. @param y2 the y position of the second corner. @param isFilled it is true if the rectangle should be filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if an error occurs. */ void exportRectangle(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException; /** Called when exporting an arrow. @param x position of the tip of the arrow. @param y position of the tip of the arrow. @param xc direction of the tip of the arrow. @param yc direction of the tip of the arrow. @param l length of the arrow. @param h width of the arrow. @param style style of the arrow. @return the coordinates of the base of the arrow. @throws IOException if an error occurs. */ PointPr exportArrow(double x, double y, double xc, double yc, double l, double h, int style) throws IOException; }
14,026
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExportEPS.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/ExportEPS.java
package net.sourceforge.fidocadj.export; import java.util.*; import java.io.*; import java.text.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.MacroDesc; import net.sourceforge.fidocadj.primitives.Arrow; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.ColorInterface; import net.sourceforge.fidocadj.graphic.DecoratedText; import net.sourceforge.fidocadj.graphic.PointDouble; import net.sourceforge.fidocadj.graphic.TextInterface; /** Drawing export in Encapsulated Postscript <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class ExportEPS implements ExportInterface, TextInterface { private final FileWriter fstream; private BufferedWriter out; private List layerV; private double actualWidth; private ColorInterface actualColor; private int currentDash; private float dashPhase; private float currentPhase=-1; private float currentFontSize=0; private DecoratedText dt; private String fontname; // Some info about the font is stored private String bold=""; private float textx; // This is used in sub-sup scripts position private float texty; // Number of digits to be used when representing coordinates static final int PREC = 3; // Dash patterns private String sDash[]; /* static final String dash[]={"[5.0 10]", "[2.5 2.5]", "[1.0 1.0]", "[1.0 2.5]", "[1.0 2.5 2.5 2.5]"};*/ /** Set the multiplication factor to be used for the dashing. @param u the factor. */ public void setDashUnit(double u) { sDash = new String[Globals.dashNumber]; // If the line width has been changed, we need to update the // stroke table // The first entry is non dashed sDash[0]=""; // Resize the dash sizes depending on the current zoom size. String dashArrayStretched; // Then, the dashed stroke styles are created. for(int i=1; i<Globals.dashNumber; ++i) { // Prepare the resized dash array. dashArrayStretched = ""; for(int j=0; j<Globals.dash[i].length;++j) { dashArrayStretched+=(Globals.dash[i][j]*(float)u/2.0f); if(j<Globals.dash[i].length-1) { dashArrayStretched+=" "; } } sDash[i]="["+dashArrayStretched+"]"; } } /** Set the "phase" in output units of the dashing style. For example, if a dash style is composed by a line followed by a space of equal size, a phase of 0 indicates that the dash starts with the line. @param p the phase, in output units. */ public void setDashPhase(float p) { dashPhase=p; } /** Constructor @param f the File object in which the export should be done. @throws IOException when things goes horribly wrong, for example if the file specified is not accessible. */ public ExportEPS (File f) throws IOException { fstream = new FileWriter(f); dt=new DecoratedText(this); } /** Called at the beginning of the export phase. Ideally, in this routine there should be the code to write the header of the file on which the drawing should be exported. @param totalSize the size of the image. Useful to calculate for example the bounding box. @param la a vector describing the attributes of each layer. @param grid the grid size. This is useful when exporting to another drawing program having some kind of grid concept. You might use this value to synchronize FidoCadJ's grid with the one used by the target. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportStart(DimensionG totalSize, List<LayerDesc> la, int grid) throws IOException { // We need to save layers informations, since we will use them later. layerV=la; out = new BufferedWriter(fstream); // An header of the EPS file // 200 dpi is the internal resolution of FidoCadJ // 72 dpi is the internal resolution of the Postscript coordinates double resMult=200.0/72.0; //resMult /= getMagnification(); out.write("%!PS-Adobe-3.0 EPSF-3.0\n"); out.write("%%Pages: 0\n"); out.write("%%BoundingBox: -1 -1 "+(int)(totalSize.width/resMult+1)+" "+ (int)(totalSize.height/resMult+1)+"\n"); out.write("%%Creator: FidoCadJ "+Globals.version+ ", EPS export filter by Davide Bucci\n"); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", new Locale("en")); Date date = new Date(); out.write("%%CreationDate: "+dateFormat.format(date)+"\n"); out.write("%%EndComments\n"); // Create a new dictionary term: ellipse // This is based on an example of the Blue Book // http://www.science.uva.nl/~robbert/ps/bluebook/program_03.html out.write("/ellipsedict 8 dict def\n"+ "ellipsedict /mtrx matrix put\n"+ "/ellipse\n"+ " { ellipsedict begin\n"+ " /endangle exch def\n"+ " /startangle exch def\n"+ " /yrad exch def\n"+ " /xrad exch def\n"+ " /y exch def\n"+ " /x exch def\n"+ " /savematrix mtrx currentmatrix def\n"+ " x y translate\n"+ " xrad yrad scale\n"+ " 0 0 1 startangle endangle arc\n"+ " savematrix setmatrix\n"+ " end\n"+ " } def\n"); // Since in a postscript drawing, the origin is at the bottom left, // we introduce a coordinate transformation to have it at the top // left of the drawing. out.write("0 "+(totalSize.height/resMult)+" translate\n"); out.write(""+(1/resMult)+" "+(-1/resMult)+" scale\n"); } /** Called at the end of the export phase. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportEnd() throws IOException { out.write("%%EOF\n"); out.close(); } /** Called when exporting an Advanced Text primitive. @param x the x position of the beginning of the string to be written. @param y the y position of the beginning of the string to be written. @param sizex the x size of the font to be used. @param sizey the y size of the font to be used. @param fontnameT the font to be used. @param isBold true if the text should be written with a boldface font. @param isMirrored true if the text should be mirrored. @param isItalic true if the text should be written with an italic font. @param orientation angle of orientation (degrees). @param layer the layer that should be used. @param textT the text that should be written. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportAdvText (int x, int y, int sizex, int sizey, String fontnameT, boolean isBold, boolean isMirrored, boolean isItalic, int orientation, int layer, String textT) throws IOException { String text = textT; LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, -1); currentFontSize = (int)(sizex*12/(double)7+.5); fontname = fontnameT; if(isBold) { bold="-Bold"; } else { bold=""; } // It seems that Postscript fonts can not handle spaces. So I substitute // every space with a "-" sign. Map<String, String> substFont = new HashMap<String, String>(); substFont.put(" ","-"); fontname=Globals.substituteBizarreChars(fontname, substFont); out.write("/"+fontname+bold+" findfont\n"+ (int)currentFontSize+" scalefont\n"+ "setfont\n"); out.write("newpath\n"); out.write("" +x+" "+y+" moveto\n"); textx=x; texty=y; out.write("gsave\n"); if(orientation !=0) { out.write(" "+(isMirrored?orientation:-orientation)+" rotate\n"); } if(isMirrored) { out.write(" -1 -1 scale\n"); } else { out.write(" 1 -1 scale\n"); } // Remember that we consider sizex/sizey=7/12 as the "normal" aspect // ratio. double ratio; if(sizey/sizex == 10/7){ ratio = 1.0; } else { ratio=(double)sizey/(double)sizex*22.0/40.0; } out.write(" "+1+" "+ratio+" scale\n"); out.write(" 0 " +(-currentFontSize*0.8)+" rmoveto\n"); checkColorAndWidth(c, 0.33); Map<String, String> subst = new HashMap<String, String>(); subst.put("(","\\050"); subst.put(")","\\051"); text=Globals.substituteBizarreChars(text, subst); dt.drawString(text,x,y); out.write("grestore\n"); } /** Called when exporting a Bézier primitive. @param x1 the x position of the first point of the trace @param y1 the y position of the first point of the trace @param x2 the x position of the second point of the trace @param y2 the y position of the second point of the trace @param x3 the x position of the third point of the trace @param y3 the y position of the third point of the trace @param x4 the x position of the fourth point of the trace @param y4 the y position of the fourth point of the trace @param layer the layer that should be used // from 0.22.1 @param arrowStart true if an arrow is present at the first point. @param arrowEnd true if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportBezier (int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, strokeWidth); registerDash(dashStyle); if (arrowStart) { PointPr p=exportArrow(x1, y1, x2, y2, arrowLength, arrowHalfWidth, arrowStyle); // This fixes issue #172 // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if(arrowLength>0) { x1=(int)Math.round(p.x); y1=(int)Math.round(p.y); } } if (arrowEnd) { PointPr p=exportArrow(x4, y4, x3, y3, arrowLength, arrowHalfWidth, arrowStyle); // Fix #172 if(arrowLength>0) { x4=(int)Math.round(p.x); y4=(int)Math.round(p.y); } } out.write(""+x1+" "+y1+" moveto \n"); out.write(""+x2+" "+y2+" "+x3+" "+y3+" "+x4+" "+y4+" curveto stroke\n"); } /** Called when exporting a Connection primitive. @param x the x position of the position of the connection. @param y the y position of the position of the connection. @param layer the layer that should be used. @param nodeSize the size of the electrical connection in logical units. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportConnection (int x, int y, int layer, double nodeSize) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, 0.33); out.write("newpath\n"); out.write(""+x+" "+y+" "+ nodeSize/2.0+ " " + nodeSize/2.0+ " 0 360 ellipse\n"); out.write("fill\n"); } /** Called when exporting a Line primitive. @param x1 the x position of the first point of the segment @param y1 the y position of the first point of the segment @param x2 the x position of the second point of the segment @param y2 the y position of the second point of the segment @param layer the layer that should be used // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportLine (double x1, double y1, double x2, double y2, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, strokeWidth); registerDash(dashStyle); double xstart=x1; double ystart=y1; double xend=x2; double yend=y2; if (arrowStart) { PointPr p=exportArrow(x1, y1, x2, y2, arrowLength, arrowHalfWidth, arrowStyle); // This fixes issue #172 // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if(arrowLength>0) { xstart=p.x; ystart=p.y; } } if (arrowEnd) { PointPr p=exportArrow(x2, y2, x1, y1, arrowLength, arrowHalfWidth, arrowStyle); // Fix #172 if(arrowLength>0) { xend=p.x; yend=p.y; } } out.write(""+xstart+" "+ystart+" moveto "+ xend+" "+yend+" lineto stroke\n"); } /** Called when exporting an arrow. @param x position of the tip of the arrow. @param y position of the tip of the arrow. @param xc direction of the tip of the arrow. @param yc direction of the tip of the arrow. @param l length of the arrow. @param h width of the arrow. @param style style of the arrow. @return the coordinates of the base of the arrow. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public PointPr exportArrow(double x, double y, double xc, double yc, double l, double h, int style) throws IOException { double alpha; double x0; double y0; double x1; double y1; double x2; double y2; // At first we need the angle giving the direction of the arrow // a little bit of trigonometry :-) if (x==xc) { alpha = Math.PI/2.0+(y-yc<0.0?0.0:Math.PI); } else { alpha = Math.atan((double)(y-yc)/(double)(x-xc)); } alpha += x-xc>0.0?0.0:Math.PI; // Then, we calculate the points for the polygon x0 = x - l*Math.cos(alpha); y0 = y - l*Math.sin(alpha); x1 = x0 - h*Math.sin(alpha); y1 = y0 + h*Math.cos(alpha); x2 = x0 + h*Math.sin(alpha); y2 = y0 - h*Math.cos(alpha); out.write("newpath\n"); out.write(""+Globals.roundTo(x)+" "+ Globals.roundTo(y)+" moveto\n"); out.write(""+Globals.roundTo(x1)+" "+Globals.roundTo(y1)+" lineto\n"); out.write(""+Globals.roundTo(x2)+" "+Globals.roundTo(y2)+" lineto\n"); out.write("closepath\n"); if ((style & Arrow.flagEmpty) == 0) { out.write("fill \n"); } else { out.write("stroke \n"); } if ((style & Arrow.flagLimiter) != 0) { double x3; double y3; double x4; double y4; x3 = x - h*Math.sin(alpha); y3 = y + h*Math.cos(alpha); x4 = x + h*Math.sin(alpha); y4 = y - h*Math.cos(alpha); out.write(""+Globals.roundTo(x3)+" "+Globals.roundTo(y3)+ " moveto\n"+Globals.roundTo(x4)+" "+Globals.roundTo(y4)+ " lineto\nstroke\n"); } return new PointPr(x0,y0); } /** Called when exporting a Macro call. This function can just return false, to indicate that the macro should be rendered by means of calling the other primitives. Please note that a macro does not have a reference layer, since the elements composing it already have their own. @param x the x position of the position of the macro. @param y the y position of the position of the macro. @param isMirrored true if the macro is mirrored. @param orientation the macro orientation in degrees. @param macroName the macro name. @param macroDesc the macro description, in the FidoCad format. @param name the shown name. @param xn coordinate of the shown name. @param yn coordinate of the shown name. @param value the shown value. @param xv coordinate of the shown value. @param yv coordinate of the shown value. @param font the used font. @param fontSize the size of the font to be used. @param m the library. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. @return true if the macro is exported as a whole, false if it should be expanded into primitives. */ public boolean exportMacro(int x, int y, boolean isMirrored, int orientation, String macroName, String macroDesc, String name, int xn, int yn, String value, int xv, int yv, String font, int fontSize, Map<String, MacroDesc> m) throws IOException { // The macro will be expanded into primitives. return false; } /** Called when exporting an Oval primitive. Specify the bounding box. @param x1 the x position of the first corner. @param y1 the y position of the first corner. @param x2 the x position of the second corner. @param y2 the y position of the second corner. @param isFilled it is true if the oval should be filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportOval(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, strokeWidth); registerDash(dashStyle); out.write("newpath\n"); out.write(""+(x1+x2)/2.0+" "+(y1+y2)/2.0+" "+ Math.abs(x2-x1)/2.0+ " " + Math.abs(y2-y1)/2.0+ " 0 360 ellipse\n"); if(isFilled) { out.write("fill\n"); } else { out.write("stroke\n"); } } /** Called when exporting a PCBLine primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param width the width ot the line. @param layer the layer that should be used. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportPCBLine(int x1, int y1, int x2, int y2, int width, int layer) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, width); registerDash(0); out.write("1 setlinecap\n"); out.write(""+x1+" "+y1+" moveto "+ x2+" "+y2+" lineto stroke\n"); } /** Called when exporting a PCBPad primitive. @param x the x position of the pad. @param y the y position of the pad. @param style the style of the pad (0: oval, 1: square, 2: rounded square). @param six the x size of the pad. @param siy the y size of the pad. @param indiam the hole internal diameter. @param layer the layer that should be used. @param onlyHole true if only the hole (drill) should be exported. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportPCBPad(int x, int y, int style, int six, int siy, int indiam, int layer, boolean onlyHole) throws IOException { double xdd; double ydd; LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, 0.33); // At first, draw the pad... if(!onlyHole) { switch (style) { case 2: // Rounded pad roundRect(x-six/2.0, y-siy/2.0, six, siy, 4, true); break; case 1: // Square pad xdd=(double)x-six/2.0; ydd=(double)y-siy/2.0; out.write("newpath\n"); out.write(""+xdd+" "+ydd+" moveto\n"); out.write(""+(xdd+six)+" "+ydd+" lineto\n"); out.write(""+(xdd+six)+" "+(ydd+siy)+" lineto\n"); out.write(""+xdd+" "+(ydd+siy)+" lineto\n"); out.write("closepath\n"); out.write("fill\n"); break; case 0: // Oval pad default: out.write("newpath\n"); out.write(""+x+" "+y+" "+ six/2.0+ " " +siy/2.0+ " 0 360 ellipse\n"); out.write("fill\n"); break; } } // ... then, drill the hole! //out.write("1 1 1 setrgbcolor\n"); checkColorAndWidth(c.white(), 0.33); out.write("newpath\n"); out.write(""+x+" "+y+" "+ indiam/2.0+ " " +indiam/2.0+ " 0 360 ellipse\n"); out.write("fill\n"); } /** Called when exporting a Polygon primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportPolygon(PointDouble[] vertices, int nVertices, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); if (nVertices<1) { return; } checkColorAndWidth(c, strokeWidth); registerDash(dashStyle); out.write("newpath\n"); out.write(""+vertices[0].x+" "+vertices[0].y+" moveto\n"); for (int i=1; i<nVertices; ++i) { out.write(""+vertices[i].x+" "+vertices[i].y+" lineto\n"); } out.write("closepath\n"); if(isFilled) { out.write("fill\n"); } else { out.write("stroke\n"); } } /** Called when exporting a Curve primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param isClosed true if the curve is closed. @param layer the layer that should be used. @param arrowStart true if an arrow is present at the first point. @param arrowEnd true if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength the length of the arrow. @param arrowHalfWidth the half width of the arrow. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. @return false if the curve should be rendered using a polygon, true if it is handled by the function. */ public boolean exportCurve(PointDouble[] vertices, int nVertices, boolean isFilled, boolean isClosed, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { return false; } /** Called when exporting a Rectangle primitive. @param x1 the x position of the first corner @param y1 the y position of the first corner @param x2 the x position of the second corner @param y2 the y position of the second corner @param isFilled it is true if the rectangle should be filled @param layer the layer that should be used @param dashStyle dashing style @param strokeWidth the width of the pen to be used when drawing @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportRectangle(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, strokeWidth); registerDash(dashStyle); out.write("newpath\n"); out.write(""+Globals.roundTo(x1,PREC)+" "+Globals.roundTo(y1,PREC)+ " moveto\n"); out.write(""+Globals.roundTo(x2,PREC)+" "+Globals.roundTo(y1,PREC)+ " lineto\n"); out.write(""+Globals.roundTo(x2,PREC)+" "+Globals.roundTo(y2,PREC)+ " lineto\n"); out.write(""+Globals.roundTo(x1,PREC)+" "+Globals.roundTo(y2,PREC)+ " lineto\n"); out.write("closepath\n"); if(isFilled) { out.write("fill\n"); } else { out.write("stroke\n"); } } private void roundRect (double x1, double y1, double w, double h, double r, boolean filled) throws IOException { out.write(""+(x1+r) + " " +y1+" moveto\n"); out.write(""+(x1+w-r) + " " +y1+" lineto\n"); out.write(""+(x1+w) + " " +y1+" "+ (x1+w) + " "+y1 + " "+(x1+w) + " " +(y1+r)+ " curveto\n"); out.write(""+(x1+w) + " " +(y1+h-r)+" lineto\n"); out.write(""+(x1+w) + " " +(y1+h)+" "+(x1+w) + " " +(y1+h)+ " "+(x1+w-r)+" "+(y1+h)+" curveto\n"); out.write(""+ (x1+r) + " " +(y1+h)+" lineto\n"); out.write(""+ x1+ " " +(y1+h)+" "+ x1+ " " +(y1+h)+ " "+ x1 + " " +(y1+h-r)+" curveto\n"); out.write(""+ x1 + " " +(y1+r)+" lineto\n"); out.write(""+x1 + " " +y1+" "+x1 + " " +y1+" "+ (x1+r)+" "+y1+" curveto\n"); out.write(" "+(filled?"fill\n":"stroke\n")); } /** Set the current color (only if necessary) and the stroke width which will be employed for subsequent drawing operations. @param c the color @param wl the stroke width. If a negative number is employed, a new stroke width will not be set. */ private void checkColorAndWidth(ColorInterface c, double wl) throws IOException { if(!c.equals(actualColor)) { out.write(" "+Globals.roundTo(c.getRed()/255.0)+" "+ Globals.roundTo(c.getGreen()/255.0)+ " " +Globals.roundTo(c.getBlue()/255.0)+ " setrgbcolor\n"); actualColor=c; } if(wl>0 && wl != actualWidth) { out.write(" " +wl+" setlinewidth\n"); actualWidth = wl; } } private void registerDash(int dashStyle) throws IOException { if(currentDash!=dashStyle ||currentPhase!=dashPhase) { currentDash=dashStyle; currentPhase=dashPhase; if(dashStyle==0) { out.write("[] 0 setdash\n"); } else { out.write(""+sDash[dashStyle]+" "+dashPhase+" setdash\n"); } } } // Functions required for the TextInterface. /** Get the font size. @return the font size. */ public double getFontSize() { return currentFontSize; } /** Set the font size. @param size the font size. */ public void setFontSize(double size) { currentFontSize=(float)size; try { out.write("/"+fontname+bold+" findfont\n"+ (int)currentFontSize+" scalefont\n"+ "setfont\n"); } catch(IOException e) { System.err.println("Can not write to file in EPS export."); } } /** Get the width of the given string with the current font. @param s the string to be used. @return the width of the string, in pixels. */ public int getStringWidth(String s) { return 0; } /** Draw a string on the current graphic context. @param str the string to be drawn. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. */ public void drawString(String str, int x, int y) { try{ out.write("" + (textx-x) +" "+ (texty-y)+ " rmoveto\n"); texty=y; out.write(" ("+str+") show\n"); } catch(IOException e) { System.err.println("Can not write to file in EPS export."); } } }
33,041
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExportPDF.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/ExportPDF.java
package net.sourceforge.fidocadj.export; import java.util.*; import java.io.*; import javax.swing.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.Arrow; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.graphic.ColorInterface; import net.sourceforge.fidocadj.graphic.DecoratedText; import net.sourceforge.fidocadj.graphic.PointDouble; import net.sourceforge.fidocadj.graphic.TextInterface; /** Export towards the Adobe Portable Document File <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class ExportPDF implements ExportInterface, TextInterface { private final File temp; private final OutputStreamWriter fstream; private final OutputStreamWriter fstreamt; private BufferedWriter out; private BufferedWriter outt; private boolean fontWarning; private String userfont; private float dashPhase; private float currentPhase=-1; private float currentFontSize=0; private DecoratedText dt; private String currentFont; // Some info about the font is stored private float textx; // This is used in sub-sup scripts position private float texty; // A graphic interface object is used here to get information about the // size of the different glyphs in the font. private final GraphicsInterface gi; // Well, this is a complex stuff. In practice, in the PDF format we have to // map the UTF8 code to the Adobe name of glyphs in a font. This is // accomplished by reading a file presenting the correspondance between // the standard UTF8 code and the glyph name. This file is from Adobe and // it is called glyphlist.txt available here: // https://github.com/adobe-type-tools/agl-aglfn // The Map is completed in the exportStart method of this class. // During the export of text (exportAdvText), a list of unicode chars // whose encoding will be considered in the PDF is filled. // At the end of the export, an encoding mapping will be created. private Map<Integer, String> unicodeToGlyph; private Map<Integer, Integer> uncodeCharsNeeded; private int unicodeCharIndex; // The file header private String head; // An array which will contain String elements representing all the // objects present in the PDF file. private String obj_PDF[]; // The maximum number of objects contained in the PDF file. private static final int numOfObjects = 20; private String closeObject; private long fileLength; private List layerV; private ColorInterface actualColor; private double actualWidth; private int currentDash; static final String encoding="UTF8"; private String sDash[]; /** Set the multiplication factor to be used for the dashing. @param u the factor. */ public void setDashUnit(double u) { sDash = new String[Globals.dashNumber]; // If the line width has been changed, we need to update the // stroke table // The first entry is non dashed sDash[0]=""; // Resize the dash sizes depending on the current zoom size. String dashArrayStretched; // Then, the dashed stroke styles are created. for(int i=1; i<Globals.dashNumber; ++i) { // Prepare the resized dash array. dashArrayStretched = ""; for(int j=0; j<Globals.dash[i].length;++j) { dashArrayStretched+=(Globals.dash[i][j]*(float)u/2.0f); if(j<Globals.dash[i].length-1) { dashArrayStretched+=" "; } } sDash[i]="["+dashArrayStretched+"]"; } } /** Set the "phase" in output units of the dashing style. For example, if a dash style is composed by a line followed by a space of equal size, a phase of 0 indicates that the dash starts with the line. @param p the phase, in output units. */ public void setDashPhase(float p) { dashPhase=p; } /** Constructor @param f the File object in which the export should be done. @param gg the graphic object. Mainly required to calculate text sizes and calculating text positions. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public ExportPDF (File f, GraphicsInterface gg) throws IOException { gi=gg; dashPhase=0; fstream = new OutputStreamWriter(new FileOutputStream(f), encoding); temp = File.createTempFile("real",".howto"); temp.deleteOnExit(); fstreamt = new OutputStreamWriter(new FileOutputStream(temp), encoding); obj_PDF = new String[numOfObjects]; dt=new DecoratedText(this); } /** Called at the beginning of the export phase. Ideally, in this routine there should be the code to write the header of the file on which the drawing should be exported. @param totalSize the size of the image. Useful to calculate for example the bounding box. @param la a vector describing the attributes of each layer. @param grid the grid size. This is useful when exporting to another drawing program having some kind of grid concept. You might use this value to synchronize FidoCadJ's grid with the one used by the target. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportStart(DimensionG totalSize, List<LayerDesc> la, int grid) throws IOException { initGlyphList(); // We need to save layers informations, since we will use them later. layerV=la; out = new BufferedWriter(fstream); fontWarning=false; // To track the block sizes, we will first write all graphic elements // in a temporary file, whose stream is called outt instead of out. // At the end, the contents of the temporary file will be copied in // the definitive destination file. outt = new BufferedWriter(fstreamt); // A header of the EPS file // 200 dpi is the internal resolution of FidoCadJ // 72 dpi is the internal resolution of the Postscript coordinates double resMult=200.0/72.0; int border = 5; head = "%PDF-1.4\n"; // Object 5 is a single page of the appropriate size, containing // as a child object 4. obj_PDF[5]= "5 0 obj\n"+ " <</Kids [4 0 R ]\n"+ " /Count 1\n"+ " /Type /Pages\n"+ " /MediaBox [ 0 0 "+ (int)(totalSize.width/resMult+1+border)+" "+ (int)(totalSize.height/resMult+1+border)+" ]\n"+ " >> endobj\n"; // Since in a postscript drawing, the origin is at the bottom left, // we introduce a coordinate transformation to have it at the top // left of the drawing. actualColor = null; actualWidth = -1; outt.write(" 1 0 0 1 0 "+(totalSize.height/resMult+border)+ " cm\n"); outt.write(" "+(1/resMult)+" 0 0 "+(-1/resMult)+" 0 0 cm\n"); outt.write("1 J\n"); } /** Init the list of glyphs by reading the glyphlist.txt file if it is available. */ private void initGlyphList() throws IOException { // The glyphlist.txt file has about 4300 lines, therefore starting // with a size of 5000 seems reasonable. unicodeToGlyph = new HashMap<Integer, String>(5000); // 128 chars for the moment will suffice. uncodeCharsNeeded = new HashMap<Integer, Integer>(128); // The mapping of Unicode chars will be done starting from code 128 // up to 256. For the moment it will suffice. unicodeCharIndex=127; // Read the glyphlist.txt file and store its contents in the hash // map for easy retrieval during the calculation of encoding needs. BufferedReader br=null; InputStreamReader isr=null; try{ isr = new InputStreamReader( getClass().getResourceAsStream("glyphlist.txt"), encoding); br = new BufferedReader(isr); String line = br.readLine(); String glyph; Integer code; String codeStr; int p; int q; while (line != null) { if(!line.startsWith("#")) { p=line.indexOf(';'); q=line.indexOf(' '); glyph=line.substring(0,p); if(q<0) { codeStr=line.substring(p+1); } else { codeStr=line.substring(p+1,q); } code=Integer.decode("0x"+codeStr); unicodeToGlyph.put(code, glyph); } line = br.readLine(); } } catch(IOException ee) { System.err.println("We could not access glyphlist.txt. A standard"+ " matching of glyphs is attempted."); for(int i=32; i<128; ++i) { unicodeToGlyph.put(Integer.valueOf(i), ""+i); } } finally { if (br!=null) { br.close(); } if (isr!=null) { isr.close(); } } } /** Called at the end of the export phase. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportEnd() throws IOException { //DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); //Date date = new Date(); outt.close(); fileLength=temp.length(); writeFontDescription(); obj_PDF[8]="8 0 obj\n" + " <<\n" + " /Length "+fileLength+"\n" + " >>\n"+ " stream\n"; out.write(head+obj_PDF[5]+obj_PDF[6]+obj_PDF[7]+obj_PDF[8]); // Object 4 is a font container. The objects corresponding to fonts // F1--F8 will be objects 6 to 14 (except object 8). obj_PDF[4] = "4 0 obj\n"+ "<< \n"+ " /Type /Page\n"+ " /Parent 5 0 R\n"+ " /Resources <<\n"+ " /Font <<\n"+ " /F1 6 0 R\n"+ " /F2 7 0 R\n"+ " /F3 9 0 R\n"+ " /F4 10 0 R\n"+ " /F5 11 0 R\n"+ " /F6 12 0 R\n"+ " /F7 13 0 R\n"+ " /F8 14 0 R\n"+ " /F9 15 0 R\n"+ ">>\n"+ "/ProcSet 2 0 R\n"+ ">>\n"+ " /Contents 8 0 R\n"+ ">>\n"+ "endobj\n"; obj_PDF[2] = "2 0 obj\n"+ "[ /PDF /Text ]\n"+ "endobj\n"; // Object 1 is just a header obj_PDF[1]="1 0 obj\n"+ "<<\n"+ " /Creator (FidoCadJ"+Globals.version+ ", PDF export filter by Davide Bucci)\n"+ // " /CreationDate ("+dateFormat.format(date)+")\n"+ " /Author ("+System.getProperty("user.name")+")\n"+ " /Producer (FidoCadJ)\n"+ ">>\n"+ "endobj\n"; obj_PDF[3] = "3 0 obj\n"+ "<<\n"+ " /Pages 5 0 R\n"+ " /Type /Catalog\n"+ ">>\n"+ "endobj\n"; BufferedReader br= new BufferedReader(new InputStreamReader( new FileInputStream(temp), encoding)); try{ String line = br.readLine(); while (line != null) { out.write(line+"\n"); line = br.readLine(); } } finally { br.close(); } closeObject="endstream\n"+"endobj\n"; out.write(closeObject+obj_PDF[4]+obj_PDF[2]+obj_PDF[1]+ obj_PDF[3]+obj_PDF[9]+obj_PDF[10]+obj_PDF[11]+obj_PDF[12]+ obj_PDF[13]+obj_PDF[14]+obj_PDF[15]+obj_PDF[16]); writeCrossReferenceTable(); out.close(); if (fontWarning) { if (java.awt.GraphicsEnvironment.isHeadless()) { System.err.println("Some fonts were not available!"); } else { JOptionPane.showMessageDialog(null, Globals.messages.getString("PDF_Font_error")); } } } /** This routine creates the eight definition of the fonts currently available: F1 - Courier F2 - Courier Bold F3 - Times Roman F4 - Times Bold F5 - Helvetica F6 - Helvetica Bold F7 - Symbol F8 - Symbol F9 - Undefinite @throws IOException if a disaster happens, i.e. a file can not be accessed. */ private void writeFontDescription() throws IOException { obj_PDF[6]= "6 0 obj\n" + " << /Type /Font\n" + " /Subtype /Type1\n" + " /BaseFont /Courier\n" + calcWidthsIndex("Courier")+ " /Encoding 16 0 R\n" + " >> endobj\n"; obj_PDF[7]="7 0 obj\n" + " << /Type /Font\n" + " /Subtype /Type1\n" + // " /Name /F2\n" + " /BaseFont /Courier-Bold\n" + calcWidthsIndex("Courier-Bold")+ " /Encoding 16 0 R\n" + " >> endobj\n"; obj_PDF[9]="9 0 obj\n" + " << /Type /Font\n" + " /Subtype /Type1\n" + // " /Name /F3\n" + " /BaseFont /Times-Roman\n" + calcWidthsIndex("Times-Roman")+ " /Encoding 16 0 R\n" + " >> endobj\n"; obj_PDF[10]="10 0 obj\n" + " << /Type /Font\n" + " /Subtype /Type1\n" + // " /Name /F4\n" + " /BaseFont /Times-Bold\n" + calcWidthsIndex("Times-Bold")+ " /Encoding 16 0 R\n" + " >> endobj\n"; obj_PDF[11]="11 0 obj\n" + " << /Type /Font\n" + " /Subtype /Type1\n" + // " /Name /F5\n" + " /BaseFont /Helvetica\n" + calcWidthsIndex("Helvetica")+ " /Encoding 16 0 R\n" + " >> endobj\n"; obj_PDF[12]="12 0 obj\n" + " << /Type /Font\n" + " /Subtype /Type1\n" + // " /Name /F6\n" + " /BaseFont /Helvetica-Bold\n" + calcWidthsIndex("Helvetica-Bold")+ " /Encoding 16 0 R\n" + " >> endobj\n"; obj_PDF[13]="13 0 obj\n" + " << /Type /Font\n" + " /Subtype /Type1\n" + // " /Name /F7\n" + " /BaseFont /Symbol\n" + calcWidthsIndex("Symbol")+ " /Encoding 16 0 R\n" + " >> endobj\n"; obj_PDF[14]="14 0 obj\n" + " << /Type /Font\n" + " /Subtype /Type1\n" + calcWidthsIndex("Symbol")+ // " /Name /F8\n" + " /BaseFont /Symbol\n" + " /Encoding 16 0 R\n" + " >> endobj\n"; obj_PDF[15]="15 0 obj\n" + " << /Type /Font\n" + " /Subtype /Type1\n" + calcWidthsIndex(userfont)+ " /BaseFont /"+userfont+"\n" + " /Encoding 16 0 R\n" + " >> endobj\n"; obj_PDF[16]="16 0 obj\n"+ " << /Type /Encoding\n"+ " /BaseEncoding /WinAnsiEncoding\n"+ " /Differences ["; for (Integer code : uncodeCharsNeeded.keySet()) { obj_PDF[16]+=""+code+"/"+unicodeToGlyph.get( uncodeCharsNeeded.get(code))+" "; } obj_PDF[16]+="]\n >> endobj\n"; } private String calcWidthsIndex(String font) { StringBuilder charWidths=new StringBuilder(); gi.setFont(font, 24); int basewidth=gi.getStringWidth("M"); charWidths.append(" /FirstChar 32\n"); charWidths.append(" /LastChar "); charWidths.append(unicodeCharIndex); charWidths.append("\n"); charWidths.append(" /Widths ["); int calcwidth; int mwidth=900; for (int i=32; i<128;++i) { calcwidth=mwidth*gi.getStringWidth(""+(char)i)/basewidth; charWidths.append(calcwidth); charWidths.append(" "); } for (Integer code : uncodeCharsNeeded.keySet()) { calcwidth=mwidth*gi.getStringWidth(""+ (char)uncodeCharsNeeded.get(code).intValue())/basewidth; charWidths.append(calcwidth); charWidths.append(" "); } charWidths.append("]\n"); return charWidths.toString(); } /** Here we create the cross reference table for the PDF file, as well as the trailer. Order of the objects: header, 5, 6, 7, 8, file, closeObject, 4, 2, 1, 3 This is probably among the most boring code in FidoCadJ. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ private void writeCrossReferenceTable() throws IOException { out.write("xref \n"+ "0 15\n"+ "0000000000 65535 f \n"+ // header addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength+ closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length())+ " 00000 n \n"+ // 1 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length())+ " 00000 n \n"+ // 2 addLeadZeros(head.length() + obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length()+ obj_PDF[1].length())+ " 00000 n \n"+ // 3 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length())+ " 00000 n \n"+ // 4 addLeadZeros(head.length())+ " 00000 n \n"+ // 5 addLeadZeros(head.length()+ obj_PDF[5].length())+ " 00000 n \n"+ // 6 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length())+ " 00000 n \n"+ // 7 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length())+ " 00000 n \n"+ // 8 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length()+ obj_PDF[1].length()+ obj_PDF[3].length())+ " 00000 n \n"+ // 9 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length()+ obj_PDF[1].length()+ obj_PDF[3].length()+ obj_PDF[9].length())+ " 00000 n \n"+ // 10 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length()+ obj_PDF[1].length()+ obj_PDF[3].length()+ obj_PDF[9].length()+ obj_PDF[10].length())+ " 00000 n \n"+ // 11 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length()+ obj_PDF[1].length()+ obj_PDF[3].length()+ obj_PDF[9].length()+ obj_PDF[10].length()+ obj_PDF[11].length())+ " 00000 n \n"+ // 12 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length()+ obj_PDF[1].length()+ obj_PDF[3].length()+ obj_PDF[9].length()+ obj_PDF[10].length()+ obj_PDF[11].length()+ obj_PDF[12].length())+ " 00000 n \n"+ // 13 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length()+ obj_PDF[1].length()+ obj_PDF[3].length()+ obj_PDF[9].length()+ obj_PDF[10].length()+ obj_PDF[11].length()+ obj_PDF[12].length()+ obj_PDF[13].length())+ " 00000 n \n"+ // 14 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length()+ obj_PDF[1].length()+ obj_PDF[3].length()+ obj_PDF[9].length()+ obj_PDF[10].length()+ obj_PDF[11].length()+ obj_PDF[12].length()+ obj_PDF[13].length()+ obj_PDF[14].length())+ " 00000 n \n"+ // 15 addLeadZeros(head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length()+ obj_PDF[1].length()+ obj_PDF[3].length()+ obj_PDF[9].length()+ obj_PDF[10].length()+ obj_PDF[11].length()+ obj_PDF[12].length()+ obj_PDF[13].length()+ obj_PDF[14].length()+ obj_PDF[15].length())+ " 00000 n \n"); // 16 out.write("trailer\n"+ "<<\n"+ " /Size 16\n"+ " /Root 3 0 R\n"+ " /Info 1 0 R\n"+ ">>\n"+ "startxref\n"+ (head.length()+ obj_PDF[5].length()+ obj_PDF[6].length()+ obj_PDF[7].length()+ obj_PDF[8].length()+ fileLength + closeObject.length()+ obj_PDF[4].length()+ obj_PDF[2].length()+ obj_PDF[1].length()+ obj_PDF[3].length()+ obj_PDF[9].length()+ obj_PDF[10].length()+ obj_PDF[11].length()+ obj_PDF[12].length()+ obj_PDF[13].length()+ obj_PDF[14].length()+ obj_PDF[15].length()+ obj_PDF[16].length())+ "\n%%EOF"); } /** Called when exporting an Advanced Text primitive. @param x the x position of the beginning of the string to be written. @param y the y position of the beginning of the string to be written. @param sizex the x size of the font to be used. @param sizey the y size of the font to be used. @param fontname the font to be used. @param isBold true if the text should be written with a boldface font. @param isMirrored true if the text should be mirrored. @param isItalic true if the text should be written with an italic font. @param orientation angle of orientation (degrees). @param layer the layer that should be used. @param textT the text that should be written. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportAdvText (int x, int y, int sizex, int sizey, String fontname, boolean isBold, boolean isMirrored, boolean isItalic, int orientation, int layer, String textT) throws IOException { String text=textT; if ("".equals(text)) { return; } LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, .33); outt.write("BT\n"); int ys = (int)(sizex*12.0/7.0+.5); if("Courier".equals(fontname) || "Courier New".equals(fontname)) { if(isBold) { currentFont="/F2"; } else { currentFont="/F1"; } } else if("Times".equals(fontname) || "Times New Roman".equals(fontname) || "Times Roman".equals(fontname)) { if(isBold) { currentFont="/F4"; } else { currentFont="/F3"; } } else if("Helvetica".equals(fontname) || "Arial".equals(fontname)) { if(isBold) { currentFont="/F6"; } else { currentFont="/F5"; } } else if("Symbol".equals(fontname)) { if(isBold) { currentFont="/F8"; } else { currentFont="/F7"; } } else { fontWarning = true; userfont=fontname; currentFont="/F9"; } outt.write(currentFont+" "+ys+" Tf\n"); currentFontSize=(float)ys; outt.write("q\n"); outt.write(" 1 0 0 1 "+ Globals.roundTo(x)+" "+ Globals.roundTo(y)+ " cm\n"); textx=x; texty=y; if(orientation !=0) { double alpha=(isMirrored?orientation:-orientation)/180.0*Math.PI; outt.write(" "+Globals.roundTo(Math.cos(alpha))+" " + Globals.roundTo(Math.sin(alpha))+ " " + Globals.roundTo(-Math.sin(alpha))+ " "+Globals.roundTo(Math.cos(alpha))+" 0 0 cm\n"); } if(isMirrored) { outt.write(" -1 0 0 -1 0 0 cm\n"); } else { outt.write(" 1 0 0 -1 0 0 cm\n"); } double ratio; if(sizey/sizex == 10/7){ ratio = 1.0; } else { ratio=(double)sizey/(double)sizex*22.0/40.0; } outt.write(" 1 0 0 "+Globals.roundTo(ratio)+ " 0 "+ (-ys*ratio*0.8)+" cm\n"); dt.drawString(text,x,y); outt.write("Q\nET\n"); } /** Called when exporting a Bézier primitive. @param x1 the x position of the first point of the trace. @param y1 the y position of the first point of the trace. @param x2 the x position of the second point of the trace. @param y2 the y position of the second point of the trace. @param x3 the x position of the third point of the trace. @param y3 the y position of the third point of the trace. @param x4 the x position of the fourth point of the trace. @param y4 the y position of the fourth point of the trace. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportBezier (int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, strokeWidth); registerDash(dashStyle); if (arrowStart) { PointPr p=exportArrow(x1, y1, x2, y2, arrowLength, arrowHalfWidth, arrowStyle); // This fixes issue #172 // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if(arrowLength>0) { x1=(int)Math.round(p.x); y1=(int)Math.round(p.y); } } if (arrowEnd) { PointPr p=exportArrow(x4, y4, x3, y3, arrowLength, arrowHalfWidth, arrowStyle); // Fix #172 if(arrowLength>0) { x4=(int)Math.round(p.x); y4=(int)Math.round(p.y); } } outt.write(""+x1+" "+y1+" m \n"); outt.write(""+x2+" "+y2+" "+x3+" "+y3+" "+x4+" "+y4+" c S\n"); } /** Called when exporting a Connection primitive. @param x the x position of the position of the connection. @param y the y position of the position of the connection. @param layer the layer that should be used. @param nodeSize the size of the connection, in logical units. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportConnection (int x, int y, int layer, double nodeSize) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, .33); ellipse(x-nodeSize/2.0, y-nodeSize/2.0, x+nodeSize/2.0, y+nodeSize/2.0, true); } /** Called when exporting a Line primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportLine (double x1, double y1, double x2, double y2, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { double xstart=x1; double ystart=y1; double xend=x2; double yend=y2; LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, strokeWidth); registerDash(dashStyle); if (arrowStart) { PointPr p=exportArrow(x1, y1, x2, y2, arrowLength, arrowHalfWidth, arrowStyle); // This fixes issue #172 // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if(arrowLength>0) { xstart=p.x; ystart=p.y; } } if (arrowEnd) { PointPr p=exportArrow(x2, y2, x1, y1, arrowLength, arrowHalfWidth, arrowStyle); // Fix #172 if(arrowLength>0) { xend=p.x; yend=p.y; } } outt.write(" "+xstart+" "+ystart+" m "+ xend+" "+yend+" l S\n"); } /** Called when exporting a Macro call. This function can just return false, to indicate that the macro should be rendered by means of calling the other primitives. Please note that a macro does not have a reference layer, since it is defined by its components. @param x the x position of the position of the macro. @param y the y position of the position of the macro. @param isMirrored true if the macro is mirrored. @param orientation the macro orientation in degrees. @param macroName the macro name. @param macroDesc the macro description, in the FidoCad format. @param name the shown name. @param xn coordinate of the shown name. @param yn coordinate of the shown name. @param value the shown value. @param xv coordinate of the shown value. @param yv coordinate of the shown value. @param font the used font. @param fontSize the size of the font to be used. @param m the library. @throws IOException if a disaster happens, i.e. a file can not be accessed. @return false if the macro should be split into primitives or true if the export is handled entirely by this function. */ public boolean exportMacro(int x, int y, boolean isMirrored, int orientation, String macroName, String macroDesc, String name, int xn, int yn, String value, int xv, int yv, String font, int fontSize, Map m) throws IOException { // The macro will be expanded into primitives. return false; } /** Called when exporting an Oval primitive. Specify the bounding box. @param x1 the x position of the first corner @param y1 the y position of the first corner @param x2 the x position of the second corner @param y2 the y position of the second corner. @param isFilled it is true if the oval should be filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportOval(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, strokeWidth); registerDash(dashStyle); ellipse(x1,y1, x2, y2, isFilled); } /** Called when exporting a PCBLine primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param width the width ot the line. @param layer the layer that should be used. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPCBLine(int x1, int y1, int x2, int y2, int width, int layer) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, width); registerDash(0); outt.write(" "+x1+" "+y1+" m "+ x2+" "+y2+" l S\n"); } /** Called when exporting a PCBPad primitive. @param x the x position of the pad. @param y the y position of the pad. @param style the style of the pad (0: oval, 1: square, 2: rounded square). @param six the x size of the pad. @param siy the y size of the pad. @param indiam the hole internal diameter. @param layer the layer that should be used. @param onlyHole true if only the hole has to be exported. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPCBPad(int x, int y, int style, int six, int siy, int indiam, int layer, boolean onlyHole) throws IOException { double xdd; double ydd; LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, 0.33); // At first, draw the pad... if(!onlyHole) { switch (style) { case 2: // Rounded pad roundRect(x-six/2.0, y-siy/2.0, six, siy, 4, true); break; case 1: // Square pad xdd=(double)x-six/2.0; ydd=(double)y-siy/2.0; outt.write(""+xdd+" "+ydd+" m\n"); outt.write(""+(xdd+six)+" "+ydd+" l\n"); outt.write(""+(xdd+six)+" "+(ydd+siy)+" l\n"); outt.write(""+xdd+" "+(ydd+siy)+" l\n"); outt.write("B\n"); break; case 0: // Oval pad default: ellipse(x-six/2.0, y-siy/2.0, x+six/2.0, y+siy/2.0, true); outt.write("f\n"); break; } } // ... then, drill the hole! checkColorAndWidth(c.white(), .33); ellipse(x-indiam/2.0, y-indiam/2.0, x+indiam/2.0, y+indiam/2.0, true); outt.write("f\n"); } /** Called when exporting a Polygon primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPolygon(PointDouble[] vertices, int nVertices, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); if (nVertices<1) { return; } checkColorAndWidth(c, strokeWidth); registerDash(dashStyle); outt.write(" "+vertices[0].x+" "+vertices[0].y+" m\n"); for (int i=1; i<nVertices; ++i) { outt.write(" "+vertices[i].x+" "+vertices[i].y+" l\n"); } if(isFilled) { outt.write(" f*\n"); } else { outt.write(" s\n"); } } /** Called when exporting a Curve primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param isClosed true if the curve is closed. @param layer the layer that should be used. @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @return false if the curve should be rendered using a polygon, true if it is handled by the function. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public boolean exportCurve(PointDouble[] vertices, int nVertices, boolean isFilled, boolean isClosed, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { return false; } /** Called when exporting a Rectangle primitive. @param x1 the x position of the first corner. @param y1 the y position of the first corner. @param x2 the x position of the second corner. @param y2 the y position of the second corner. @param isFilled it is true if the rectangle should be filled; @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportRectangle(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { LayerDesc l=(LayerDesc)layerV.get(layer); ColorInterface c=l.getColor(); checkColorAndWidth(c, strokeWidth); registerDash(dashStyle); outt.write(" "+x1+" "+y1+" m\n"); outt.write(" "+x2+" "+y1+" l\n"); outt.write(" "+x2+" "+y2+" l\n"); outt.write(" "+x1+" "+y2+" l\n"); if(isFilled) { outt.write("f\n"); } else { outt.write("s\n"); } } private void roundRect (double x1, double y1, double w, double h, double r, boolean filled) throws IOException { outt.write(""+ (x1+r) + " " +y1+" m\n"); outt.write(""+ (x1+w-r) + " " +y1+" l\n"); outt.write(""+ (x1+w) + " " +y1+" "+ (x1+w) + " " +(y1+r)+" y\n"); outt.write(""+ (x1+w) + " " +(y1+h-r)+" l\n"); outt.write(""+ (x1+w) + " " +(y1+h)+" "+ (x1+w-r) + " " +(y1+h)+" y\n"); outt.write(""+ (x1+r) + " " +(y1+h)+" l\n"); outt.write(""+ x1 + " " +(y1+h)+" "+ x1 + " " +(y1+h-r)+" y\n"); outt.write(""+ x1 + " " +(y1+r)+" l\n"); outt.write(""+ x1 + " " +y1+" "+ (x1+r) + " " +y1+" y \n"); outt.write(" "+(filled?"f\n":"s\n")); } /** TODO: I am sure that a better solution for drawing ellipses may be found. This code is pretty inefficient. */ private void ellipse(double x1, double y1, double x2, double y2, boolean filled) throws IOException { double cx = (x1+x2)/2.0; double cy = (y1+y2)/2.0; double rx = Math.abs(x2-x1)/2.0; double ry = Math.abs(y2-y1)/2.0; final int nMAX=32; double xC; double yC; double xD; double yD; double alpha; final double tt = 1.01; outt.write(" "+ Globals.roundTo(cx+rx)+" "+ Globals.roundTo(cy)+ " m\n"); for(int i=0; i<nMAX; ++i) { alpha = 2.0*Math.PI*(double)i/(double)nMAX; alpha += 2.0*Math.PI/(double)nMAX/3.0; alpha += 2.0*Math.PI/(double)nMAX/3.0; xC = cx + tt*rx * Math.cos(alpha); yC = cy + tt*ry * Math.sin(alpha); alpha += 2.0*Math.PI/(double)nMAX/3.0; xD = cx + rx * Math.cos(alpha); yD = cy + ry * Math.sin(alpha); outt.write(Globals.roundTo(xC)+" "+ Globals.roundTo(yC)+" "+ Globals.roundTo(xD)+" "+ Globals.roundTo(yD)+" y\n"); } outt.write(" "+(filled?"f\n":"s\n")); } private String addLeadZeros(long n) { String s=""+n; // simple and inefficient. while (s.length()<10) { s="0"+s; } return s; } private void checkColorAndWidth(ColorInterface c, double wl) throws IOException { if(!c.equals(actualColor)) { outt.write(" "+Globals.roundTo(c.getRed()/255.0)+" "+ Globals.roundTo(c.getGreen()/255.0)+ " " +Globals.roundTo(c.getBlue()/255.0)+ " rg\n"); outt.write(" "+Globals.roundTo(c.getRed()/255.0)+" "+ Globals.roundTo(c.getGreen()/255.0)+ " " +Globals.roundTo(c.getBlue()/255.0)+ " RG\n"); actualColor=c; } if(wl != actualWidth) { outt.write(" " +wl+" w\n"); actualWidth = wl; } } private void registerDash(int dashStyle) throws IOException { if(currentDash!=dashStyle ||currentPhase!=dashPhase) { currentDash=dashStyle; currentPhase=dashPhase; if(dashStyle==0) { outt.write("[] 0 d\n"); } else { outt.write(""+sDash[dashStyle]+" "+dashPhase+" d\n"); } } } /** Called when exporting an arrow. @param x position of the tip of the arrow. @param y position of the tip of the arrow. @param xc direction of the tip of the arrow. @param yc direction of the tip of the arrow. @param l length of the arrow. @param h width of the arrow. @param style style of the arrow. @return the coordinates of the base of the arrow. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public PointPr exportArrow(double x, double y, double xc, double yc, double l, double h, int style) throws IOException { double alpha; double x0; double y0; double x1; double y1; double x2; double y2; // At first we need the angle giving the direction of the arrow // a little bit of trigonometry :-) if (x==xc) { alpha = Math.PI/2.0+(y-yc<0.0?0.0:Math.PI); } else { alpha = Math.atan((double)(y-yc)/(double)(x-xc)); } alpha += x-xc>0.0?0.0:Math.PI; // Then, we calculate the points for the polygon x0 = x - l*Math.cos(alpha); y0 = y - l*Math.sin(alpha); x1 = x0 - h*Math.sin(alpha); y1 = y0 + h*Math.cos(alpha); x2 = x0 + h*Math.sin(alpha); y2 = y0 - h*Math.cos(alpha); outt.write(""+Globals.roundTo(x)+" " +Globals.roundTo(y)+ " m\n"); outt.write(""+Globals.roundTo(x1)+" "+Globals.roundTo(y1)+" l\n"); outt.write(""+Globals.roundTo(x2)+" "+Globals.roundTo(y2)+" l\n"); if ((style & Arrow.flagEmpty) == 0) { outt.write(" f*\n"); } else { outt.write(" s\n"); } if ((style & Arrow.flagLimiter) != 0) { double x3; double y3; double x4; double y4; x3 = x - h*Math.sin(alpha); y3 = y + h*Math.cos(alpha); x4 = x + h*Math.sin(alpha); y4 = y - h*Math.cos(alpha); outt.write(""+Globals.roundTo(x3)+" "+Globals.roundTo(y3)+" m\n"+ Globals.roundTo(x4)+" "+Globals.roundTo(y4)+" l s\n"); } return new PointPr(x0,y0); } // Functions required for the TextInterface. /** Get the font size. @return the font size. */ public double getFontSize() { return currentFontSize; } /** Set the font size. @param size the font size. */ public void setFontSize(double size) { currentFontSize=(float)size; try { outt.write(currentFont+" "+currentFontSize+" Tf\n"); } catch(IOException ee) { System.err.println("Can not write to file in PDF export."); } } /** Get the width of the given string with the current font. @param s the string to be used. @return the width of the string, in pixels. */ public int getStringWidth(String s) { return 0; } /** Draw a string on the current graphic context. @param str the string to be drawn. @param x the x coordinate of the starting point. @param y the y coordinate of the starting point. */ public void drawString(String str, int x, int y) { try { outt.write(" 1 0 0 1 "+ Globals.roundTo(textx-x)+ " "+ Globals.roundTo(texty-y)+ " cm\n"); texty=y; outt.write(" <"); int ch; for(int i=0; i<str.length();++i) { ch=(int)str.charAt(i); // Proceed to encode UTF-8 characters as much as possible. if(ch>127) { if(uncodeCharsNeeded.containsKey(ch)) { ch=uncodeCharsNeeded.get(ch); } else { ++unicodeCharIndex; if(unicodeCharIndex<256) { uncodeCharsNeeded.put(unicodeCharIndex,ch); ch=unicodeCharIndex; } else { System.err.println("Too many Unicode chars! "+ "The present version of the PDF export filter "+ "handles up to 128 different Unicode chars in "+ "one file."); } } } outt.write(Integer.toHexString(ch)); outt.write(" "); } outt.write("> Tj\n"); } catch(IOException ee) { System.err.println("Can not write to file in EPS export."); } } }
52,459
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExportEagle.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/ExportEagle.java
package net.sourceforge.fidocadj.export; import java.util.*; import java.io.*; import java.text.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.MacroDesc; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.PointDouble; /** Circuit export towards Cadsoft Eagle scripts. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class ExportEagle implements ExportInterface { private final FileWriter fstream; private BufferedWriter out; private DimensionG dim; private int oldtextsize; private String macroList; private String junctionList; static final double text_stretch = 0.73; static final String EagleFidoLib = "FidoCadJLIB"; static final String ExportFormatString = "####.####"; // Conversion between FidoCadJ units and Eagle units (1/10 inches) static double res=5e-2; /** Constructor @param f the File object in which the export should be done. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public ExportEagle (File f) throws IOException { macroList = ""; junctionList = ""; fstream = new FileWriter(f); } /** Set the multiplication factor to be used for the dashing. @param u the factor. */ public void setDashUnit(double u) { // Nothing particular to do here, dashing is not supported. } /** Set the "phase" in output units of the dashing style. For example, if a dash style is composed by a line followed by a space of equal size, a phase of 0 indicates that the dash starts with the line. @param p the phase, in output units. */ public void setDashPhase(float p) { // Nothing particular to do here, dashing is not supported. } /** Called at the beginning of the export phase. Ideally, in this routine there should be the code to write the header of the file on which the drawing should be exported. @param totalSize the size of the image. Useful to calculate for example the bounding box. @param la a vector describing the attributes of each layer. @param grid the grid size. This is useful when exporting to another drawing program having some kind of grid concept. You might use this value to synchronize FidoCadJ's grid with the one used by the target. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportStart(DimensionG totalSize, List<LayerDesc> la, int grid) throws IOException { dim=totalSize; out = new BufferedWriter(fstream); oldtextsize=-1; macroList = ""; junctionList = ""; // A basic configuration of an Eagle script out.write("# Created by FidoCadJ "+Globals.version+ " by Davide Bucci\n"); out.write("Set Wire_Bend 2; \n"); out.write("Grid inch "+een(grid*res)+";\n"); out.write("Change font fixed;\n"); out.write("Set auto_junction off;\n"); } /** Called at the end of the export phase. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportEnd() throws IOException { out.write(macroList); out.write(junctionList); out.write("Window Fit; \n"); out.close(); } /** Called when exporting an Advanced Text primitive. @param x the x position of the beginning of the string to be written. @param y the y position of the beginning of the string to be written. @param sizex the x size of the font to be used. @param sizey the y size of the font to be used. @param fontname the font to be used. @param isBold true if the text should be written with a boldface font. @param isMirrored true if the text should be mirrored. @param isItalic true if the text should be written with an italic font. @param orientation angle of orientation (degrees). @param layer the layer that should be used. @param text the text that should be written. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportAdvText (int x, int y, int sizex, int sizey, String fontname, boolean isBold, boolean isMirrored, boolean isItalic, int orientation, int layer, String text) throws IOException { String mirror=""; if(isMirrored) { mirror="M"; } if(oldtextsize!=sizey) { out.write("Change size "+sizey*res*text_stretch+"\n"); } oldtextsize=sizey; out.write("Text "+text+" "+mirror+"R"+(-orientation)+" ("+een(x*res)+ " "+een((dim.height-y)*res)+");\n"); } /** Called when exporting a Bézier primitive. @param x1 the x position of the first point of the trace. @param y1 the y position of the first point of the trace. @param x2 the x position of the second point of the trace. @param y2 the y position of the second point of the trace. @param x3 the x position of the third point of the trace. @param y3 the y position of the third point of the trace. @param x4 the x position of the fourth point of the trace. @param y4 the y position of the fourth point of the trace. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if. the file in which the output is being done is not accessible. */ public void exportBezier (int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { out.write("# Bézier export not implemented yet\n"); } /** Called when exporting a Connection primitive. @param x the x position of the position of the connection. @param y the y position of the position of the connection. @param layer the layer that should be used. @param size specify the size of the junction. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportConnection (int x, int y, int layer, double size) throws IOException { junctionList += "Junction ("+een(x*res)+" " +een((dim.height-y)*res)+");\n"; } /** Called when exporting a Line primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if. the file in which the output is being done is not accessible. */ public void exportLine (double x1, double y1, double x2, double y2, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { out.write("Net ("+een(x1*res)+" "+een((dim.height-y1)*res)+") ("+ een(x2*res)+" "+een((dim.height-y2)*res)+");\n"); } /** Called when exporting a Macro call. This function can just return false, to indicate that the macro should be rendered by means of calling the other primitives. Please note that a macro does not have a reference layer, since it is defined by its components. @param x the x position of the position of the macro @param y the y position of the position of the macro @param isMirrored true if the macro is mirrored @param orientation the macro orientation in degrees @param macroName the macro name @param macroDesc the macro description, in the FidoCad format @param tname the name shown @param xn coordinate of the name shown @param yn coordinate of the name shown @param value the shown value @param xv coordinate of the value shown @param yv coordinate of the value shown @param font the used font @param fontSize the size of the font to be used. @param m the library. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. @return false if the macro has to be expanded into primitives. True if its export has been treated by the function. */ public boolean exportMacro(int x, int y, boolean isMirrored, int orientation, String macroName, String macroDesc, String tname, int xn, int yn, String value, int xv, int yv, String font, int fontSize, Map<String, MacroDesc> m) throws IOException { String mirror =""; if (isMirrored) { mirror = "M"; } // The component name should not contain spaces. Substitute with // the underline character. Map<String, String> subst = new HashMap<String, String>(); subst.put(" ","_"); String name=Globals.substituteBizarreChars(tname, subst); macroList += "Add "+ macroName+"@"+EagleFidoLib+ " "+name+" "+mirror+"R" +(-orientation)+" ("+een(x*res)+" "+een((dim.height-y)*res)+");\n"; macroList +="Value "+name+" "+value+";\n"; // The macro will NOT be expanded into primitives. return true; } /** Called when exporting an Oval primitive. Specify the bounding box. @param x1 the x position of the first corner. @param y1 the y position of the first corner. @param x2 the x position of the second corner. @param y2 the y position of the second corner. @param isFilled it is true if the oval should be filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportOval(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { out.write("# Circle export not fully implemented\n"); out.write("Circle ("+een(x1*res)+" "+een((dim.height-y1)*res)+") (" +een((x2-x1)*res)+ " "+een((y2-y1)*res)+");"); } /** Called when exporting a PCBLine primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param width the width ot the line. @param layer the layer that should be used. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportPCBLine(int x1, int y1, int x2, int y2, int width, int layer) throws IOException { out.write("# PCBLine export not implemented yet\n"); } /** Called when exporting a PCBPad primitive. @param x the x position of the pad. @param y the y position of the pad. @param style the style of the pad (0: oval, 1: square, 2: rounded square). @param six the x size of the pad. @param siy the y size of the pad. @param indiam the hole internal diameter. @param layer the layer that should be used. @param onlyHole true if only the hole has to be exported. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportPCBPad(int x, int y, int style, int six, int siy, int indiam, int layer, boolean onlyHole) throws IOException { // At first, draw the pad... if(!onlyHole) { switch (style) { case 1: // Square pad break; case 2: // Rounded pad break; case 0: // Oval pad default: break; } } // ... then, drill the hole! out.write("# PCBpad export not implemented yet\n"); } /** Called when exporting a Polygon primitive @param vertices array containing the position of each vertex @param nVertices number of vertices @param isFilled true if the polygon is filled @param layer the layer that should be used @param dashStyle dashing style @param strokeWidth the width of the pen to be used when drawing @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportPolygon(PointDouble[] vertices, int nVertices, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { out.write("# Polygon export not implemented yet\n"); } /** Called when exporting a Rectangle primitive. @param x1 the x position of the first corner @param y1 the y position of the first corner @param x2 the x position of the second corner @param y2 the y position of the second corner @param isFilled it is true if the rectangle should be filled @param layer the layer that should be used @param dashStyle dashing style @param strokeWidth the width of the pen to be used when drawing @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportRectangle(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { out.write("Layer 94;\n"); if(isFilled) { out.write("Rect ("+een(x1*res)+" "+een((dim.height-y1)*res)+ ") ("+een(x2*res)+" "+een((dim.height-y2)*res)+");\n"); } else { out.write("Set Wire_Bend 0;\n"); out.write("Wire ("+een(x1*res)+" "+een((dim.height-y1)*res)+") ("+ een(x2*res)+" "+een((dim.height-y2)*res)+");\n"); out.write("Wire ("+een(x2*res)+" "+een((dim.height-y2)*res)+") ("+ een(x1*res)+" "+een((dim.height-y1)*res)+");\n"); out.write("Set Wire_Bend 2;\n"); } out.write("Layer 91;\n"); } /** Called when exporting a Curve primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param isClosed true if the curve is closed. @param layer the layer that should be used. @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @return false if the curve should be rendered using a polygon, true if it is handled by the function. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public boolean exportCurve(PointDouble[] vertices, int nVertices, boolean isFilled, boolean isClosed, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { return false; } /** Called when exporting an arrow. @param x position of the tip of the arrow. @param y position of the tip of the arrow. @param xc direction of the tip of the arrow. @param yc direction of the tip of the arrow. @param l length of the arrow. @param h width of the arrow. @param style style of the arrow. @return always (0,0). @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public PointPr exportArrow(double x, double y, double xc, double yc, double l, double h, int style) throws IOException { // Does nothing, since it will not be useful here. return new PointPr(); } /** Export a number: truncate it to four decimals */ private String een(double n) { // Force the Java system to use ALWAYS the dot as a decimal separator, // regardless the locale settings (in Italy and France, the // decimal separator is the comma). DecimalFormatSymbols separators = new DecimalFormatSymbols(); separators.setDecimalSeparator('.'); DecimalFormat exportFormat = new DecimalFormat(ExportFormatString, separators); return exportFormat.format(n); } }
20,193
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExportGraphic.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/ExportGraphic.java
package net.sourceforge.fidocadj.export; import java.io.*; import java.awt.*; import java.awt.image.*; import java.util.*; import javax.imageio.*; import net.sourceforge.fidocadj.circuit.controllers.SelectionActions; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.circuit.views.Export; import net.sourceforge.fidocadj.circuit.views.Drawing; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.DrawingSize; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.swing.Graphics2DSwing; import net.sourceforge.fidocadj.graphic.swing.ColorSwing; import net.sourceforge.fidocadj.graphic.nil.GraphicsNull; /** ExportGraphic.java Handle graphic export of a FidoCadJ file This class should be used to export the circuit under different graphic formats. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class ExportGraphic { private ExportGraphic() { // Nothing to do. } /** Exports the circuit contained in circ using the specified parsing class. @param file the file name of the graphic file which will be created. @param pp the parsing schematics class which should be used (libraries). @param format the graphic format which should be used {png|jpg}. @param unitPerPixel the number of unit for each graphic pixel. @param antiAlias specify whether the anti alias option should be on. @param blackWhite specify that the export should be done in B/W. @param ext activate FidoCadJ extensions when exporting @param shiftMin shift the exported image at the origin. @param splitLayers write each layer on a separate output file. @throws IOException if the file can not be created or an error occurs. */ public static void export(File file, DrawingModel pp, String format, double unitPerPixel, boolean antiAlias, boolean blackWhite, boolean ext, boolean shiftMin, boolean splitLayers) throws IOException { exportSizeP(file, pp, format, 0, 0, unitPerPixel, false, antiAlias, blackWhite, ext, shiftMin, splitLayers); } /** Exports the circuit contained in circ using the specified parsing class. @param file the file name of the graphic file which will be created. @param pp the parsing schematics class which should be used (libraries). @param format the graphic format which should be used {png|jpg}. @param width the image width in pixels (raster images only) @param height the image heigth in pixels (raster images only) @param antiAlias specify whether the anti alias option should be on. @param blackWhite specify that the export should be done in B/W. @param ext activate FidoCadJ extensions when exporting @param shiftMin shift the exported image at the origin. @param splitLayers split each layer into a different output file. @throws IOException if an error occurs. */ public static void exportSize(File file, DrawingModel pp, String format, int width, int height, boolean antiAlias, boolean blackWhite, boolean ext, boolean shiftMin, boolean splitLayers) throws IOException { exportSizeP(file, pp, format, width, height, 1, true, antiAlias, blackWhite, ext, shiftMin, splitLayers); } /** Exports the circuit contained in circ using the specified parsing class. @param file the file name of the graphic file which will be created. @param pp the parsing schematics class which should be used (libraries). @param format the graphic format which should be used {png|jpg}. @param unitperpixel the number of unit for each graphic pixel. @param width the image width in pixels (raster images only) @param heith the image heigth in pixels (raster images only) @param setSize if true, calculate resolution from size. If false, it does the opposite strategy. @param antiAlias specify whether the anti alias option should be on. @param blackWhite specify that the export should be done in B/W. @param ext activate FidoCadJ extensions when exporting. @param shiftMin shift the exported image at the origin. @param splitLayers if true, split layers into different files. @throws IOException if an error occurs. */ private static void exportSizeP(File file, DrawingModel pp, String format, int widthT, int heightT, double unitPerPixelT, boolean setSize, boolean antiAlias, boolean blackWhite, boolean ext, boolean shiftMin, boolean splitLayers) throws IOException { int width=widthT; int height=heightT; double unitPerPixel=unitPerPixelT; // obtain drawing size MapCoordinates m=new MapCoordinates(); // This solves bug #3299281 new SelectionActions(pp).setSelectionAll(false); PointG org=new PointG(0,0); DimensionG d = DrawingSize.getImageSize(pp, 1,true,org); if (setSize) { // In this case, the image size is set and so we need to calculate // the correct zoom factor in order to fit the drawing in the // specified area. d.width+=Export.exportBorder; d.height+=Export.exportBorder; unitPerPixel = Math.min((double)width/(double)d.width, (double)height/(double)d.height); } else { // In this situation, we do have to calculate the size from the // specified resolution. width=(int)((d.width+Export.exportBorder)*unitPerPixel); height=(int)((d.height+Export.exportBorder)*unitPerPixel); } org.x *=unitPerPixel; org.y *=unitPerPixel; org.x -= Export.exportBorder*unitPerPixel/2.0; org.y -= Export.exportBorder*unitPerPixel/2.0; java.util.List<LayerDesc> ol=pp.getLayers(); BufferedImage bufferedImage; // To print in black and white, we only need to create an array layer // in which all colours will be black. if(blackWhite) { java.util.List<LayerDesc> v=new Vector<LayerDesc>(); for (int i=0; i<16;++i) { v.add(new LayerDesc((new ColorSwing()).black(), // NOPMD ((LayerDesc)ol.get(i)).getVisible(), "B/W",((LayerDesc)ol.get(i)).getAlpha())); } pp.setLayers(v); } // Center the drawing in the given space. m.setMagnitudes(unitPerPixel, unitPerPixel); if(shiftMin && !"pcb".equals(format)) {// don't alter geometry m.setXCenter(-org.x); // if exported to pcb-rnd m.setYCenter(-org.y); } if ("png".equals(format)||"jpg".equals(format)) { // Create a buffered image in which to draw /* To get an error, try to export this in png at 1200 dpi: [FIDOCAD] RP 25 15 11000 95000 2 */ try { bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // Create a graphics contents on the buffered image Graphics2D g2d = (Graphics2D)bufferedImage.createGraphics(); if(antiAlias) { g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } g2d.setColor(Color.white); g2d.fillRect(0,0, width, height); // Save bitmap Drawing drawingAgent = new Drawing(pp); Graphics2DSwing graphicSwing=new Graphics2DSwing(g2d); // This is important for taking into account the dashing size graphicSwing.setZoom(m.getXMagnitude()); drawingAgent.draw(graphicSwing,m); ImageIO.write(bufferedImage, format, file); // Graphics context no longer needed so dispose it g2d.dispose(); } finally { pp.setLayers(ol); } } else { exportVectorFormats(pp, format,file,m,ext,splitLayers); } pp.setLayers(ol); } /** Create a file name containing an index from a template. For example, if the input name is example.txt and the index is 5, the created name should be example_5.txt. If the input name does not contain an extension, the "_5" will be added to the name. @param name the template name. @param index the index. @return the new name containing the index separated by an underscore. */ private static String addIndexInFilename(String name, int index) { int dotpos=name.lastIndexOf('.'); if(dotpos<0) { return name+"_"+index; } return name.substring(0,dotpos)+"_"+index+"."+name.substring(dotpos+1); } private static ExportInterface createExportInterface(String format, File file, boolean ext) throws IOException { ExportInterface ei; if("eps".equals(format)) { ei = new ExportEPS(file); } else if("pgf".equals(format)) { ei = new ExportPGF(file); } else if("pdf".equals(format)) { ei = new ExportPDF(file, new GraphicsNull()); } else if("scr".equals(format)) { ei = new ExportEagle(file); } else if("pcb".equals(format)) { ei = new ExportPCBRND(file); } else if("fcd".equals(format)) { ExportFidoCad ef = new ExportFidoCad(file); ef.setSplitStandardMacros(false); ef.setExtensions(ext); ei=ef; } else if("fcda".equals(format)) { ExportFidoCad ef = new ExportFidoCad(file); ef.setSplitStandardMacros(true); ef.setExtensions(ext); ei=ef; } else if("svg".equals(format)) { ei = new ExportSVG(file, new GraphicsNull()); } else { throw new IOException("Wrong file format"); } return ei; } /** Export a file in a vector format. @param pp the model to be used. @param format the file format code. @param file the output file to be written. @param m the coordinate system to be used. @param splitLayer true if the export should separate the different layers into different files. */ private static void exportVectorFormats(DrawingModel pp, String format, File file, MapCoordinates m, boolean ext, boolean splitLayer) throws IOException { ExportInterface ei; System.out.println("SplitLayer: "+splitLayer); if(splitLayer) { for(int i=0; i<16;++i) { if(!pp.containsLayer(i)) { // Don't export empty layers. break; } // Create a new file and export the current layer. File layerFile=new File(addIndexInFilename(file.toString(),i)); ei=createExportInterface(format, layerFile, ext); Export e = new Export(pp); pp.setDrawOnlyLayer(-1); e.exportHeader(ei, m); pp.setDrawOnlyLayer(i); e.exportDrawing(ei, false, m); ei.exportEnd(); } pp.setDrawOnlyLayer(-1); } else { ei=createExportInterface(format, file,ext); Export e = new Export(pp); e.exportHeader(ei, m); e.exportDrawing(ei, false, m); ei.exportEnd(); } } }
13,818
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExportPCBRND.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/ExportPCBRND.java
package net.sourceforge.fidocadj.export; import java.util.*; import java.io.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.MacroDesc; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.PointDouble; /** Circuit export to gEDA PCB and gEDA pcb-rnd. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci Copyright 2017 Erich Heinzle </pre> @author Davide Bucci, Erich Heinzle */ public final class ExportPCBRND implements ExportInterface { private final FileWriter fstream; private BufferedWriter out; private static List<String> viaList = new ArrayList<String>(); private static List<String> pinList = new ArrayList<String>(); private static List<String> footprints = new ArrayList<String>(); private static List<String> fpList = new ArrayList<String>(); private static List<String> layerEls1 = new ArrayList<String>(); private static List<String> layerEls2 = new ArrayList<String>(); private static List<String> layerEls3 = new ArrayList<String>(); private static List<String> layerEls4 = new ArrayList<String>(); private static List<String> layerEls5 = new ArrayList<String>(); private static List<String> layerEls6 = new ArrayList<String>(); private static List<String> layerEls7 = new ArrayList<String>(); private static List<String> layerEls8 = new ArrayList<String>(); private static List<String> layerEls9 = new ArrayList<String>(); private static List<String> layerEls10 = new ArrayList<String>(); private static List<String> layerEls11 = new ArrayList<String>(); private static List<String> layerEls12 = new ArrayList<String>(); private static List<String> layerEls13 = new ArrayList<String>(); private static List<String> layerEls14 = new ArrayList<String>(); private static List<String> layerEls15 = new ArrayList<String>(); private static List<String> layerEls16 = new ArrayList<String>(); static final double text_stretch = 0.73; static final String EagleFidoLib = "FidoCadJLIB"; static final String ExportFormatString = "####.####"; // Conversion between FidoCadJ units and Eagle units (1/10 inches) //static double res=5e-2; // these variable are used with recursive calls to embed FPs String currentMacro = ""; int macroX = 0; int macroY = 0; long defaultClearance = 1000; // centimils long minExportedLineThickness = 1000; // centimils int bezierSegments = 11; // number of line elements per cubic bezier /** Constructor @param f the File object in which the export should be done. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public ExportPCBRND (File f) throws IOException { //macroList = ""; //junctionList = ""; fstream = new FileWriter(f); } /** Set the multiplication factor to be used for the dashing. @param u the factor. */ public void setDashUnit(double u) { // Nothing is implemented for the moment. } /** Set the "phase" in output units of the dashing style. For example, if a dash style is composed by a line followed by a space of equal size, a phase of 0 indicates that the dash starts with the line. @param p the phase, in output units. */ public void setDashPhase(float p) { // Nothing is implemented for the moment. } /** Called at the beginning of the export phase. Ideally, in this routine there should be the code to write the header of the file on which the drawing should be exported. @param totalSize the size of the image. Useful to calculate for example the bounding box. @param la a vector describing the attributes of each layer. @param grid the grid size. This is useful when exporting to another drawing program having some kind of grid concept. You might use this value to synchronize FidoCadJ's grid with the one used by the target. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportStart(DimensionG totalSize, List<LayerDesc> la, int grid) throws IOException { out = new BufferedWriter(fstream); // start with a gEDA PCB file header gEDALayoutHeader(); } /** Called at the end of the export phase. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportEnd() throws IOException { writeFootprints(); writeVias(); writePins(); writeLayers(); /* out.write(macroList); // <- footprints out.write(junctionList); */ out.close(); } /** Called when exporting an Advanced Text primitive. @param x the x position of the beginning of the string to be written. @param y the y position of the beginning of the string to be written. @param sizex the x size of the font to be used. @param sizey the y size of the font to be used. @param fontname the font to be used. @param isBold true if the text should be written with a boldface font. @param isMirrored true if the text should be mirrored. @param isItalic true if the text should be written with an italic font. @param orientation angle of orientation (degrees). @param layer the layer that should be used. @param text the text that should be written. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportAdvText (int x, int y, int sizex, int sizey, String fontname, boolean isBold, boolean isMirrored, boolean isItalic, int orientation, int layer, String text) throws IOException { String line = fidoTextToPCBText(x, y, text, sizey, orientation); pushElement(line, layer); // ignore mirroring for now //System.out.println("# text added on layer: " + layer); } /** Called when exporting a Bézier primitive. @param x1 the x position of the first point of the trace. @param y1 the y position of the first point of the trace. @param x2 the x position of the second point of the trace. @param y2 the y position of the second point of the trace. @param x3 the x position of the third point of the trace. @param y3 the y position of the third point of the trace. @param x4 the x position of the fourth point of the trace. @param y4 the y position of the fourth point of the trace. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if. the file in which the output is being done is not accessible. */ public void exportBezier (int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { PointDouble[] vertices = cubicBezierToVector(x1, y1, x2, y2, x3, y3, x4, y4, bezierSegments); String lines = fidoPolylineToPCBLines(vertices, vertices.length, strokeWidth); pushElement(lines, layer); //System.out.println("# bezier segment on layer: " + layer); } /** Called when exporting a Connection primitive. @param x the x position of the position of the connection. @param y the y position of the position of the connection. @param layer the layer that should be used. @param size specify the size of the junction. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportConnection (int x, int y, int layer, double size) throws IOException { //junctionList += "Junction ("+een(x*res)+" " // +een((dim.height-y)*res)+");\n"; } /** Called when exporting a Line primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if. the file in which the output is being done is not accessible. */ public void exportLine (double x1, double y1, double x2, double y2, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { String line = fidoLineToPCBLine(x1, y1, x2, y2, strokeWidth); pushElement(line, layer); } /** Called when exporting a Macro call. This function can just return false, to indicate that the macro should be rendered by means of calling the other primitives. Please note that a macro does not have a reference layer, since it is defined by its components. @param x the x position of the position of the macro @param y the y position of the position of the macro @param isMirrored true if the macro is mirrored @param orientation the macro orientation in degrees @param macroName the macro name @param macroDesc the macro description, in the FidoCad format @param tname the name shown @param xn coordinate of the name shown @param yn coordinate of the name shown @param value the shown value @param xv coordinate of the value shown @param yv coordinate of the value shown @param font the used font @param fontSize the size of the font to be used. @param m the library. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. @return false if the macro has to be expanded into primitives. True if its export has been treated by the function. */ public boolean exportMacro(int x, int y, boolean isMirrored, int orientation, String macroName, String macroDesc, String tname, int xn, int yn, String value, int xv, int yv, String font, int fontSize, Map<String, MacroDesc> m) throws IOException { currentMacro = "macroName=" + macroName // "-value=" + value // is empty + "-x=" + x + "-y="+ y + "-rot=" + orientation + "-mirror=" + isMirrored; // + "-desc=" + macroDesc <- actual definition // System.out.println("# About to process: " + currentMacro); // System.out.println("# with xn: " + xn + ", yn: " + yn // + ", xv: " + xv + ", yv: " + yv); if (footprintUnique(currentMacro)) { // beware duplicate calls macroX = x; macroY = y; String header = gEDAElementHeader(currentMacro, macroX, macroY); String footprintBody = parseMacro(macroDesc); String footer = gEDAElementFooter(); if (!"".equals(footprintBody)) { pushFootprint(header + footprintBody + footer, macroName); } } return true; // The macro WILL NOT be expanded into primitives. /* String mirror =""; if (isMirrored) mirror = "M"; // The component name should not contain spaces. Substitute with // the underline character. Map<String, String> subst = new HashMap<String, String>(); subst.put(" ","_"); String name=Globals.substituteBizarreChars(tname, subst); */ } /** Called when exporting an Oval primitive. Specify the bounding box. @param x1 the x position of the first corner. @param y1 the y position of the first corner. @param x2 the x position of the second corner. @param y2 the y position of the second corner. @param isFilled it is true if the oval should be filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportOval(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { int dx = x2 - x1; int dy = y2 - y1; double midx = ((double)x1 + (double)x2)/2.0; double midy = ((double)y1 + (double)y2)/2.0; String ellipse = ""; if (dx < 0) { dx = -dx; } if (dy < 0) { dy = -dy; } if (dx == dy) { // a perfect circle ellipse = fidoArcToPCBArc(midx, midy, dx, strokeWidth, isFilled); } else { // is an ellipse int minSegments = 22; double arcFrac = 2*Math.PI/minSegments; double theta = 0.0; PointDouble[] vertices = new PointDouble[minSegments + 1]; PointDouble startVertex = new PointDouble(); startVertex.x = midx + dx/2.0; // int to double, start at RHS startVertex.y = midy; vertices[0] = startVertex; PointDouble endVertex = new PointDouble(); endVertex.x = vertices[0].x; // int to double endVertex.y = vertices[0].y; vertices[minSegments] = endVertex; for (int t = 1; t < minSegments; t++) { theta += arcFrac; PointDouble latestVertex = new PointDouble(); latestVertex.x += midx + Math.cos(theta)*dx/2; latestVertex.y += midy + Math.sin(theta)*dy/2; vertices[t] = latestVertex; } ellipse = fidoPolyToPCBPoly(vertices, minSegments, strokeWidth, isFilled); } pushElement(ellipse, layer); //System.out.println("# circle/ellipse on layer: " + layer); } /** Called when exporting a PCBLine primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param width the width ot the line. @param layer the layer that should be used. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportPCBLine(int x1, int y1, int x2, int y2, int width, int layer) throws IOException { String line = ""; line = fidoLineToPCBLine(x1, y1, x2, y2, width); pushElement(line, layer); //System.out.println(line + "# layer: " + layer); } /** Called when exporting a PCBPad primitive. @param x the x position of the pad. @param y the y position of the pad. @param style the style of the pad (0: oval, 1: square, 2: rounded square). @param six the x size of the pad. @param siy the y size of the pad. @param indiam the hole internal diameter. @param layer the layer that should be used. @param onlyHole true if only the hole has to be exported. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportPCBPad(int x, int y, int style, int six, int siy, int indiam, int layer, boolean onlyHole) throws IOException { String newPad = ""; int maxDim = six; if (siy > six) { maxDim = siy; // see which dimension is larger } /* Pin[X Y Thickness Clearance Mask Drill Name Number SFlags]*/ if (onlyHole) { newPad = "\tVia[" + coordToPCB(x) + " " + coordToPCB(y) + " " + coordToPCB(maxDim) + " " // annulus outer + (coordToPCB(maxDim)+100) + " " // Cu clearance + (coordToPCB(maxDim)+100) + " " // mask + coordToPCB(indiam) + " " // drill + "\"\" \"hole\"]\n"; // hole flag } else { switch (style) { case 1: // Square pad newPad = "\tVia[" + coordToPCB(x) + " " + coordToPCB(y) + " " + coordToPCB(maxDim) + " " // annulus outer + (coordToPCB(maxDim)+100) + " " // Cu clearance + (coordToPCB(maxDim)+100) + " " // mask + coordToPCB(indiam) + " " // drill + "\"\" \"square\"]\n"; // square flag break; case 2: // Rounded pad newPad = "\tVia[" + coordToPCB(x) + " " + coordToPCB(y) + " " + coordToPCB(maxDim) + " " // annulus outer + (coordToPCB(maxDim)+100) + " " // Cu clearance + (coordToPCB(maxDim)+100) + " " // mask + coordToPCB(indiam) + " " // drill + "\"\" \"square,shape(17)\"]\n";// octagon break; case 0: // round pin newPad = "\tVia[" + coordToPCB(x) + " " + coordToPCB(y) + " " + coordToPCB(maxDim) + " " // annulus outer + (coordToPCB(maxDim)+100) + " "// Cu clearance + (coordToPCB(maxDim)+100) + " "// mask + coordToPCB(indiam) + " " // drill + "\"\" \"\"]\n"; // no flag break; default: break; } out.write(newPad); // ... then, drill the hole! out.write("# Oval and rect pad export approximated\n"); } } /** Called when exporting a Polygon primitive @param vertices array containing the position of each vertex @param nVertices number of vertices @param isFilled true if the polygon is filled @param layer the layer that should be used @param dashStyle dashing style @param strokeWidth the width of the pen to be used when drawing @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportPolygon(PointDouble[] vertices, int nVertices, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { String poly = fidoPolyToPCBPoly(vertices, nVertices, strokeWidth, isFilled); pushElement(poly, layer); } /** Called when exporting a Rectangle primitive. @param x1 the x position of the first corner @param y1 the y position of the first corner @param x2 the x position of the second corner @param y2 the y position of the second corner @param isFilled it is true if the rectangle should be filled @param layer the layer that should be used @param dashStyle dashing style @param strokeWidth the width of the pen to be used when drawing @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public void exportRectangle(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { String newRect = ""; if (isFilled) { // export a solid polygon newRect = fidoRectToPCBPoly(x1, y1, x2, y2); } else { // just export the four bounding lines newRect = fidoRectToPCBLines(x1, y1, x2, y2, strokeWidth); } pushElement(newRect, layer); } /** Called when exporting a Curve primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param isClosed true if the curve is closed. @param layer the layer that should be used. @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @return false if the curve should be rendered using a polygon, true if it is handled by the function. @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public boolean exportCurve(PointDouble[] vertices, int nVertices, boolean isFilled, boolean isClosed, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { if (nVertices == 0) { // here we avoid null pointer dereferences System.out.println("Ignoring empty cubic spline definition."); return true; } else if (nVertices == 2) { // simplify as a simple line String line = ""; line = fidoLineToPCBLine(vertices[0].x, vertices[0].y, vertices[1].x, vertices[1].y, strokeWidth); pushElement(line, layer); return true; } else { // let Export.java break it up into segments return false; } } /** Called when exporting an arrow. @param x position of the tip of the arrow. @param y position of the tip of the arrow. @param xc direction of the tip of the arrow. @param yc direction of the tip of the arrow. @param l length of the arrow. @param h width of the arrow. @param style style of the arrow. @return always (0,0). @throws IOException when things goes horribly wrong, for example if the file in which the output is being done is not accessible. */ public PointPr exportArrow(double x, double y, double xc, double yc, double l, double h, int style) throws IOException { // Does nothing, since it will not be useful here. return new PointPr(); } ////////////////////// Custom routines below ///////////////////// private void gEDALayoutHeader() throws IOException { out.write("# release: pcb 20110918\n\n"); out.write("# To read pcb files, the pcb version " + "(or the git source date) must be >=" + " the file version\n"); out.write("FileVersion[20070407]\n\n"); out.write("PCB[\"\" 600000 500000]\n\n"); out.write("Grid[500.0 0 0 1]\n"); out.write("Cursor[2500 62500 0.000000]\n"); out.write("PolyArea[3100.006200]\n"); out.write("Thermal[0.500000]\n"); out.write("DRC[1200 900 1000 700 1500 1000]\n"); out.write("Flags(\"nameonpcb,clearnew,snappin\")\n"); out.write("Groups(\"1,s:2,c:3:4:5:6:7:8:9:10:11:12:13:14\")\n"); out.write("Styles[\"Signal,1000,7874,3150,2000:Power,2000,8661" + ",3937,2000:Fat,8000,13780,4724,2500:Sig-tight," + "1000,6400,3150,1200\"]\n\n"); out.write("Attribute(\"PCB::grid::unit\" \"mil\")\n"); out.write("# Created by FidoCadJ "+Globals.version+ " by Erich Heinzle, based on code by Davide Bucci.\n"); } private String gEDAElementHeader(String macroName, int macroX, int macroY) { return "Element[\"\" \"" + macroName + "\" " + "\"\" \"\" " + coordToPCB(macroX) + " " + coordToPCB(macroY) + " " + "-2500 -1500 0 100 \"\"]\n(\n"; } private int sToInt(String val) { return Integer.parseInt(val); } private String parseMacro(String macroDesc) throws IOException { BufferedReader buffer =null; List<String> macroDefs = new ArrayList<String>(); int padCounter = 1; String line; String [] tokens; String footprintElements = ""; try { buffer = new BufferedReader(new StringReader(macroDesc)); while ((line = buffer.readLine()) != null) { macroDefs.add(line); } for (String macro : macroDefs) { tokens = macro.split(" "); if (tokens.length >= 5) { if ("LI".equals(tokens[0]) && "3".equals(tokens[5])) { // silk footprintElements = footprintElements + fidoLineToPCBLineElement(sToInt(tokens[1]) - 100, sToInt(tokens[2]) - 100, sToInt(tokens[3]) - 100, sToInt(tokens[4]) - 100, 2); } else if ("EP".equals(tokens[0]) // filled && "3".equals(tokens[5])) { // silk int dx = sToInt(tokens[3])-sToInt(tokens[1]); if (dx < 0) { dx = -dx; } int dy = sToInt(tokens[4])-sToInt(tokens[2]); if (dy < 0) { dy = -dy; } if (dx == dy) { // circle; ignore ellipses for now double midx = (sToInt(tokens[3])+sToInt(tokens[1]))/2; double midy = (sToInt(tokens[4])+sToInt(tokens[2]))/2; // System.out.println("Filled FP ellipse"); footprintElements = footprintElements + fidoArcToPCBArcElement(midx-100, midy-100, dx, 2, true); } } else if ("EV".equals(tokens[0]) // not filled && "3".equals(tokens[5])) { // silk int dx = sToInt(tokens[3])-sToInt(tokens[1]); if (dx < 0) { dx = -dx; } int dy = sToInt(tokens[4])-sToInt(tokens[2]); if (dy < 0) { dy = -dy; } if (dx == dy) { // circle; ignore ellipses for now double midx = (sToInt(tokens[3])+sToInt(tokens[1]))/2; double midy = (sToInt(tokens[4])+sToInt(tokens[2]))/2; System.out.println("Processing empty FP ellipse"); footprintElements = footprintElements + fidoArcToPCBArcElement(midx - 100, midy - 100, dx, 2, false); } } else if ("RP".equals(tokens[0]) //filled rectangle pad && !"0".equals(tokens[5])) { // not circuit footprintElements = footprintElements + fidoRectToPCBPadElement(sToInt(tokens[1]) - 100, sToInt(tokens[2]) - 100, sToInt(tokens[3]) - 100, sToInt(tokens[4]) - 100, sToInt(tokens[5]), padCounter); padCounter++; } else if ("RV".equals(tokens[0]) // empty rectangle && "3".equals(tokens[5])) { // on silk footprintElements = footprintElements + fidoRectToPCBLineElements(sToInt(tokens[1]) - 100, sToInt(tokens[2]) - 100, sToInt(tokens[3]) - 100, sToInt(tokens[4]) - 100, sToInt(tokens[5])); } else if ("PA".equals(tokens[0])) { // pin footprintElements = footprintElements + fidoPadToPCBPinElement(sToInt(tokens[1]) - 100, sToInt(tokens[2]) - 100, sToInt(tokens[3]), sToInt(tokens[4]), sToInt(tokens[5]), sToInt(tokens[6]), //sToInt(tokens[7]), padCounter); padCounter++; } else if ("PV".equals(tokens[0])) { // empty polyline // silk int nVertices = 0; if (tokens.length%2 == 0) { // an even number nVertices = (tokens.length-2)/2; } //System.out.println("# nvertices: " + nVertices); PointDouble [] vertices = new PointDouble[nVertices]; for (int vertex = 0; vertex < 2*nVertices; vertex = vertex + 2) { PointDouble newV = new PointDouble(); newV.x = Double.parseDouble(tokens[vertex+1]) - 100; newV.y = Double.parseDouble(tokens[vertex+2]) - 100; vertices[vertex/2] = newV; } // NB number of line segments = vertices - 1 footprintElements = footprintElements + fidoPolylineToPCBLineElements(vertices, nVertices, 2); // 10 mil default } else if ("BE".equals(tokens[0]) // bezier && !"0".equals(tokens[9])) { // not circuit // System.out.println("# About to process FP bezier"); int x1 = sToInt(tokens[1]) - 100; int y1 = sToInt(tokens[2]) - 100; int x2 = sToInt(tokens[3]) - 100; int y2 = sToInt(tokens[4]) - 100; int x3 = sToInt(tokens[5]) - 100; int y3 = sToInt(tokens[6]) - 100; int x4 = sToInt(tokens[7]) - 100; int y4 = sToInt(tokens[8]) - 100; int nVertices = 10; PointDouble [] vertices = new PointDouble[nVertices]; vertices = cubicBezierToVector(x1, y1, x2, y2, x3, y3, x4, y4, nVertices-1); footprintElements = footprintElements + fidoPolylineToPCBLineElements(vertices, nVertices, 2); // 10 mil default for exported lines } else if ("TY".equals(tokens[0])) { // We don't support text in footprints in gEDA System.out.println("Text not supported."); } else { System.out.println("# Unsure what to do with: " + tokens[0] + " in macro."); } } } } finally { if (buffer!=null) { buffer.close(); } } return footprintElements; } private String gEDAElementFooter() { return ")\n"; } private PointDouble[] cubicBezierToVector(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int nsegments) { int sPCP1deltaX = x2 - x1; int sPCP1deltaY = y2 - y1; int cP1CP2deltaX = x3 - x2; int cP1CP2deltaY = y3 - y2; int cP2EPdeltaX = x4 - x3; int cP2EPdeltaY = y4 - y3; int minSegments = nsegments; double segFrac = 1.0/minSegments; double cP1dx = sPCP1deltaX*segFrac; double cP1dy = sPCP1deltaY*segFrac; double cP2dx = cP1CP2deltaX*segFrac; double cP2dy = cP1CP2deltaY*segFrac; double ePdx = cP2EPdeltaX*segFrac; double ePdy = cP2EPdeltaY*segFrac; double currentSeg1X = x1; double currentSeg1Y = y1; double currentSeg2X = x2; double currentSeg2Y = y2; double currentSeg3X = x3; double currentSeg3Y = y3; double virtSegX1 = 0.0; double virtSegY1 = 0.0; double virtSegX2 = 0.0; double virtSegY2 = 0.0; PointDouble[] vertices = new PointDouble[minSegments + 1]; PointDouble startVertex = new PointDouble(); startVertex.x = x1; // int to double startVertex.y = y1; vertices[0] = startVertex; PointDouble endVertex = new PointDouble(); endVertex.x = x4; // int to double endVertex.y = y4; vertices[minSegments] = endVertex; double tFrac = 0.0; for (int t = 1; t < minSegments; t++) { tFrac = 1.0*t/minSegments; currentSeg1X += cP1dx; currentSeg1Y += cP1dy; currentSeg2X += cP2dx; currentSeg2Y += cP2dy; currentSeg3X += ePdx; currentSeg3Y += ePdy; virtSegX1 = currentSeg1X + tFrac*(currentSeg2X - currentSeg1X); virtSegY1 = currentSeg1Y + tFrac*(currentSeg2Y - currentSeg1Y); virtSegX2 = currentSeg2X + tFrac*(currentSeg3X - currentSeg2X); virtSegY2 = currentSeg2Y + tFrac*(currentSeg3Y - currentSeg2Y); PointDouble latestVertex = new PointDouble(); latestVertex.x = virtSegX1 + tFrac*(virtSegX2 - virtSegX1); latestVertex.y = virtSegY1 + tFrac*(virtSegY2 - virtSegY1); vertices[t] = latestVertex; } return vertices; } private String fidoLineToPCBLine(double x1, double y1, double x2, double y2, double thickness) { long exportedThickness = coordToPCB(thickness); if (exportedThickness < minExportedLineThickness) { exportedThickness = 1000; } return "\tLine[" + coordToPCB(x1) + " " + coordToPCB(y1) + " " + coordToPCB(x2) + " " + coordToPCB(y2) + " " + exportedThickness + " " + defaultClearance + " \"clearline\"]\n"; } private String fidoLineToPCBLine(int x1, int y1, int x2, int y2, double thickness) { return fidoLineToPCBLine((double) x1, (double) y1, (double) x2, (double) y2, thickness); } /* private String fidoLineToPCBLine(PointDouble p1, PointDouble p2, double thickness) { return fidoLineToPCBLine(p1.x, p1.y, p2.x, p2.y, thickness); } private String fidoLineToPCBLineElement(int x1, int y1, int x2, int y2, int thickness) { return fidoLineToPCBLineElement((double) x1, (double) y1, (double) x2, (double) y2, (double) thickness); } */ private String fidoLineToPCBLineElement(double x1, double y1, double x2, double y2, double thickness) { long exportedThickness = coordToPCB(thickness); if (exportedThickness < minExportedLineThickness) { exportedThickness = 1000; } return "\tElementLine[" + coordToPCB(x1) + " " + coordToPCB(y1) + " " + coordToPCB(x2) + " " + coordToPCB(y2) + " " + exportedThickness + "]\n"; } /* private String fidoLineToPCBLineElement(PointDouble p1, PointDouble p2, int thickness) { return fidoLineToPCBLineElement(p1.x, p1.y, p2.x, p2.y, thickness); } */ private String fidoPolylineToPCBLineElements(PointDouble[] vertices, int nVertices, double strokeWidth) { StringBuffer newPolylines = new StringBuffer(); for (int v = 0; v < (nVertices - 1); v++) { newPolylines.append( fidoLineToPCBLineElement(vertices[v].x, vertices[v].y, vertices[v+1].x, vertices[v+1].y, strokeWidth)); } return newPolylines.toString(); } private String fidoRectToPCBLineElements(int x1, int y1, int x2, int y2, double strokeWidth) { return fidoRectToPCBLineElements((double) x1, (double) y1, (double) x2, (double) y2, strokeWidth); } private String fidoRectToPCBLineElements(double x1, double y1, double x2, double y2, double strokeWidth) { return fidoLineToPCBLineElement(x1, y1, x1, y2, strokeWidth) + fidoLineToPCBLineElement(x1, y2, x2, y2, strokeWidth) + fidoLineToPCBLineElement(x2, y2, x2, y1, strokeWidth) + fidoLineToPCBLineElement(x2, y1, x1, y1, strokeWidth); } private String fidoArcToPCBArc(double midx, double midy, int dx, double thickness, boolean filled) { String arc = ""; long exportedThickness = coordToPCB(thickness); if (exportedThickness < minExportedLineThickness) { exportedThickness = 1000; } if (filled) { arc = "\tArc[" + coordToPCB(midx) + " " + coordToPCB(midy) + " " + coordToPCB(dx)/4 + " " + coordToPCB(dx)/4 + " " + coordToPCB(dx)/2 + " " // thickness + defaultClearance + " " // clearance + "0 360 " // start and stop in degrees + "\"clearline\"]\n"; } else { arc = "\tArc[" + coordToPCB(midx) + " " + coordToPCB(midy) + " " + coordToPCB(dx)/2 + " " + coordToPCB(dx)/2 + " " // is a circle, so dx = dy + exportedThickness + " " // thickness + defaultClearance + " " // clearance + "0 360 " // start and stop in degrees + "\"clearline\"]\n"; } return arc; } /* private String fidoArcToPCBArc(PointDouble loc, int dx, double thickness, boolean fill) { return fidoArcToPCBArc(loc.x, loc.y, dx, thickness, fill); } */ private String fidoArcToPCBArcElement(double midx, double midy, int dx, double thickness, boolean filled) { String arc = ""; long exportedThickness = coordToPCB(thickness); if (exportedThickness < minExportedLineThickness) { exportedThickness = 1000; } if (filled) { arc = "\tElementArc[" + coordToPCB(midx) + " " + coordToPCB(midy) + " " + coordToPCB(dx)/4 + " " + coordToPCB(dx)/4 + " " + "0 360 " // start and stop in degrees + coordToPCB(dx)/2 // thickness + "]\n"; } else { arc = "\tElementArc[" + coordToPCB(midx) + " " + coordToPCB(midy) + " " + coordToPCB(dx)/2 + " " + coordToPCB(dx)/2 + " " // is a circle, so dx = dy + "0 360 " // start and stop in degrees + exportedThickness + " " // thickness + "]\n"; } return arc; } private String fidoRectToPCBPadElement(double x1, double y1, double x2, double y2, int layer, int padCounter) { int actualLayer = 2; // we'll assume SMD is on top surface for now double dx = x2-x1; double dy = y2-y1; double midx = dx/2.0 + x1; double midy = dy/2.0 + y1; double xX1 = 0; double yY1 = 0; double xX2 = 0; double yY2 = 0; if (dy < 0) { dy = -dy; } if (dx < 0) { dx = -dx; } double thickness = dy; if (dy > dx) { // taller than wide thickness = dx; xX1 = xX2 = midx; yY1 = midy + (dy - thickness)/2; yY2 = midy - (dy - thickness)/2; } else { yY1 = yY2 = midy; xX1 = midx + (dx - thickness)/2; xX2 = midx - (dx - thickness)/2; } String flags = "square"; if (actualLayer == 1) { flags = "square,onsolder"; } if (layer != 3) { // not silk return "\tPad[" // x1, y1, x2, y2 next + coordToPCB(xX1) + " " + coordToPCB(yY1) + " " + coordToPCB(xX2) + " " + coordToPCB(yY2) + " " + coordToPCB(thickness) + " " // thickness + defaultClearance + " " // then mask + (coordToPCB(thickness) + 600) + " " + "\"" + padCounter + "\" " + "\"" + padCounter + "\" " + "\"" + flags + "\"]\n"; //refdes, pinnum, flags } else { // silk rectangle/poly return "\tElementLine[" // x1, y1, x2, y2 thickness + coordToPCB(xX1) + " " + coordToPCB(yY1) + " " + coordToPCB(xX2) + " " + coordToPCB(yY2) + " " + coordToPCB(thickness) + "]\n"; } } private String fidoPadToPCBPinElement(double x1, double y1, double dx, double dy, int drill, int style, int padCounter) { double thickness = dx; if (dx > dy) { thickness = dy; } String flags = ""; String newPin = "\tPin[" // x1, y1, x2, y2 next + coordToPCB(x1) + " " + coordToPCB(y1) + " " + coordToPCB(thickness) + " " + defaultClearance + " " // then mask + (coordToPCB(thickness) + 600) + " " + coordToPCB(drill) + " " + "\"" + padCounter + "\" " + "\"" + padCounter + "\" " + "\"" + flags + "\"]\n"; //refdes, pinnum, flags if (style > 0) { // not round double xX1 = x1 - dx/2.0; double xX2 = x1 + dx/2.0; double yY1 = y1 - dy/2.0; double yY2 = y1 + dy/2.0; // we put a pad on the top and bottom layer newPin = newPin + fidoRectToPCBPadElement(xX1, yY1, xX2, yY2, 1, padCounter); newPin = newPin + fidoRectToPCBPadElement(xX1, yY1, xX2, yY2, 2, padCounter); // need to think about rounded corners } return newPin; } private String fidoPadToPCBPinElement(int x1, int y1, int dx, int dy, int drill, int style, int padCounter) { return fidoPadToPCBPinElement((double)x1, (double)y1, (double)dx, (double)dy, drill, style, padCounter); } private String fidoTextToPCBText(double x, double y, String text, int height, int orientation) { // overall text hight at 100% in gEDA is 5789 centimil // based on default_font 'm', 'l', p', 'q' glyphs // which includes default stroke thickness of 800 centimil // an additional scaling factor of 2 seems necessary long scaling = 2*100*coordToPCB(height)/5789; // in % of gEDA size int gEDAorientation = 0; // default if (orientation > 45 && orientation <= 135) { gEDAorientation = 1; } else if (orientation > 135 && orientation <= 225) { gEDAorientation = 2; } else if (orientation > 225 && orientation <= 315) { gEDAorientation = 3; } return "\tText[" + coordToPCB(x) + " " + coordToPCB(y) + " " + gEDAorientation + " " // orientation = 0,1,2,3 (times 90) + scaling + " " + "\"" + text + "\" \"clearline\"]\n"; } private String fidoTextToPCBText(int x, int y, String text, int height, int orientation) { return fidoTextToPCBText((double)x, (double)y, text, height, orientation); } private String fidoPolyToPCBPoly(PointDouble[] vertices, int nVertices, double strokeWidth, boolean fill) { String newPoly= ""; if (fill) { // solid poly newPoly = "\tPolygon(\"clearpoly\")\n" + "\t(\n" + "\t\t"; for (int v = 0; v < nVertices; v++) { if (v < (nVertices - 1)) { newPoly = newPoly + "[" + fidoCoordToPCB(vertices[v].x) + " " + fidoCoordToPCB(vertices[v].y) + "] "; } else { newPoly = newPoly + "[" + fidoCoordToPCB(vertices[v].x) + " " + fidoCoordToPCB(vertices[v].y) + "]\n" + ")\n"; } } } else { // not filled newPoly = fidoPolylineToPCBLines(vertices, nVertices, strokeWidth); newPoly = newPoly + fidoLineToPCBLine(vertices[nVertices-1].x, vertices[nVertices-1].y, vertices[0].x, vertices[0].y, strokeWidth); } return newPoly; } private String fidoPolylineToPCBLines(PointDouble[] vertices, int nVertices, double strokeWidth) { StringBuffer newPolylines = new StringBuffer(); for (int v = 0; v < (nVertices - 1); v++) { newPolylines.append( fidoLineToPCBLine(vertices[v].x, vertices[v].y, vertices[v+1].x, vertices[v+1].y, strokeWidth)); } return newPolylines.toString(); } private String fidoRectToPCBPoly(int x1, int y1, int x2, int y2) { return "\tPolygon(\"clearpoly\")\n" + "\t(\n" + "\t\t[" + coordToPCB(x1) + " " + fidoCoordToPCB(y1) + "] " + "[" + fidoCoordToPCB(x1) + " " + fidoCoordToPCB(y2) + "] " + "[" + fidoCoordToPCB(x2) + " " + fidoCoordToPCB(y2) + "] " + "[" + fidoCoordToPCB(x2) + " " + fidoCoordToPCB(y1) + "]\n" + "\t)\n"; } private String fidoRectToPCBLines(int x1, int y1, int x2, int y2, double strokeWidth) { return fidoLineToPCBLine(x1, y1, x1, y2, strokeWidth) + fidoLineToPCBLine(x1, y2, x2, y2, strokeWidth) + fidoLineToPCBLine(x2, y2, x2, y1, strokeWidth) + fidoLineToPCBLine(x2, y1, x1, y1, strokeWidth); } private String fidoPadToPCBVia(double x,double y,int dia,int drill)//NOPMD { return "#FidoPadToPCBVia stub\n"; } private long fidoCoordToPCB(double coord) { // coords are in multiples of 5mil = 127micron // if we export in centimil PCBcoord = 500x return (long)(500*coord); // are they using 25.4 microns?? } private long coordToPCB(int coord) { // coords are in multiples of 5mil = 127micron // if we export in centimil PCBcoord = 500x return (long)(500*coord); // are they using 25.4 microns?? } private long coordToPCB(double thickness) { // coords are in multiples of 5mil = 127micron // if we export in centimil PCBcoord = 500x return (long)(500*thickness); // are they using 25.4 microns?? } private boolean footprintUnique(String macroName) { boolean duplicate = false; for (String el : fpList) { if (el.equals(macroName)) { duplicate = true; } } return !duplicate; } private void pushFootprint(String fp, String macroName) { fpList.add(macroName); footprints.add(fp); } private void pushElement(String el, int layer) { switch (layer) { // here where we map FidoCadJ's stackup to gEDA pcb-rnd's // default 16 layer stack up, where last two are silk case 0: // we put circuit, if any on bottom silk, layer 15 layerEls15.add(el); break; case 1: layerEls1.add(el); // bottom copper on layer 1 break; case 2: layerEls2.add(el); // top copper on layer 2 break; case 3: layerEls16.add(el); // top silk goes to layer 15 break; case 4: layerEls3.add(el); // here starteth inner layers break; case 5: layerEls4.add(el); break; case 6: layerEls5.add(el); break; case 7: layerEls6.add(el); break; case 8: layerEls7.add(el); break; case 9: layerEls8.add(el); break; case 10: layerEls9.add(el); break; case 11: layerEls10.add(el); break; case 12: layerEls11.add(el); break; case 13: layerEls12.add(el); break; case 14: layerEls13.add(el); break; case 15: layerEls14.add(el); // here endeth inner layers break; default: break; } } private void writeElements(List<String> elements) throws IOException { for (String el : elements) { out.write(el); } elements.clear(); // in case we export again later; it's static. } private void writeFootprints() throws IOException { writeElements(footprints); } private void writeVias() throws IOException { writeElements(viaList); } private void writePins() throws IOException { writeElements(pinList); } private void writeLayers() throws IOException { for (int layer = 0; layer < 16; layer++) { switch (layer) { case 0: out.write("Layer(1 \"B.Cu\")\n(\n"); writeElements(layerEls1); out.write(")\n"); break; case 1: out.write("Layer(2 \"F.Cu\")\n(\n"); writeElements(layerEls2); out.write(")\n"); break; case 2: out.write("Layer(3 \"Inner1.Cu\")\n(\n"); writeElements(layerEls3); out.write(")\n"); break; case 3: out.write("Layer(4 \"Inner2.Cu\")\n(\n"); writeElements(layerEls4); out.write(")\n"); break; case 4: out.write("Layer(5 \"Inner3.Cu\")\n(\n"); writeElements(layerEls5); out.write(")\n"); break; case 5: out.write("Layer(6 \"Inner4.Cu\")\n(\n"); writeElements(layerEls6); out.write(")\n"); break; case 6: out.write("Layer(7 \"Inner5.Cu\")\n(\n"); writeElements(layerEls7); out.write(")\n"); break; case 7: out.write("Layer(8 \"Inner6.Cu\")\n(\n"); writeElements(layerEls8); out.write(")\n"); break; case 8: out.write("Layer(9 \"Inner7.Cu\")\n(\n"); writeElements(layerEls9); out.write(")\n"); break; case 9: out.write("Layer(10 \"Inner8.Cu\")\n(\n"); writeElements(layerEls10); out.write(")\n"); break; case 10: out.write("Layer(11 \"Inner9.Cu\")\n(\n"); writeElements(layerEls11); out.write(")\n"); break; case 11: out.write("Layer(12 \"Inner10.Cu\")\n(\n"); writeElements(layerEls12); out.write(")\n"); break; case 12: out.write("Layer(13 \"Inner11.Cu\")\n(\n"); writeElements(layerEls13); out.write(")\n"); break; case 13: out.write("Layer(14 \"Inner12.Cu\")\n(\n"); writeElements(layerEls14); out.write(")\n"); break; case 14: out.write("Layer(15 \"B.SilkS\")\n(\n"); writeElements(layerEls15); out.write(")\n"); break; case 15: out.write("Layer(16 \"F.SilkS\")\n(\n"); writeElements(layerEls16); out.write(")\n"); break; default: System.out.println("Unknown layer number for layer out: " + layer); break; } } } }
60,707
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PointPr.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/PointPr.java
package net.sourceforge.fidocadj.export; /** A simple point featuring double-precision coordinates <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2020 by Davide Bucci </pre> @author Davide Bucci */ public class PointPr { public double x; public double y; /** Standard constructor, yielding a (0,0) coordinate. */ public PointPr() { x=0;y=0; } /** Constructor, yielding a generic coordinate. @param xx the x coordinate. @param yy the y coordinate. */ public PointPr(double xx, double yy) { x=xx;y=yy; } }
1,293
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExportFidoCad.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/export/ExportFidoCad.java
package net.sourceforge.fidocadj.export; import java.util.*; import java.io.*; import net.sourceforge.fidocadj.circuit.controllers.ParserActions; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.primitives.MacroDesc; import net.sourceforge.fidocadj.primitives.PrimitiveAdvText; import net.sourceforge.fidocadj.primitives.PrimitiveBezier; import net.sourceforge.fidocadj.primitives.PrimitiveConnection; import net.sourceforge.fidocadj.primitives.PrimitiveLine; import net.sourceforge.fidocadj.primitives.PrimitiveMacro; import net.sourceforge.fidocadj.primitives.PrimitiveOval; import net.sourceforge.fidocadj.primitives.PrimitivePCBLine; import net.sourceforge.fidocadj.primitives.PrimitivePCBPad; import net.sourceforge.fidocadj.primitives.PrimitivePolygon; import net.sourceforge.fidocadj.primitives.PrimitiveComplexCurve; import net.sourceforge.fidocadj.primitives.PrimitiveRectangle; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.PointDouble; /** Export towards FidoCAD (!) No pun intended :-) This is useful because we can split macros very easily. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class ExportFidoCad implements ExportInterface { private final BufferedWriter out; private final OutputStreamWriter fstream; private List<LayerDesc> layerV; private boolean extensions; // use FidoCadJ extensions private boolean splitStandardMacros; // Split also the standard macros private String textFont; private int textFontSize; /** Set the multiplication factor to be used for the dashing. @param u the factor. */ public void setDashUnit(double u) { // Nothing special to do here. } /** Set the "phase" in output units of the dashing style. For example, if a dash style is composed by a line followed by a space of equal size, a phase of 0 indicates that the dash starts with the line. @param p the phase, in output units. */ public void setDashPhase(float p) { // Nothing special to do here. } /** Define the macro font to be used for the export. @param f the font name @param size the vertical size in logical units. */ public void setMacroFont(String f, int size) { textFont = f; textFontSize = size; } /** Define wether standard macros should be split or not. @param s true if the nonstandard macros should be split. */ public void setSplitStandardMacros(boolean s) { splitStandardMacros = s; } /** double to integer conversion. In some cases, some processing might be applied. @param double l the value to convert. */ private int cLe(double l) { return (int)l; } /** Constructor @param f the File object in which the export should be done. @throws IOException if a disaster happens, i.e. a file can not be created. */ public ExportFidoCad (File f) throws IOException { extensions = true; splitStandardMacros=false; textFont=Globals.defaultTextFont; textFontSize=3; fstream = new OutputStreamWriter( new FileOutputStream(f), Globals.encoding); out = new BufferedWriter(fstream); } /** Specify whether the FidoCadJ extensions should be taken into account. @param e true if the FidoCadJ extensions to the original and very old FidoCAD format should be active. */ public void setExtensions(boolean e) { extensions=e; } /** Called at the beginning of the export phase. Ideally, in this routine there should be the code to write the header of the file on which the drawing should be exported. @param totalSize the size of the image. Useful to calculate for example the bounding box. @param la a vector describing the attributes of each layer. @param grid the grid size. This is useful when exporting to another drawing program having some kind of grid concept. You might use this value to synchronize FidoCadJ's grid with the one used by the target. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportStart(DimensionG totalSize, List<LayerDesc> la, int grid) throws IOException { // We need to save layers informations, since we will use them later. layerV=la; out.write("[FIDOCAD]\n"); DrawingModel p = new DrawingModel(); ParserActions pa = new ParserActions(p); p.setLayers(la); out.write(new String(pa.registerConfiguration(extensions))); } /** Called at the end of the export phase. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportEnd() throws IOException { out.close(); fstream.close(); } /** Called when exporting an Advanced Text primitive. @param x the x position of the beginning of the string to be written. @param y the y position of the beginning of the string to be written. @param sizex the x size of the font to be used. @param sizey the y size of the font to be used. @param fontname the font to be used. @param isBold true if the text should be written with a boldface font. @param isMirrored true if the text should be mirrored. @param isItalic true if the text should be written with an italic font. @param orientation angle of orientation (degrees). @param layer the layer that should be used. @param text the text that should be written. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportAdvText (int x, int y, int sizex, int sizey, String fontname, boolean isBold, boolean isMirrored, boolean isItalic, int orientation, int layer, String text) throws IOException { int style=0; if (isBold) { style+=1; } if (isItalic) { style+=2; } if (isMirrored) { style+=4; } out.write(new PrimitiveAdvText(cLe(x), cLe(y), cLe(sizex), cLe(sizey), fontname, orientation, style,text, layer).toString(extensions)); } /** Called when exporting a Bézier primitive. @param x1 the x position of the first point of the trace. @param y1 the y position of the first point of the trace. @param x2 the x position of the second point of the trace. @param y2 the y position of the second point of the trace. @param x3 the x position of the third point of the trace. @param y3 the y position of the third point of the trace. @param x4 the x position of the fourth point of the trace. @param y4 the y position of the fourth point of the trace. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the stroke to use. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportBezier (int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { out.write(new PrimitiveBezier(cLe(x1), cLe(y1), cLe(x2), cLe(y2), cLe(x3), cLe(y3), cLe(x4), cLe(y4), layer,arrowStart, arrowEnd,arrowStyle, cLe(arrowLength), cLe(arrowHalfWidth), dashStyle, textFont, textFontSize).toString(extensions)); } /** Called when exporting a Connection primitive. @param x the x position of the position of the connection. @param y the y position of the position of the connection. @param layer the layer that should be used. @param size the size of the connection in logical units. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportConnection (int x, int y, int layer, double size) throws IOException { out.write(new PrimitiveConnection(cLe(x), cLe(y),layer, textFont, textFontSize).toString(extensions)); } /** Called when exporting a Line primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param layer the layer that should be used. // from 0.22.1 @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the stroke to use. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportLine (double x1, double y1, double x2, double y2, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { out.write(new PrimitiveLine(cLe(x1),cLe(y1), cLe(x2),cLe(y2),layer,arrowStart, arrowEnd,arrowStyle, cLe(arrowLength), cLe(arrowHalfWidth), dashStyle, textFont, textFontSize).toString(extensions)); } /** Called when exporting a Macro call. This function can just return false, to indicate that the macro should be rendered by means of calling other primitives. Please note that a macro does not have a reference layer, since it is defined by its components. @param x the x position of the position of the macro. @param y the y position of the position of the macro. @param isMirrored true if the macro is mirrored. @param orientation the macro orientation in degrees. @param macroName the macro name. @param macroDesc the macro description, in the FidoCad format. @param name the shown name. @param xn coordinate of the shown name. @param yn coordinate of the shown name. @param value the shown value. @param xv coordinate of the shown value. @param yv coordinate of the shown value. @param font the used font. @param fontSize the size of the font to be used. @param m the library. @throws IOException if a disaster happens, i.e. a file can not be accessed. @return false if the export of the macro is handled by this function, true if the macro should be split into primitives. */ public boolean exportMacro(int x, int y, boolean isMirrored, int orientation, String macroName, String macroDesc, String name, int xn, int yn, String value, int xv, int yv, String font, int fontSize, Map<String, MacroDesc> m) throws IOException { if(splitStandardMacros) { return false; } boolean isStandard=false; // A first way to determine if a macro is standard is to see if its // name does not contains a dot (original FidoCAD standard library) int dotpos=macroName.indexOf("."); if (dotpos<0) { isStandard = true; } else { // If the name contains a dot, we might check whether we have // one of the new FidoCadJ standard libraries: // pcb, ihram, elettrotecnica. // Obtain the library name String library=macroName.substring(0,dotpos); // Check it if(extensions && "pcb".equals(library)) { isStandard = true; } else if (extensions && "ihram".equals(library)) { isStandard = true; } else if (extensions && "elettrotecnica".equals(library)) { isStandard = true; } } // If the library is standard, we output the symbol just with a // single MC command. if(isStandard) { out.write(new PrimitiveMacro(m, layerV, cLe(x), cLe(y), macroName, name, cLe(xn), cLe(yn), value, cLe(xv), cLe(yv), font, cLe(fontSize), orientation/90, isMirrored).toString(extensions)); return true; } // If it is not standard, the macro will be expanded into primitives. return false; } /** Called when exporting an Oval primitive. Specify the bounding box. @param x1 the x position of the first corner. @param y1 the y position of the first corner. @param x2 the x position of the second corner. @param y2 the y position of the second corner. @param isFilled it is true if the oval should be filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the stroke to use. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportOval(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { out.write(new PrimitiveOval(cLe(x1), cLe(y1), cLe(x2), cLe(y2), isFilled, layer, dashStyle, textFont, textFontSize).toString(extensions)); } /** Called when exporting a PCBLine primitive. @param x1 the x position of the first point of the segment. @param y1 the y position of the first point of the segment. @param x2 the x position of the second point of the segment. @param y2 the y position of the second point of the segment. @param width the width ot the line. @param layer the layer that should be used. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPCBLine(int x1, int y1, int x2, int y2, int width, int layer) throws IOException { out.write(new PrimitivePCBLine(cLe(x1), cLe(y1),cLe(x2),cLe(y2), cLe(width), cLe(layer), textFont, textFontSize).toString(extensions)); } /** Called when exporting a PCBPad primitive. @param x the x position of the pad. @param y the y position of the pad. @param style the style of the pad (0: oval, 1: square, 2: rounded square). @param six the x size of the pad. @param siy the y size of the pad. @param indiam the hole internal diameter. @param layer the layer that should be used. @param onlyHole export only the hole. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPCBPad(int x, int y, int style, int six, int siy, int indiam, int layer, boolean onlyHole) throws IOException { if(!onlyHole) { out.write(new PrimitivePCBPad(cLe(x), cLe(y),cLe(six), cLe(siy),cLe(indiam), style, layer, textFont, textFontSize).toString(extensions)); } } /** Called when exporting a Polygon primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the stroke to use. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportPolygon(PointDouble[] vertices, int nVertices, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { PrimitivePolygon p=new PrimitivePolygon(isFilled, layer, dashStyle, textFont, textFontSize); for (int i=0; i <nVertices; ++i) { p.addPoint(cLe(vertices[i].x), cLe(vertices[i].y)); } out.write(p.toString(extensions)); } /** Called when exporting a Curve primitive. @param vertices array containing the position of each vertex. @param nVertices number of vertices. @param isFilled true if the polygon is filled. @param isClosed true if the curve is closed. @param layer the layer that should be used. @param arrowStart specify if an arrow is present at the first point. @param arrowEnd specify if an arrow is present at the second point. @param arrowStyle the style of the arrow. @param arrowLength total lenght of arrows (if present). @param arrowHalfWidth half width of arrows (if present). @param dashStyle dashing style. @param strokeWidth the width of the pen to be used when drawing. @return false if the curve should be rendered using a polygon, true if it is handled by the function. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public boolean exportCurve(PointDouble[] vertices, int nVertices, boolean isFilled, boolean isClosed, int layer, boolean arrowStart, boolean arrowEnd, int arrowStyle, int arrowLength, int arrowHalfWidth, int dashStyle, double strokeWidth) throws IOException { PrimitiveComplexCurve p=new PrimitiveComplexCurve(isFilled, isClosed, layer, arrowStart, arrowEnd,arrowStyle, cLe(arrowLength), cLe(arrowHalfWidth), dashStyle, textFont, textFontSize); for (int i=0; i <nVertices; ++i) { p.addPoint(cLe(vertices[i].x), cLe(vertices[i].y)); } out.write(p.toString(extensions)); return true; } /** Called when exporting a Rectangle primitive. @param x1 the x position of the first corner. @param y1 the y position of the first corner. @param x2 the x position of the second corner. @param y2 the y position of the second corner. @param isFilled it is true if the rectangle should be filled. @param layer the layer that should be used. @param dashStyle dashing style. @param strokeWidth the width of the stroke to use. @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public void exportRectangle(int x1, int y1, int x2, int y2, boolean isFilled, int layer, int dashStyle, double strokeWidth) throws IOException { out.write(new PrimitiveRectangle(cLe(x1), cLe(y1), cLe(x2), cLe(y2), isFilled, layer, dashStyle, textFont, textFontSize).toString(extensions)); } /** Called when exporting an arrow. @param x position of the tip of the arrow. @param y position of the tip of the arrow. @param xc direction of the tip of the arrow. @param yc direction of the tip of the arrow. @param l length of the arrow. @param h width of the arrow. @param style style of the arrow. @return always (0,0). @throws IOException if a disaster happens, i.e. a file can not be accessed. */ public PointPr exportArrow(double x, double y, double xc, double yc, double l, double h, int style) throws IOException { // Does nothing, since it will not be useful here. return new PointPr(); } }
21,932
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/layers/package-info.java
/** Provides the layer description as well as some code of general interest handling layers. NOTE: this package will be merged with net.sourceforge.fidocadj.layermodel in the future. */ package net.sourceforge.fidocadj.layers;
233
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
LayerDesc.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/layers/LayerDesc.java
package net.sourceforge.fidocadj.layers; import net.sourceforge.fidocadj.graphic.ColorInterface; /** layerDesc.java Provide a complete description of each layer (color, visibility). <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public class LayerDesc { // Number of layers to be treated: public static final int MAX_LAYERS=16; // The color of the layer: private ColorInterface layerColor; // isVisible is true if the layer should be drawn: public boolean isVisible; // is Modified is true if a redraw is needed: private boolean isModified; // Name or description of the layer: private String layerDescription; // Transparency private float alpha; /** Standard constructor: obtain a visible layer with a black color and no description. */ public LayerDesc() { layerColor=null; isVisible=true; layerDescription=""; } /** Standard constructor. @param c the color which should be used. @param v the visibility of the layer. @param d the layer description. @param a the transparency level (alpha), between 0.0 and 1.0. */ public LayerDesc(ColorInterface c, boolean v, String d, float a) { layerColor=c; isVisible=v; layerDescription=d; alpha = a; } /** This method allows to obtain the color in which this layer should be drawn. @return the color to be used */ final public ColorInterface getColor() { return layerColor; } /** This method allows to obtain the alpha channel of the current layer. @return the alpha blend */ final public float getAlpha() { return alpha; } /** This method returns true if this layer should be traced @return a boolean value indicating if the layer should be drawn */ final public boolean getVisible() { return isVisible; } /** This method returns true if this layer has been modified @return a boolean value indicating that the layer has been modified */ final public boolean getModified() { return isModified; } /** This method allows to obtain the color in which this layer should be drawn. @return the color to be used */ public String getDescription() { return layerDescription; } /** This method allows to set the layer description. @param s the layer description */ final public void setDescription(String s) { layerDescription=s; } /** This method allows to set the layer visibility. @param v the layer visibility. */ final public void setVisible(boolean v) { isVisible=v; } /** This method allows to indicate that the layer has been modified. @param v true if the layer should be considered as modified. */ final public void setModified(boolean v) { isModified=v; } /** This method allows to set the layer color. @param c the layer color. */ final public void setColor(ColorInterface c) { layerColor=c; } /** This method allows to set the alpha blend. @param a the alpha blend. */ final public void setAlpha(float a) { alpha=a; } }
4,128
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
StandardLayers.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/layers/StandardLayers.java
package net.sourceforge.fidocadj.layers; import java.awt.*; import java.util.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.swing.ColorSwing; /** SWING VERSION <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class StandardLayers { // A dummy list of layers. private static java.util.List<LayerDesc> ll_dummy; private final static Object lock = new Object(); /** Private constructor, for Utility class pattern */ private StandardLayers () { // nothing } /** Create the standard array containing the layer descriptions, colors and transparency. The name of the layers are read from the resources which may be initizialized. If Globals.messages==null, no description is given. @return the list of the layers being created. */ public static java.util.List<LayerDesc> createStandardLayers() { java.util.List<LayerDesc> layerDesc; synchronized(lock) { String s=""; layerDesc=new Vector<LayerDesc>(); if(Globals.messages!=null) { s=Globals.messages.getString("Circuit_l"); } layerDesc.add(new LayerDesc(new ColorSwing(Color.black), true, s,1.0f)); // 0 if(Globals.messages!=null) { s=Globals.messages.getString("Bottom_copper"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(0,0,128)), true, s,1.0f)); // 1 if(Globals.messages!=null) { s=Globals.messages.getString("Top_copper"); } layerDesc.add(new LayerDesc(new ColorSwing(Color.red), true, s,1.0f)); // 2 if(Globals.messages!=null) { s=Globals.messages.getString("Silkscreen"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(0,128,128)), true,s,1.0f));// 3 if(Globals.messages!=null) { s=Globals.messages.getString("Other_1"); } layerDesc.add(new LayerDesc(new ColorSwing(Color.orange), true,s,1.0f)); // 4 if(Globals.messages!=null) { s=Globals.messages.getString("Other_2"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(-8388864)), true,s,1.0f)); // 5 if(Globals.messages!=null) { s=Globals.messages.getString("Other_3"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(-16711681)), true,s,1.0f));// 6 if(Globals.messages!=null) { s=Globals.messages.getString("Other_4"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(-16744448)), true,s,1.0f));// 7 if(Globals.messages!=null) { s=Globals.messages.getString("Other_5"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(-6632142)), true, s,1.0f));// 8 if(Globals.messages!=null) { s=Globals.messages.getString("Other_6"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(-60269)), true,s,1.0f)); // 9 if(Globals.messages!=null) { s=Globals.messages.getString("Other_7"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(-4875508)), true,s,1.0f)); // 10 if(Globals.messages!=null) { s=Globals.messages.getString("Other_8"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(-16678657)), true,s,1.0f));// 11 if(Globals.messages!=null) { s=Globals.messages.getString("Other_9"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(-1973791)), true,s,0.95f));// 12 if(Globals.messages!=null) { s=Globals.messages.getString("Other_10"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(-6118750)), true,s,0.9f)); // 13 if(Globals.messages!=null) { s=Globals.messages.getString("Other_11"); } layerDesc.add(new LayerDesc(new ColorSwing(new Color(-10526881)), true,s,0.9f));// 14 if(Globals.messages!=null) { s=Globals.messages.getString("Other_12"); } layerDesc.add(new LayerDesc(new ColorSwing(Color.black), true, s,1.0f)); // 15 } return layerDesc; } /** Create a fictionous Array List. @return an Vector composed by LayerDesc.MAX_LAYERS opaque layers in green. */ public static java.util.List<LayerDesc> createEditingLayerArray() { synchronized(lock) { // This is called at each redraw, so it is a good idea to avoid // creating it each time. if(ll_dummy == null || ll_dummy.isEmpty()) { ll_dummy = new Vector<LayerDesc>(); ll_dummy.add(new LayerDesc(new ColorSwing(Color.green), true, "", 1.0f)); } } return ll_dummy; } }
6,152
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
package-info.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/geom/package-info.java
/** <p> Perform all kinds of geometrical operations: coordinate mapping, calculate distances between a graphical element and a given pointer... Probably, the most important class here is MapCoordinates, which contains information about the coordinate mapping, which is changed during zoom operations and so on. </p> */ package net.sourceforge.fidocadj.geom;
382
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ChangeCoordinatesListener.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/geom/ChangeCoordinatesListener.java
package net.sourceforge.fidocadj.geom; /** ChangeCoordinatesListener interface @author Davide Bucci @version 1.0, June 2008 <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008 by Davide Bucci </pre> */ public interface ChangeCoordinatesListener { /** Callback when the coordinates are changed. @param x the x coordinate of the mouse pointer @param y the y coordinate of the mouse pointer */ void changeCoordinates(int x, int y); /** Callback useful when some infos are to be shown. @param s the text to be shown (usually coordinates of the cursor). */ void changeInfos(String s); }
1,340
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DrawingSize.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/geom/DrawingSize.java
package net.sourceforge.fidocadj.geom; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.circuit.views.Drawing; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.nil.GraphicsNull; /** Calculate the size of a given drawing. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class DrawingSize { /** Private constructor, for Utility class pattern */ private DrawingSize () { // nothing } /** Get the image size. @param dm the model class containing the drawing. @param unitperpixel the zoom set to be used. @param countMin specifies that the size should be calculated counting the minimum x and y coordinates, and not the origin. @param origin is updated with the image origin. @return the image size stored in a {@link DimensionG} object. */ public static DimensionG getImageSize(DrawingModel dm, double unitperpixel, boolean countMin, PointG origin) { int width; int height; MapCoordinates m=new MapCoordinates(); m.setMagnitudes(unitperpixel, unitperpixel); m.setXCenter(0); m.setYCenter(0); // force an in-depth recalculation dm.setChanged(true); Drawing drawingAgent = new Drawing(dm); drawingAgent.draw(new GraphicsNull(),m); dm.imgCanvas.trackExtremePoints(m); dm.setChanged(true); // Calculate image size if(countMin) { width=m.getXMax()-m.getXMin(); height=m.getYMax()-m.getYMin(); } else { width=m.getXMax(); height=m.getYMax(); } // Verify that the image size is reasonable if(width<=0) { width=1; } if(height<=0) { height=1; } if (m.getXMax() >= m.getXMin() && m.getYMax() >= m.getYMin()) { origin.x=m.getXMin(); origin.y=m.getYMin(); } else { origin.x=0; origin.y=0; } return new DimensionG(width, height); } /** Get the image origin. @param dm the model class containing the drawing. @param unitperpixel the zoom set to be used. @return the origin coordinates in logical units, stored in a {@link PointG} object. */ public static PointG getImageOrigin(DrawingModel dm, double unitperpixel) { int originx; int originy; // force an in-depth recalculation dm.setChanged(true); MapCoordinates m=new MapCoordinates(); m.setMagnitudes(unitperpixel, unitperpixel); m.setXCenter(0); m.setYCenter(0); // Draw the image. In this way, the min and max coordinates will be // tracked. Drawing drawingAgent = new Drawing(dm); dm.imgCanvas.trackExtremePoints(m); drawingAgent.draw(new GraphicsNull(), m); dm.setChanged(true); // Verify that the image size is correct if (m.getXMax() >= m.getXMin() && m.getYMax() >= m.getYMin()) { originx=m.getXMin(); originy=m.getYMin(); } else { originx=0; originy=0; } return new PointG(originx, originy); } /** Calculate the zoom to fit the given size in pixel (i.e. the viewport size). @param dm the current drawing model. @param sizex the width of the area to be used for calculations. @param sizey the height of the area to be used for calculations. @param countMin specify if the absolute or relative size should be taken into account. In other words, consider (countMin=false) or not (countMin=true) the origin as part of the drawing. @return the zoom to fit settings stored in a new {@link MapCoordinates} object. */ public static MapCoordinates calculateZoomToFit(DrawingModel dm, int sizex, int sizey, boolean countMin) { // Here we calculate the zoom to fit parameters double maxsizex; double maxsizey; PointG org=new PointG(0,0); MapCoordinates newZoom=new MapCoordinates(); // Determine the size and the origin of the current drawing. DimensionG d = getImageSize(dm,1,countMin, org); maxsizex=d.width+1; maxsizey=d.height+1; if (!countMin) { org=new PointG(0,0); } double zoomx=1.0/(maxsizex/(double)sizex); double zoomy=1.0/(maxsizey/(double)sizey); double z= zoomx>zoomy ? zoomy:zoomx; z=Math.round(z*100.0)/100.0; // 0.20.5 if(z<MapCoordinates.MIN_MAGNITUDE) { z=MapCoordinates.MIN_MAGNITUDE; } newZoom.setMagnitudesNoCheck(z,z); // The zoom setting might have been rounded, or bounded. z = newZoom.getYMagnitude(); newZoom.setXCenter(org.x*z); newZoom.setYCenter(org.y*z); return newZoom; } }
6,018
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MapCoordinates.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/geom/MapCoordinates.java
package net.sourceforge.fidocadj.geom; import java.util.*; /** MapCoordinates.java <pre> @author D. Bucci This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2007-2023 by Davide Bucci </pre> MapCoordinates performs the coordinate mapping between the logical units used in FidoCad schematics with the corrisponding pixel position to be used when drawing on the screen or on an image file. The class tracks also the minimum and maximum values of the pixel x/y coordinates, in order to obtain the drawing size. The logical Fidocad resolution is 5 mils (127um). Thus, for the following resolutions, we obtain: <pre> Resolution units/pixel x/y magnitude --------------------------------------------------------- 72 pixels/inch 2.7778 0.36000 150 pixels/inch 1.3333 0.75000 300 pixels/inch 0.66666 1.50000 600 pixels/inch 0.33333 3.00000 1200 pixels/inch 0.16667 6.00000 </pre> This class allows to concatenate a translation with the xCenter and yCenter variables. This should NOT be used to scroll the actual drawing in the viewport, since this is done by using the JScrollPane Swing control. This is indeed very useful when exporting or when drawing macros. */ public class MapCoordinates { // Every member should be made private sooner or later... private double xCenter; private double yCenter; private double xMagnitude; private double yMagnitude; private int orientation; public boolean mirror; public boolean isMacro; private boolean snapActive; public static final double MIN_MAGNITUDE=0.25; public static final double MAX_MAGNITUDE=100.0; private double vx; private int ivx; // NOPMD this is not a local variable for efficiency private double vy; private int ivy; // NOPMD this is not a local variable for efficiency private int xMin; private int xMax; private int yMin; private int yMax; private int xGridStep; private int yGridStep; private final Deque<MapCoordinates> stack; /** Standard constructor */ public MapCoordinates() { xCenter=0.0; yCenter=0.0; xMagnitude=1.0; yMagnitude=1.0; orientation=0; xGridStep=5; yGridStep=5; isMacro=false; snapActive=true; resetMinMax(); stack = new ArrayDeque<MapCoordinates>(); } /** Change the current orientation. @param o the wanted orientation (comprised between 0 and 3). NOTE: if o is greater than 3, it will be truncated to 3. */ public void setOrientation(int o) { orientation=o; // Check for sanity if (orientation<0) { orientation=0; } if (orientation>3) { orientation=3; } } /** Get the current orientation. @return the current orientation. */ public int getOrientation() { return orientation; } /** Get the current mirroring state @return the current mirroring state. */ public boolean getMirror() { return mirror; } /** Save in a stack the current coordinate state. */ public void push() { MapCoordinates m = new MapCoordinates(); m.xCenter=xCenter; m.yCenter=yCenter; m.xMagnitude=xMagnitude; m.yMagnitude=yMagnitude; m.orientation=orientation; m.mirror=mirror; m.isMacro=isMacro; m.snapActive=snapActive; m.xMin=xMin; m.xMax=xMax; m.yMin=yMin; m.yMax=yMax; m.xGridStep=xGridStep; m.yGridStep=yGridStep; stack.addFirst(m); } /** Pop from a stack the coordinate state. */ public void pop() { if(stack.isEmpty()) { System.out.println("Warning: I can not pop the coordinate state "+ "out of an empty stack!"); } else { MapCoordinates m=(MapCoordinates) stack.removeFirst(); xCenter=m.xCenter; yCenter=m.yCenter; xMagnitude=m.xMagnitude; yMagnitude=m.yMagnitude; orientation=m.orientation; mirror=m.mirror; isMacro=m.isMacro; snapActive=m.snapActive; xMin=m.xMin; xMax=m.xMax; yMin=m.yMin; yMax=m.yMax; xGridStep=m.xGridStep; yGridStep=m.yGridStep; } } /** Set the snapping state (used in the unmapping functions) @param s the wanted state. */ public final void setSnap(boolean s) { snapActive=s; } /** Get the snapping state (used in the unmapping functions) @return the current snapping state. */ public final boolean getSnap() { return snapActive; } /** Set the X grid step @param xg the X grid step */ public final void setXGridStep(int xg) { if (xg>0) { xGridStep=xg; } } /** Set the Y grid step @param yg the Y grid step */ public final void setYGridStep(int yg) { if (yg>0) { yGridStep=yg; } } /** Get the X grid step @return the X grid step used */ public final int getXGridStep() { return xGridStep; } /** Get the Y grid step @return the Y grid step used */ public final int getYGridStep() { return yGridStep; } /** Get the X magnification factor @return the X magnification factor */ public final double getXMagnitude() { return xMagnitude; } /** Get the Y magnification factor @return the Y magnification factor */ public final double getYMagnitude() { return yMagnitude; } /** Set the X magnification factor. The factor is checked and will always be comprised between limits defined by MIN_MAGNITUDE and MAX_MAGNITUDE. @param txm the X magnification factor. */ public final void setXMagnitude(double txm) { double xm=txm; if (Math.abs(xm)<MIN_MAGNITUDE) { xm=MIN_MAGNITUDE; } if (Math.abs(xm)>MAX_MAGNITUDE) { xm=MAX_MAGNITUDE; } xMagnitude=xm; } /** Set the Y magnification factor. The factor is checked and will always be comprised between limits defined by MIN_MAGNITUDE and MAX_MAGNITUDE. @param tym the Y magnification factor. */ public final void setYMagnitude(double tym) { double ym=tym; if (Math.abs(ym)<MIN_MAGNITUDE) { ym=MIN_MAGNITUDE; } if (Math.abs(ym)>MAX_MAGNITUDE) { ym=MAX_MAGNITUDE; } yMagnitude=ym; } /** Set the X magnification factor. Does not check for limits of the magnification factor. Use with care! @param xm the X magnification factor. */ public final void setXMagnitudeNoCheck(double xm) { xMagnitude=xm; } /** Set the Y magnification factor. Does not check for limits of the magnification factor. Use with care! @param ym the Y magnification factor. */ public final void setYMagnitudeNoCheck(double ym) { yMagnitude=ym; } /** Get the X shift of the coordinate systems, in pixels @return the X shift in pixels */ public final double getXCenter() { return xCenter; } /** Get the Y shift of the coordinate systems, in pixels @return the Y shift in pixels */ public final double getYCenter() { return yCenter; } /** Set the X shift of the coordinate systems, in pixels @param xm the X shift in pixel */ public final void setXCenter(double xm) { xCenter=xm; } /** Set the Y shift of the coordinate systems, in pixels @param ym the Y shift in pixels */ public final void setYCenter(double ym) { yCenter=ym; } /** Set both X and Y magnification factors. @param xm the X magnification factor. @param ym the Y magnification factor. */ public final void setMagnitudes(double xm, double ym) { setXMagnitude(xm); setYMagnitude(ym); } /** Set both X and Y magnification factors. Does not check for limits of the magnification factor. Use with care! @param xm the X magnification factor. @param ym the Y magnification factor. */ public final void setMagnitudesNoCheck(double xm, double ym) { setXMagnitudeNoCheck(xm); setYMagnitudeNoCheck(ym); } /** Get the maximum tracked X coordinate @return the maximum tracked X coordinate */ public final int getXMax() { return xMax; } /** Get the maximum tracked Y coordinate @return the maximum tracked Y coordinate */ public final int getYMax() { return yMax; } /** Get the minimum tracked X coordinate @return the minimum tracked X coordinate */ public final int getXMin() { return xMin; } /** Get the minimum tracked Y coordinate @return the minimum tracked Y coordinate */ public final int getYMin() { return yMin; } /** Reset the minimum and maximum X/Y pixel coordinates tracked. */ public final void resetMinMax() { xMin=yMin=Integer.MAX_VALUE; xMax=yMax=Integer.MIN_VALUE; } /** Map the xc,yc coordinate given in the X pixel coordinate. The tracking is active. @param xc the horizontal coordinate in the drawing coordinate system. @param yc the vertical coordinate in the drawing coordinate system. @return the X coordinates in pixels. */ public final int mapX(double xc,double yc) { return mapXi(xc, yc, true); } /** Map the xc,yc coordinate given in the X pixel coordinate. @param xc the horizontal coordinate in the drawing coordinate system. @param yc the vertical coordinate in the drawing coordinate system. @param track specifies if the tracking should be active or not. @return the X coordinates in pixels. */ public final int mapXi(double xc,double yc, boolean track) { ivx=(int)Math.round(mapXr(xc,yc)); /* The integer cast cuts decimals to the lowest integer. We need to round correctly; */ if(track) { if(ivx<xMin) { xMin=ivx; } if(ivx>xMax) { xMax=ivx; } } return ivx; } /** Map the txc,tyc coordinate given in the X pixel coordinate. The results are given as double precision. Tracking is not active. @param txc the horizontal coordinate in the drawing coordinate system. @param tyc the vertical coordinate in the drawing coordinate system. @return the X coordinates in pixels. */ public final double mapXr(double txc,double tyc) { double xc=txc; double yc=tyc; // The orientation data is not used outside a macro if(isMacro){ xc-=100.0; yc-=100.0; if(mirror) { switch(orientation){ case 0: vx=-xc*xMagnitude; break; case 1: vx=yc*yMagnitude; break; case 2: vx=xc*xMagnitude; break; case 3: vx=-yc*yMagnitude; break; default: vx=-xc*xMagnitude; break; } } else { switch(orientation){ case 0: vx=xc*xMagnitude; break; case 1: vx=-yc*yMagnitude; break; case 2: vx=-xc*xMagnitude; break; case 3: vx=yc*yMagnitude; break; default: vx=xc*xMagnitude; break; } } } else { vx=(double)xc*xMagnitude; } return vx+xCenter; } /** Map the xc,yc coordinate given in the Y pixel coordinate. The tracking is active. @param xc the horizontal coordinate in the drawing coordinate system. @param yc the vertical coordinate in the drawing coordinate system. @return the Y coordinates in pixels. */ public final int mapY(double xc,double yc) { return mapYi(xc, yc, true); } /** Map the xc,yc coordinate given in the Y pixel coordinate. @param xc the horizontal coordinate in the drawing coordinate system. @param yc the vertical coordinate in the drawing coordinate system. @param track specify if the point should be tracked. @return the Y coordinates in pixels. */ public final int mapYi(double xc,double yc, boolean track) { ivy=(int)Math.round(mapYr(xc,yc)); /* The integer cast cuts decimals to the lowest integer. We need to round correctly; */ if(track) { if(ivy<yMin) { yMin=ivy; } if(ivy>yMax) { yMax=ivy; } } return ivy; } /** Map the xc,yc coordinate given in the Y pixel coordinate. The results are given as double precision. Tracking is not active. @param txc the horizontal coordinate in the drawing coordinate system. @param tyc the vertical coordinate in the drawing coordinate system. @return the Y coordinates in pixels. */ public final double mapYr(double txc,double tyc) { double xc=txc; double yc=tyc; if(isMacro){ xc-=100.0; yc-=100.0; switch(orientation){ case 0: vy=yc*yMagnitude; break; case 1: vy=xc*xMagnitude; break; case 2: vy=-yc*yMagnitude; break; case 3: vy=-xc*xMagnitude; break; default: vy=0.0; break; } } else { vy=(double)yc*yMagnitude; } return vy+yCenter; } /** Add a point in the min/max tracking system. The point should be specified in the SCREEN coordinates. @param xp the X coordinate of the point being tracked. @param yp the Y coordinate of the point being tracked. */ public final void trackPoint(double xp, double yp) { if(yp<yMin) { yMin=(int)yp; } if(yp>yMax) { yMax=(int)yp; } if(xp<xMin) { xMin=(int)xp; } if(xp>xMax) { xMax=(int)xp; } } /** Un Map the X screen coordinate given in the drawing coordinate. If the snapping is active, it is NOT applied here. @param x the horizontal coordinate in the screen coordinate system (pixels). @return the X coordinates in logical units. */ public int unmapXnosnap(int x) { return (int)Math.round((x-xCenter)/xMagnitude); } /** Un Map the Y screen coordinate given in the drawing coordinate. If the snapping is active, it is NOT applied here. @param y the horizontal coordinate in the screen coordinate system. @return the Y coordinates in logical units. */ public int unmapYnosnap(int y) { return (int)Math.round((y-yCenter)/yMagnitude); } /** Un Map the X screen coordinate given in the drawing coordinate. If the snapping is active, it is applied here. @param x the horizontal coordinate in the screen coordinate system. @return the X coordinates in logical units. */ public int unmapXsnap(int x) { int xc=unmapXnosnap(x); // perform the snapping. if(snapActive) { xc= (int)Math.round((double)xc/xGridStep); xc*=xGridStep; } return xc; } /** Un Map the Y screen coordinate given in the drawing coordinate. If the snapping is active, it is applied here. @param y the horizontal coordinate in the screen coordinate system (pixels). @return the Y coordinates in logical units. */ public int unmapYsnap(int y) { int yc=unmapYnosnap(y); // perform the snapping. if(snapActive) { yc=(int)Math.round((double)yc/yGridStep); yc*=yGridStep; } return yc; } /** Create a string containing all possibly interesting info about the internal state of this class. @return a {@link String} describing the coordinates system, mainly for debugging purposes. */ @Override public String toString() { String s=""; s+="[xCenter="+ xCenter; s+="|yCenter="+ yCenter; s+="|xMagnitude="+xMagnitude; s+="|yMagnitude="+yMagnitude; s+="|orientation="+orientation; s+="|mirror="+ mirror; s+="|isMacro="+isMacro; s+="|snapActive="+snapActive; s+="|xMin="+ xMin; s+="|xMax="+xMax; s+="|yMin="+yMin; s+="|yMax="+yMax; s+="|xGridStep="+xGridStep; s+="|yGridStep="+ yGridStep+"]"; return s; } }
18,798
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
GeometricDistances.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/geom/GeometricDistances.java
package net.sourceforge.fidocadj.geom; /** Calculate geometric distances between a given point and a few geometric objects. <pre> This file is part of FidoCadJ. FidoCadJ is 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, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 FidoCadJ. If not, @see <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class GeometricDistances { public static final int MIN_DISTANCE = 100; // Number of segments evaluated when calculatin the distance between a // point and a Bézier curve. public static final int MAX_BEZIER_SEGMENTS=10; // Some caching data private static int idx; private static int idy; private static int it; private static int ixmin; private static int ixmax; private static int iymin; private static int iymax; private static double dx; private static double dy; private static double t; private static double xmin; private static double ymin; private static double xmax; private static double ymax; private static int i; private static int j; private static boolean c; private GeometricDistances() { // Does nothing. } /** Calculate the euclidean distance between two points. The distance calculated here is not accurate. It is meant only to discriminate objects during the selection and therefore a inaccurate way to calculate distances is employed if the result is known to be greater than MIN_DISTANCE. @param xa the X coordinate of the first point. @param ya the Y coordinate of the first point. @param xb the X coordinate of the second point. @param yb the Y coordinate of the second point. @return the distance. */ public static double pointToPoint(double xa, double ya, double xb, double yb) { if(Math.abs(xa-xb) < MIN_DISTANCE || Math.abs(ya-yb) < MIN_DISTANCE) { return Math.sqrt((xa-xb)*(xa-xb)+(ya-yb)*(ya-yb)); } else { return MIN_DISTANCE; } } /** Calculate the euclidean distance between two points. The distance calculated here is not accurate. It is meant only to discriminate objects during the selection and therefore a inaccurate way to calculate distances is employed if the result is known to be greater than MIN_DISTANCE. @param xa the X coordinate of the first point. @param ya the Y coordinate of the first point. @param xb the X coordinate of the second point. @param yb the Y coordinate of the second point. @return the distance. */ public static int pointToPoint(int xa, int ya, int xb, int yb) { if(Math.abs(xa-xb) < MIN_DISTANCE || Math.abs(ya-yb) < MIN_DISTANCE) { return (int)Math.sqrt((xa-xb)*(xa-xb)+(ya-yb)*(ya-yb)); } else { return MIN_DISTANCE; } } /** Calculate the euclidean distance between a point and a segment. Adapted from http://www.vb-helper.com/howto_distance_point_to_line.html The distance calculated here is not accurate. It is meant only to discriminate objects during the selection and therefore a inaccurate way to calculate distances is employed if the result is known to be greater than MIN_DISTANCE. @param xa the X coordinate of the starting point of the segment. @param ya the Y coordinate of the starting point of the segment. @param xb the X coordinate of the ending point of the segment. @param yb the Y coordinate of the ending point of the segment. @param x the X coordinate of the point. @param y the Y coordinate of the point. @return the calculated distance. */ public static double pointToSegment(double xa, double ya, double xb, double yb, double x, double y) { // Shortcuts if(xa>xb) { xmin = xb; xmax = xa; } else { xmin = xa; xmax = xb; } if(x<xmin-MIN_DISTANCE || x>xmax+MIN_DISTANCE) { return MIN_DISTANCE; } if(ya>yb) { ymin = yb; ymax = ya; } else { ymin = ya; ymax = yb; } if(y<ymin-MIN_DISTANCE || y>ymax+MIN_DISTANCE) { return MIN_DISTANCE; } dx=xb-xa; dy=yb-ya; if (dx==0 && dy==0) { dx=x-xa; dy=y-yb; return Math.sqrt(dx*dx+dy*dy); } t=((x-xa)*dx+(y-ya)*dy)/(dx*dx+dy*dy); if (t<0.0) { dx=x-xa; dy=y-ya; } else if (t>1.0){ dx=x-xb; dy=y-yb; } else { dx=x-(xa+t*dx); dy=y-(ya+t*dy); } return Math.sqrt(dx*dx+dy*dy); } /** Calculate the euclidean distance between a point and a segment. Adapted from http://www.vb-helper.com/howto_distance_point_to_line.html This is a version which does all calculations in fixed point with three digits and it should be faster than the double precision version on some platforms. @param xa the X coordinate of the starting point of the segment. @param ya the Y coordinate of the starting point of the segment. @param xb the X coordinate of the ending point of the segment. @param yb the Y coordinate of the ending point of the segment. @param x the X coordinate of the point. @param y the Y coordinate of the point. @return the calculated distance. */ public static int pointToSegment(int xa, int ya, int xb, int yb, int x, int y) { // Shortcuts if(xa>xb) { ixmin = xb; ixmax = xa; } else { ixmin = xa; ixmax = xb; } if(x<ixmin-MIN_DISTANCE || x>ixmax+MIN_DISTANCE) { return MIN_DISTANCE; } if(ya>yb) { iymin = yb; iymax = ya; } else { iymin = ya; iymax = yb; } if(y<iymin-MIN_DISTANCE || y>iymax+MIN_DISTANCE) { return MIN_DISTANCE; } if (xb==xa && yb==ya) { idx=x-xa; idy=y-yb; return (int)Math.sqrt(idx*idx+idy*idy); } idx=xb-xa; idy=yb-ya; // This is an integer, fixed point implementation. We suppose to make // calculations with three decimals. it=1000*((x-xa)*idx+(y-ya)*idy)/(idx*idx+idy*idy); if (it<0) { idx=x-xa; idy=y-ya; } else if (it>1000){ idx=x-xb; idy=y-yb; } else { idx=x-(xa+it*idx/1000); // NOPMD parentheses are useful here! idy=y-(ya+it*idy/1000); // NOPMD parentheses are useful here! } return (int)Math.sqrt(idx*idx+idy*idy); } /** Tells if a point lies inside a polygon, using the alternance rule adapted from a snippet by Randolph Franklin, in Paul Bourke pages: http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/ @param xp vector of x coordinates of vertices @param yp vector of y coordinates of vertices @param npol number of vertices @param x x coordinate of the point @param y y coordinate of the point @return true if the point lies in the polygon, false otherwise. */ public static boolean pointInPolygon( int[] xp, int[] yp,int npol, double x, double y) { c = false; for (i = 0,j = npol-1; i < npol; j=i++) { if ((yp[i] <= y && y < yp[j] || yp[j] <= y && y < yp[i]) && x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] - yp[i]) + xp[i]) { c = !c; } j=i; } return c; } /** Tells if a point lies inside an ellipse @param ex x coordinate of the top left corner of the ellipse @param ey y coordinate of the top left corner of the ellipse @param w width of the ellipse @param h height of the ellipse @param px x coordinate of the point @param py y coordinate of the point @return true if the point lies in the ellipse, false otherwise. */ public static boolean pointInEllipse(double ex,double ey,double w, double h,double px,double py) { //Determine and normalize quadrant. dx = Math.abs(px-(ex+w/2.0)); // NOPMD dy = Math.abs(py-(ey+h/2.0)); // NOPMD //Shortcut if( dx > w/2.0 || dy > h/2.0) { return false; } // The multiplication by four is mandatory as the principal axis of an // ellipse are the half of the width and the height. return (4.0*dx*dx/w/w+4.0*dy*dy/h/h)<1.0; } /** Tells if a point lies inside an ellipse (integer version). @param ex x coordinate of the top left corner of the ellipse. @param ey y coordinate of the top left corner of the ellipse. @param w width of the ellipse. @param h height of the ellipse. @param px x coordinate of the point. @param py y coordinate of the point. @return true if the point lies in the ellipse, false otherwise. */ public static boolean pointInEllipse(int ex,int ey,int w, int h, int px,int py) { return pointInEllipse((double) ex,(double) ey,(double) w, (double) h,(double) px,(double) py); /* // On my iMac G5 the integer code is SLOWER than the double precision // calculations. //Determine and normalize quadrant. idx = Math.abs(px-(ex+w/2)); idy = Math.abs(py-(ey+h/2)); //Shortcut if( idx > w/2 || idy > h/2 ) { return false; } // Calculate the semi-latus rectum of the ellipse at the given point // The multiplication by four is mandatory as the principal axis of an // ellipse are the half of the width and the height. // Integer calculation with three digit accuracy. return (4000*idx*idx/w/w+4000*dy*dy/h/h)<1000; */ } /** Give the distance between the given point and the ellipse path. The difference with pointInEllipse is that pointInEllipse gives 0 when the point is inside the ellipse, where here we get the distance with the contour of the ellipse. @param ex x coordinate of the top left corner of the ellipse. @param ey y coordinate of the top left corner of the ellipse. @param w width of the ellipse. @param h height of the ellipse. @param px x coordinate of the point. @param py y coordinate of the point. @return the distance to the contour of the ellipse. */ public static double pointToEllipse(double ex,double ey,double w, double h,double px,double py) { // Calculate distance of the point from center of ellipse. double dx = Math.abs(px-(ex+w/2.0)); // NOPMD parentheses are useful! double dy = Math.abs(py-(ey+h/2.0)); // NOPMD parentheses are useful! // Treat separately the degenerate cases. This will avoid a divide // by zero anomalous situation. if (w==0) { return pointToSegment(ex, ey, ex, ey+h, px, py); } if (h==0) { return pointToSegment(ex, ey, ex+w, ey, px, py); } // Calculate the semi-latus rectum of the ellipse at the given point double l=(dx*dx/w/w+dy*dy/h/h)*4.0; return Math.abs(l-1.0)*Math.min(w,h)/4.0; } /** Give the distance between the given point and the ellipse path (integer version). @param ex x coordinate of the top left corner of the ellipse. @param ey y coordinate of the top left corner of the ellipse. @param w width of the ellipse. @param h height of the ellipse. @param px x coordinate of the point. @param py y coordinate of the point. @return the distance to the contour of the ellipse. */ public static int pointToEllipse(int ex,int ey,int w, int h, int px,int py) { return (int)Math.round(pointToEllipse((double) ex,(double)ey,(double) w, (double) h,(double) px,(double) py)); } /** Tells if a point lies inside a rectangle. @param ex x coordinate of the top left corner of the rectangle. @param ey y coordinate of the top left corner of the rectangle. @param w width of the rectangle. @param h height of the rectangle. @param px x coordinate of the point. @param py y coordinate of the point. @return true if the point lies in the ellipse, false otherwise. */ public static boolean pointInRectangle(double ex,double ey,double w, double h,double px,double py) { return !(ex>px||px>ex+w || ey>py || py>ey+h); } /** Tells if a point lies inside a rectangle, integer version. @param ex x coordinate of the top left corner of the rectangle. @param ey y coordinate of the top left corner of the rectangle. @param w width of the rectangle. @param h height of the rectangle. @param px x coordinate of the point. @param py y coordinate of the point. @return true if the point lies in the ellipse, false otherwise. */ public static boolean pointInRectangle(int ex,int ey,int w, int h, int px,int py) { return !(ex>px || px>ex+w || ey>py || py>ey+h); } /** Give the distance between the given point and the borders of a rectangle. @param ex x coordinate of the top left corner of the rectangle. @param ey y coordinate of the top left corner of the rectangle. @param w width of the rectangle. @param h height of the rectangle. @param px x coordinate of the point. @param py y coordinate of the point. @return the distance to one of the border of the rectangle. */ public static double pointToRectangle(double ex,double ey,double w, double h, double px,double py) { double d1=pointToSegment(ex,ey,ex+w,ey,px,py); double d2=pointToSegment(ex+w,ey,ex+w,ey+h,px,py); double d3=pointToSegment(ex+w,ey+h,ex,ey+h,px,py); double d4=pointToSegment(ex,ey+h,ex,ey,px,py); return Math.min(Math.min(d1,d2),Math.min(d3,d4)); } /** Give the distance between the given point and the borders of a rectangle (integer version). @param ex x coordinate of the top left corner of the rectangle. @param ey y coordinate of the top left corner of the rectangle. @param w width of the rectangle. @param h height of the rectangle. @param px x coordinate of the point. @param py y coordinate of the point. @return the distance to one of the border of the rectangle. */ public static int pointToRectangle(int ex,int ey,int w, int h, int px,int py) { int d1=pointToSegment(ex,ey,ex+w,ey,px,py); int d2=pointToSegment(ex+w,ey,ex+w,ey+h,px,py); int d3=pointToSegment(ex+w,ey+h,ex,ey+h,px,py); int d4=pointToSegment(ex,ey+h,ex,ey,px,py); return Math.min(Math.min(d1,d2),Math.min(d3,d4)); } /** Give an approximation of the distance between a point and a Bézier curve. The curve is divided into MAX_BEZIER_SEGMENTS linear pieces and the distance is calculated with each piece. The given distance is the minimum distance found for all pieces. Freely inspired from the original FidoCAD code. @param x1 x coordinate of the first control point of the Bézier curve. @param y1 y coordinate of the first control point of the Bézier curve. @param x2 x coordinate of the second control point of the Bézier curve. @param y2 y coordinate of the second control point of the Bézier curve. @param x3 x coordinate of the third control point of the Bézier curve. @param y3 y coordinate of the third control point of the Bézier curve. @param x4 x coordinate of the fourth control point of the Bézier curve. @param y4 y coordinate of the fourth control point of the Bézier curve. @param px x coordinate of the point. @param py y coordinate of the point. @return an approximate value of the distance between the given point and the Bézier curve specified by the control points. */ public static int pointToBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int px, int py) { int distance=Integer.MAX_VALUE; double b03; double b13; double b23; double b33; double umu; double u; int[] x=new int[MAX_BEZIER_SEGMENTS+1]; int[] y=new int[MAX_BEZIER_SEGMENTS+1]; for(i=0; i<=MAX_BEZIER_SEGMENTS; ++i) { u=(double)i/MAX_BEZIER_SEGMENTS; // This is the parametric form of the Bézier curve. // Probably, this is not the most convenient way to draw the // curve (one should probably use De Casteljau's Algorithm), // but it indeed OK to find a few values such the one we need umu=1-u; b03 = umu*umu*umu; b13 = 3 * u * umu*umu; b23 = 3 * u * u * umu; b33 = u*u*u; x[i] = (int)(x1 * b03 + x2 * b13 + x3 * b23 + x4 * b33); y[i] = (int)(y1 * b03 + y2 * b13 + y3 * b23 + y4 * b33); } // Calculate the distance of the given point with each of the // obtained segments. for(j=0;j<MAX_BEZIER_SEGMENTS;++j) { distance=Math.min(distance, pointToSegment(x[j], y[j], x[j+1], y[j+1],px, py)); } return distance; } }
19,287
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z