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
TextTransfer.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/clipboard/TextTransfer.java
package net.sourceforge.fidocadj.clipboard; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.Toolkit; import java.io.*; import net.sourceforge.fidocadj.globals.ProvidesCopyPasteInterface; /** Clipboard handling 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 2015-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class TextTransfer implements ClipboardOwner, ProvidesCopyPasteInterface { /** Perform a copy operation of the text specified as an argument. @param s the text to be copied */ public void copyText(String s) { // get the system clipboard Clipboard systemClipboard =Toolkit.getDefaultToolkit() .getSystemClipboard(); Transferable transferableText = new StringSelection(s); systemClipboard.setContents(transferableText,null); } /** Perform a paste operation of the copied test. The pasted text is returned. In other words, do a read in the clipboard. @return the pasted test. */ public String pasteText() { // TODO: review a little... // HASDONE: it seems to work quite reliably. No problems so far... TextTransfer textTransfer = new TextTransfer(); return textTransfer.getClipboardContents(); } /** Empty implementation of the ClipboardOwner interface. @param aClipboard handle to the clipboard to use. @param aContents handle to the contents. */ @Override public void lostOwnership(Clipboard aClipboard, Transferable aContents) { // does nothing } /** Place a {@link String} on the clipboard, and make this class the owner of the Clipboard's contents. @param aString the {@link String} to be employed. */ public void setClipboardContents(String aString) { StringSelection stringSelection = new StringSelection(aString); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, this); } /** Get the String residing on the clipboard. @return any text found on the Clipboard; if none found, return an empty {@link String}. */ public String getClipboardContents() { String result = ""; Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); //odd: the Object param of getContents is not currently used Transferable contents = clipboard.getContents(null); boolean hasTransferableText = contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor); if (hasTransferableText) { try { result = (String)contents.getTransferData( DataFlavor.stringFlavor); } catch (UnsupportedFlavorException | IOException ex){ //highly unlikely since we are using a standard DataFlavor System.out.println(ex); ex.printStackTrace(); } } return result; } }
4,018
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/globals/package-info.java
/** Provide methods of general interest (usually, low level). Some classes define global constants as well as global variables. */ package net.sourceforge.fidocadj.globals;
177
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
AccessResources.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/globals/AccessResources.java
package net.sourceforge.fidocadj.globals; import java.util.*; /** SWING VERSION This class is a container for the resource bundles employed by FidoCadJ. We need that since the code employing it must run on Swing as well as on Android and with Android we do not have the ResourceBundle class available. <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,If not, see http://www.gnu.org/licenses/ Copyright 2014-2023 by Davide Bucci </pre> */ public class AccessResources { // message bundle final private ResourceBundle messages; /** Standard creator. No resource bundle associated. */ public AccessResources() { messages = null; } /** Standard creator. @param m the resource bundle to be associated with the object. */ public AccessResources(ResourceBundle m) { messages = m; } /** Get the string associated to the given key in the resource bundle. @param s the key to retrieve the string resource. @return the message associated to the provided key. */ public String getString(String s) { return messages.getString(s); } }
1,769
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
Utf8ResourceBundle.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/globals/Utf8ResourceBundle.java
package net.sourceforge.fidocadj.globals; import java.io.UnsupportedEncodingException; import java.util.Enumeration; import java.util.Locale; import java.util.PropertyResourceBundle; import java.util.ResourceBundle; /** Taken here http://www.thoughtsabout.net/blog/archives/000044.html TODO: review Javadoc comments, check the license. */ public final class Utf8ResourceBundle { /** Standard creator. */ private Utf8ResourceBundle() { // Nothing to do. } /** Get the resource bundle. @param baseName the name of the bundle to be retrieved. @return the resource bundle object. */ public static ResourceBundle getBundle(String baseName) { ResourceBundle bundle = ResourceBundle.getBundle(baseName); return createUtf8PropertyResourceBundle(bundle); } /** Get the resource bundle. @param baseName the name of the bundle to be retrieved. @param locale the locale to be searched for. @return the resource bundle object. */ public static ResourceBundle getBundle(String baseName, Locale locale) { ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale); return createUtf8PropertyResourceBundle(bundle); } /** Get the resource bundle. @param baseName the name of the bundle to be retrieved. @param locale the locale to be searched for. @param loader the loader class to which the bundle should be associated. @return the resource bundle object. */ public static ResourceBundle getBundle(String baseName, Locale locale, ClassLoader loader) { ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, loader); return createUtf8PropertyResourceBundle(bundle); } /** Create a resource bundle with proper handling of UTF-8 resources. @param bundle the original bundle. @return the resource bundle. */ private static ResourceBundle createUtf8PropertyResourceBundle( ResourceBundle bundle) { if (!(bundle instanceof PropertyResourceBundle)) { return bundle; } return new Utf8PropertyResourceBundle((PropertyResourceBundle)bundle); } private static class Utf8PropertyResourceBundle extends ResourceBundle { PropertyResourceBundle bundle; public Utf8PropertyResourceBundle(PropertyResourceBundle bundle) { this.bundle = bundle; } /* (non-Javadoc) * @see java.util.ResourceBundle#getKeys() */ @Override public Enumeration<String> getKeys() { return bundle.getKeys(); } /* (non-Javadoc) * @see java.util.ResourceBundle#handleGetObject(java.lang.String) */ @Override protected Object handleGetObject(String key) { String value = (String)bundle.getString(key); String version = System.getProperty("java.specification.version"); // Things have changed starting from Java 9: the bundle.getString // returns directly an UTF-8 string, thus the translation is not // required anymore (JEP 226). if("1.7".equals(version) || "1.8".equals(version)) { // FindBugs suggests the following test is redundant. //if (value==null) return null; try { return new String (value.getBytes("ISO-8859-1"),"UTF-8") ; } catch (UnsupportedEncodingException e) { System.err.println("Unsupported encoding. "+ "Problems in Utf8PropertyResourceBundle class."); return null; } } else { return value; } } } }
3,857
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
LibUtils.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/globals/LibUtils.java
package net.sourceforge.fidocadj.globals; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.prefs.Preferences; import java.util.Locale; import net.sourceforge.fidocadj.primitives.MacroDesc; import net.sourceforge.fidocadj.undo.UndoActorListener; import net.sourceforge.fidocadj.FidoMain; /** Class to handle library files and databases. <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 phylum2, Davide Bucci </pre> @author phylum2, Davide Bucci */ public final class LibUtils { /** Private constructor, for Utility class pattern */ private LibUtils () { // nothing } /** Extract all the macros belonging to a given library. @param m the macro list. @param libfile the file name of the wanted library. @return the library. */ public static Map<String,MacroDesc> getLibrary(Map<String,MacroDesc> m, String libfile) { Map<String,MacroDesc> mm = new TreeMap<String,MacroDesc>(); MacroDesc md; for (Entry<String, MacroDesc> e : m.entrySet()) { md = e.getValue(); // The most reliable way to discriminate the macros is to watch // at the prefix in the key, i.e. everything which comes // before the dot in the complete key. int dotPos = md.key.lastIndexOf("."); // If no dot is found, this is by definition the original FidoCAD // standard library (immutable). if(dotPos<0) { continue; } String lib = md.key.substring(0,dotPos).trim(); if (lib.equalsIgnoreCase(libfile)) { mm.put(e.getKey(), md); } } return mm; } /** Prepare an header and collect text for creating a complete library. @param m the macro map associated to the library @param name the name of the library @return the library description in FidoCadJ code. */ public static String prepareText(Map<String,MacroDesc> m, String name) { StringBuffer sb = new StringBuffer(); String prev = null; int u; MacroDesc md; // Header sb.append("[FIDOLIB " + name + "]\n"); for (Entry<String,MacroDesc> e : m.entrySet()) { md = e.getValue(); // Category (check if it is changed) if (prev == null || !prev.equalsIgnoreCase(md.category.trim())) { sb.append("{"+md.category+"}\n"); prev = md.category.toLowerCase(Locale.US).trim(); } sb.append("["); // When the macros are written in the library, they contain only // the last part of the key, since the first part (before the .) // is always the file name. sb.append(md.key.substring( md.key.lastIndexOf(".")+1).toUpperCase(Locale.US).trim()); sb.append(" "); sb.append(md.name.trim()); sb.append("]"); u = md.description.codePointAt(0) == '\n'?1:0; sb.append("\n"); sb.append(md.description.substring(u)); sb.append("\n"); } return sb.toString(); } /** Save to a file a string respecting the global encoding settings. @param file the file name. @param text the string to be written in the file. @throws FileNotFoundException if the file can not be accessed. */ public static void saveToFile(String file, String text) throws FileNotFoundException { PrintWriter pw = null; try { pw = new PrintWriter(file, Globals.encoding); pw.print(text); pw.flush(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } finally { if (pw!=null) { pw.close(); } } } /** Save a library in a file. @param m the map containing the library. @param file the file name. @param libname the name of the library. @param prefix the prefix to be used for the keys. */ public static void save(Map<String,MacroDesc> m, String file, String libname, String prefix) { try { saveToFile(file + ".fcl", prepareText( getLibrary(m, prefix), libname)); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** Get the directory where the libraries files are to be read. @return the path to the directory. @throws FileNotFoundException if the directory can not be accessed. */ public static String getLibDir() throws FileNotFoundException { Preferences prefs = Preferences.userNodeForPackage(FidoMain.class); String s = prefs.get("DIR_LIBS", ""); if (s == null || s.length()==0) { throw new FileNotFoundException(); } if (!s.endsWith(System.getProperty("file.separator"))) { s+=System.getProperty("file.separator"); } return s; } /** Returns full path to lib file. @param lib Library name. @return the full path as a String. @throws FileNotFoundException if the file can not be accessed. */ public static String getLibPath(String lib) throws FileNotFoundException { return getLibDir()+lib.trim(); } /** Eliminates a library. @param s Name of the library to eliminate. @throws FileNotFoundException if the file can not be accessed. @throws IOException if a generic IO error occurs. */ public static void deleteLib(String s) throws FileNotFoundException, IOException { File f = new File(getLibDir()+s+".fcl"); if(!f.delete()) { throw new IOException("Can not delete library."); } } /** Get all the library in the current library directory. @return a list containing all the library files. @throws FileNotFoundException if the files can not be accessed. */ public static List<File> getLibs() throws FileNotFoundException { File lst = new File(getLibDir()); List<File> l = new ArrayList<File>(); if (!lst.exists()) { return l; } File[] list=lst.listFiles(); if(list==null) { return l; } for (File f : list) { if (f.getName().toLowerCase(Locale.US).endsWith(".fcl")) { l.add(f); } } return l; } /** Determine whether a library is standard or not. @param tlib the name (better prefix?) of the library @return true if the specified library is standard */ public static boolean isStdLib(MacroDesc tlib) { String szlib=tlib.library; if(szlib==null) { return false; } boolean isStandard=false; int dotpos=-1; boolean extensions=true; // 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) dotpos=tlib.key.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, ey_libraries. // Obtain the library name String library=tlib.key.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; } else if (extensions && "ey_libraries".equals(library)) { isStandard = true; } } return isStandard; } /** Rename a group inside a library. @param libref the map containing the library. @param tlib the name of the library. @param tgrp the name of the group to be renamed. @param newname the new name of the group. @throws FileNotFoundException if the file can not be accessed. */ public static void renameGroup(Map<String, MacroDesc> libref, String tlib, String tgrp, String newname) throws FileNotFoundException { // TODO: what if a group is not present? String prefix=""; for (MacroDesc md : libref.values()) { if (md.category.equalsIgnoreCase(tgrp) && md.library.trim().equalsIgnoreCase( tlib.trim())) { md.category = newname; prefix = md.filename; } } if ("".equals(prefix)) { return; } save(libref, getLibPath(tlib), tlib.trim(), prefix); } /** Check whether a key is used in a given library or it is available. The code also check for the presence of ']', a forbidden char since it would mess up the FidoCadJ file. Also check for strange characters. @param libref the map containing the library. @param tlib the name of the library. @param key the key to be checked. @return false if the key is available, true if it is used. */ public static boolean checkKey(Map<String, MacroDesc> libref, String tlib,String key) { for (MacroDesc md : libref.values()) { if (md.library.equalsIgnoreCase(tlib) && md.key.equalsIgnoreCase(key.trim())) { return true; } } return key.contains("]"); } /** Check if a library name is acceptable. Since the library name is used also as a file name, it must not contain characters which would be in conflict with the rules of file names in the various operating systems. @param library the library name to be checked. @return true if something strange is found. */ public static boolean checkLibrary(String library) { if (library == null) { return false; } return library.contains("[")||library.contains(".")|| library.contains("/")||library.contains("\\")|| library.contains("~")||library.contains("&")|| library.contains(",")||library.contains(";")|| library.contains("]")||library.contains("\""); } /** Delete a group inside a library. @param m the map containing the library. @param tlib the library name. @param tgrp the group to be deleted. @throws FileNotFoundException if the file can not be accessed. */ public static void deleteGroup(Map<String, MacroDesc> m,String tlib, String tgrp) throws FileNotFoundException { // TODO: what if a group is not found? Map<String, MacroDesc> mm = new TreeMap<String, MacroDesc>(); mm.putAll(m); String prefix=""; for (Entry<String, MacroDesc> smd : mm.entrySet()) { MacroDesc md = smd.getValue(); if (md.library.trim().equalsIgnoreCase(tlib) && md.category.equalsIgnoreCase(tgrp)) { m.remove(md.key); prefix = md.filename; } } if("".equals(prefix)) { return; } save(m, getLibPath(tlib), tlib, prefix); } /** Obtain a list containing all the groups in a given library. @param m the map containing all the libraries. @param prefix the filename of the wanted library. @return the list of groups. */ public static List<String> enumGroups(Map<String,MacroDesc> m, String prefix) { List<String> lst = new LinkedList<String>(); for (MacroDesc md : m.values()) { if (!lst.contains(md.category) && prefix.trim().equalsIgnoreCase(md.filename.trim())) { lst.add(md.category); } } return lst; } /** Obtain the full name of a library, from the prefix. @param m the map containing all the libraries. @param prefix the filename of the wanted library. @return the library name. */ public static String getLibName(Map<String,MacroDesc> m, String prefix) { List lst = new LinkedList(); for (MacroDesc md : m.values()) { if (!lst.contains(md.category) && prefix.trim().equalsIgnoreCase(md.filename.trim())) { return md.library; } } return null; } /** Here we save the state of the library for the undo operation. We create a temporary directory and we copy all the contents of the current library directory inside it. The temporary directory name is then saved in the undo system. @param ua the undo controller. @throws IOException if the files or directories needed for the undo can not be accessed. */ public static void saveLibraryState(UndoActorListener ua) throws IOException { try { // This is an hack: at first, we create a temporary file. We store // its name and we use it to create a temporary directory. File tempDir = File.createTempFile("fidocadj_", ""); if(!tempDir.delete()) { throw new IOException( "saveLibraryState: Can not delete temp file."); } if(!tempDir.mkdir()) { throw new IOException( "saveLibraryState: Can not create temp directory."); } String s=getLibDir(); String d=tempDir.getAbsolutePath(); // We copy all the contents of the current library directory in the // temporary directory. File sourceDir = new File(s); File destinationDir = new File(d); FileUtils.copyDirectoryNonRecursive(sourceDir, destinationDir, "fcl"); // We store the directory name in the stack structure of the // undo system. if(ua != null) { ua.saveUndoLibrary(d); } } catch (IOException e) { System.out.println("Cannot save the library status."); } } }
15,596
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
Globals.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/globals/Globals.java
package net.sourceforge.fidocadj.globals; import java.util.*; import net.sourceforge.fidocadj.ADesktopIntegration; /** Globals.java What? Global variables should not be used? But... who cares!!! (ehm... PMD does!) <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> */ public final class Globals { // message bundle public static AccessResources messages; // Information about desktop integration public static ADesktopIntegration desktopInt; // shortcut key to be used: public static int shortcutKey; // META (Command) for Macintoshes // CTRL elsewhere // This may be interesting on Macintoshes public static boolean useMetaForMultipleSelection; // Native file dialogs are far better on MacOSX than Linux public static boolean useNativeFileDialogs; // We are on a Mac!!! public static boolean weAreOnAMac; // Show the cancel button to the right of the OK button, as it is done in // Windows public static boolean okCancelWinOrder; // Track the total number of FidoCadJ open windows public static int openWindowsNumber; // A pointer to the active window public static Object activeWindow; public static final Set<Object> openWindows = new HashSet<Object>(); // Line width expressed in FidoCadJ coordinates public static final double lineWidthDefault = 0.5; public static double lineWidth = lineWidthDefault; // Line width expressed in FidoCadJ coordinates (ovals) public static final double lineWidthCirclesDefault = 0.35; public static double lineWidthCircles = lineWidthCirclesDefault; // Connection size in FidoCadJ coordinates (diameter) public static final double diameterConnectionDefault = 2.0; public static double diameterConnection = diameterConnectionDefault; // The last library and group selected by the user. // TODO: refactor this! Those variables should not be here. public static Object lastCLib; public static Object lastCGrp; // Version. This is shown in the main window title bar public static final String version = "0.24.9 alpha"; // Is it a beta version? Some debug options become available, such as // timing each redraw operation. public static final boolean isBeta = true; // The default file extension public static final String DEFAULT_EXTENSION = "fcd"; // The default font public static final String defaultTextFont = "Courier New"; // Comic Sans MS will send a 30 kV electrical discharge through USB... // Dash styles public static final int dashNumber = 5; public static final float dash[][] = { {10.0f,0f}, {5.0f,5.0f}, {2.0f, 2.0f}, {2.0f, 5.0f}, {2.0f, 5.0f,5.0f,5.0f}}; // Minimum height in pixels of a text to be drawn. public static final int textSizeLimit = 4; // The encoding to be used by FidoCadJ public static final String encoding = "UTF8"; // Maximum zoom factor in % // NOTE: there is an internal limit on geom.MapCoordinates that should // always be kept larger than this so that the limit is active. public static final double maxZoomFactor = 4000; // Maximum zoom factor in % public static final double minZoomFactor = 10; // Make sort that this is an utility class (private constructor). private Globals() { } /** Adjust a long string in order to cope with space limitations. Tipically, it will be used to show long paths in the window caption. @param s the string to be treated. @param len the total maximum length of the result. @return the prettified path. */ public static String prettifyPath(String s, int len) { int l=len; if(s.length()<l) { return s; } if (l<10) { l=10; } String r; r= s.substring(0,l/2-5)+ "... "+ s.substring(s.length()-l/2); return r; } /** Determine what is the current platform and configures some interface details such as the key to be used for shortcuts (Command/Meta for Mac and Ctrl for Linux and Windows). @param metaCode key code for the Meta key. @param ctrlCode key code for Ctrl key. */ public static void configureInterfaceDetailsFromPlatform(int metaCode, int ctrlCode) { useNativeFileDialogs=false; useMetaForMultipleSelection=false; if (System.getProperty("os.name").startsWith("Mac")) { // From what I know, only Mac users expect to use the Command (meta) // key for shortcuts, while others will use Control. shortcutKey=metaCode; useMetaForMultipleSelection=true; // Standard dialogs are vastly better on MacOSX than the Swing ones useNativeFileDialogs=true; // The order of the OK and Cancel buttons differs in Windows and // MacOSX. How about the most common Window Managers in Linux? okCancelWinOrder = false; } else { // This solves the bug #3076513 okCancelWinOrder = true; shortcutKey=ctrlCode; } } /** Check if an extension is present in a file name and, if it is not the case, add or adjust it in order to obtain the specified extension. If the string contains " somewhere, this character is removed and the extension is not added. In this way, if the user wants to avoid the automatic extension add, he should put the file name between "'s @param p the file name @param ext the extension that should be added if the file name does not contain one. This extension should NOT contain the dot. @return true if an extension already exists. */ public static boolean checkExtension(String p, String ext) { // TODO: check if the code can be simplified. int i; String s=""; StringBuffer t=new StringBuffer(25); // Check if we have a " somewhere boolean skip=false; for (i=0; i<p.length(); ++i) { if(p.charAt(i)=='"') { skip=true; } else { t.append(p.charAt(i)); } } if (skip) { return true; } s=t.toString(); // We need to check only the file name and not the entire path. // So we begin our research only after the last file separation int start=s.lastIndexOf(System.getProperty("file.separator")); int search=s.lastIndexOf("."); // If the separator has not been found, start is negative. if(start<0) { start=0; } // Search if there is a dot (separation of the extension) if (search>start && search>=0) { // There is already an extension. // We do not need to add anything but instead we need to check if // the extension is correct. String extension = s.substring(search+1); if(!extension.equals(ext)) { return false; } } else { return false; } return true; } /** Check if an extension is present in a file name and, if it is not the case, add or adjust it in order to obtain the specified extension. If the string contains " somewhere, this character is removed and the extension is not added. In this way, if the user wants to avoid the automatic extension add, he should put the file name between "'s @param p the file name @param ext the extension that should be added if the file name does not contain one. This extension should NOT contain the dot. @return the absolutely gorgeous file name, completed with an extension. */ public static String adjustExtension(String p, String ext) { int i; // Check if we have a " somewhere boolean skip=false; StringBuffer temp=new StringBuffer(25); for (i=0; i<p.length(); ++i) { if(p.charAt(i)=='"') { skip=true; } else { temp.append(p.charAt(i)); } } String s=temp.toString(); if (skip) { return s; } // We need to check only the file name and not the entire path. // So we begin our research only after the last file separation int start=s.lastIndexOf(System.getProperty("file.separator")); int search=s.lastIndexOf("."); // If the separator has not been found, start is negative. if(start<0) { start=0; } // Search if there is a dot (separation of the extension) if (search>start && search>=0) { // There is already an extension. // We do not need to add anything but instead we need to check if // the extension is correct. s = s.substring(0, search)+"."+ext; } else { s+="."+ext; } return s; } /** Get the file name, without extensions. @param s the file name with path and extension to be processed. @return the file name, without path and extension(s). */ public static String getFileNameOnly(String s) { // We need to check only the file name and not the entire path. // So we begin our research only after the last file separation int start=s.lastIndexOf(System.getProperty("file.separator")); int search=s.lastIndexOf("."); // If the separator has not been found, start is negative. if(start<0) { start=0; } else { start+=1; } if(search<0) { search=s.length(); } return s.substring(start,search); } /** When we have a path and a filename to put together, we need to separate them with a system file separator, being careful not to add it when it is already include in the path. @param path the path @param filename the file name @return the complete filename, including path */ public static String createCompleteFileName(String path, String filename) { boolean incl=!path.endsWith(System.getProperty("file.separator")); return path + (incl?System.getProperty("file.separator") : "") + filename; } /** Change characters which could give an error in some situations with their corresponding code, or escape sequence. @param p the input string, eventually containing the characters to be changed. @param bc an hash table (char, String) in which each character to be changed is associated with its code, or escape sequence. @return the string with the characters changed. */ public static String substituteBizarreChars(String p, Map bc) { StringBuffer s=new StringBuffer(""); for (int i=0; i<p.length(); ++i) { if((String)bc.get(""+p.charAt(i))==null) { s.append(p.charAt(i)); } else { s.append((String)bc.get(""+p.charAt(i))); } } return s.toString(); } /** Round the specified number to the specified number of decimal digits. @param n the number to be represented. @param ch the number of decimal digits to be retained. @return a string containing the result rounded to n digits. */ public static String roundTo(double n, int ch) { return ""+ (((int)(n*Math.pow(10,ch)))/Math.pow(10,ch)); } /** Round the specified number to two decimal digits. @param n the number to be represented. @return a string containing the result rounded to two digits. */ public static String roundTo(double n) { return ""+ Math.round(n*100.0)/100.0; } }
12,703
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ProvidesCopyPasteInterface.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/globals/ProvidesCopyPasteInterface.java
package net.sourceforge.fidocadj.globals; /** ProvidesCopyPasteInterface is an interface describing a minimalistic set of methods which may be used during copy/paste operations. <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> */ public interface ProvidesCopyPasteInterface { /** Copy a text into the clipboard. @param s the text to be copied. */ void copyText(String s); /** Paste a text from the clipboard. @return the text retrieved from the clipboard. */ String pasteText(); }
1,260
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
FileUtils.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/globals/FileUtils.java
package net.sourceforge.fidocadj.globals; import java.io.*; import java.util.*; /** The FileUtils class contains methods for file and directory handling, which comprises reading a file, copying or deleting a directory as well as things like 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 <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2008-2023 by Davide Bucci </pre> */ public final class FileUtils { /** Private constructor, for Utility class pattern */ private FileUtils () { // nothing } /** Read an input file. @param filename the complete path and filename of the file to read. @return the file contents. @throws IOException if the file access fails. */ public static String readFile(String filename) throws IOException { FileReader input = null; BufferedReader bufRead = null; StringBuffer txt=new StringBuffer(""); try { input=new FileReader(filename); bufRead = new BufferedReader(input); String line=""; txt = new StringBuffer(bufRead.readLine()); txt.append("\n"); while (line != null){ line =bufRead.readLine(); txt.append(line); txt.append("\n"); } } finally { if(bufRead!=null) { bufRead.close(); } if(input!=null) { input.close(); } } return txt.toString(); } /** Copy a directory recursively. http://subversivebytes.wordpress.com/2012/11/05/java-copy-directory- recursive-delete/ @param sourceLocation the original directory. @param targetLocation the destination. @throws IOException if the file access fails. */ public static void copyDirectory(File sourceLocation, File targetLocation) throws IOException { if(sourceLocation.isDirectory()) { if(!targetLocation.exists() && !targetLocation.mkdir()) { throw new IOException("Can not create temp. directory."); } // Process all the elements of the directory. String[] children = sourceLocation.list(); if (children==null) { return; } for(String currentFile: children) { copyDirectory(new File(sourceLocation, currentFile), new File(targetLocation, currentFile)); } } else { copyFile(sourceLocation, targetLocation); } } /** Copy a file from a location to another one. @param sourceLocation origin of the file to copy. @param targetLocation destination of the file to copy. @throws IOException if the file access fails. */ public static void copyFile(File sourceLocation, File targetLocation) throws IOException { if(sourceLocation.isDirectory()) { return; } InputStream in = null; OutputStream out = null; // The copy is made by bunch of 1024 bytes. // I wander whether better OS copy funcions exist. try { in= new FileInputStream(sourceLocation); out=new FileOutputStream(targetLocation); byte[] buf = new byte[1024]; int len; while((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { if (out!=null) { out.close(); } if (in!=null) { in.close(); } } } /** Copy all the files containing the specified criterium in the given directory. The criterium specifies files in a very simple way. The function just check if the file name contains it. Therefore, specifying "txt" as criteria would match "txtpipo.ed" as well as "pipo.txt". Specifying ".txt" would match "lors.txt.bak" as well as "rone.txt". This copy is not recursive: only the first level is processed. @param sourceLocation origin of the directory where are the files to copy. @param targetLocation destination of the files to copy. @param tcriteria the search criteria to be employed. @throws IOException if the file access fails. */ public static void copyDirectoryNonRecursive(File sourceLocation, File targetLocation, String tcriteria) throws IOException { String criteria=tcriteria; if(sourceLocation.isDirectory()) { if(!targetLocation.exists() && !targetLocation.mkdir()) { throw new IOException("Can not create temp. directory."); } criteria = criteria.toLowerCase(new Locale("en")); String[] children = sourceLocation.list(); if(children==null) { return; } for(String s : children) { if(s.toLowerCase(Locale.US).contains(criteria)) { copyFile(new File(sourceLocation, s), new File(targetLocation, s)); } } } } /** http://stackoverflow.com/questions/3775694/deleting-folder-from-java @param directory the directory to delete. @return true if deletion was successful. @throws IOException if the file access fails. */ public static boolean deleteDirectory(File directory) throws IOException { if(directory.exists()){ File[] files = directory.listFiles(); if(null!=files){ for(File f : files) { if(f.isDirectory()) { deleteDirectory(f); } else { if (!f.delete()) { throw new IOException("Can not delete file"+f); } } } } } return directory.delete(); } }
6,654
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ChangeGridState.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/toolbars/ChangeGridState.java
package net.sourceforge.fidocadj.toolbars; /** Interface used to callback notify that the current grid or snap state 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>. Copyright 2008-2023 by Davide Bucci </pre> @author Davide Bucci */ public interface ChangeGridState { /** The callback method which is called when the current grid visibility has changed. @param v is the wanted grid visibility state */ void setGridVisibility(boolean v); /** The callback method which is called when the current snap visibility has changed. @param v is the wanted snap state */ void setSnapState(boolean v); }
1,360
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/toolbars/package-info.java
/** Package containing all the GUI elements for the FidoCadJ toolbars, as well as the interfaces needed for keeping track of the actions from the user. */ package net.sourceforge.fidocadj.toolbars;
206
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ToolbarZoom.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/toolbars/ToolbarZoom.java
package net.sourceforge.fidocadj.toolbars; import javax.swing.*; import java.util.*; import java.awt.Dimension; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import net.sourceforge.fidocadj.dialogs.LayerCellRenderer; import net.sourceforge.fidocadj.geom.ChangeCoordinatesListener; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; /** ToolbarZoom 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 ToolbarZoom extends JToolBar implements ActionListener, ChangeZoomListener, ChangeCoordinatesListener { private final JComboBox<String> zoom; private final JToggleButton showGrid; private final JToggleButton snapGrid; private final JToggleButton showLibs; private final JLabel coords; private ChangeGridState changeListener; private double oldzoom; private ChangeZoomListener notifyZoomChangeListener; private ZoomToFitListener actualZoomToFitListener; private final JComboBox<LayerDesc> layerSel; private ChangeSelectedLayer changeLayerListener; /** Standard constructor @param l the layer description */ public ToolbarZoom (List<LayerDesc> l) { putClientProperty("Quaqua.ToolBar.style", "title"); zoom = new JComboBox<String>(); zoom.addItem("25%"); zoom.addItem("50%"); zoom.addItem("75%"); zoom.addItem("100%"); zoom.addItem("150%"); zoom.addItem("200%"); zoom.addItem("300%"); zoom.addItem("400%"); zoom.addItem("600%"); zoom.addItem("800%"); zoom.addItem("1000%"); zoom.addItem("1500%"); zoom.addItem("2000%"); zoom.addItem("3000%"); zoom.addItem("4000%"); zoom.setPreferredSize(new Dimension (100,29)); zoom.setMaximumSize(new Dimension (100,38)); zoom.setMinimumSize(new Dimension (100,18)); /* Commented the following line due to this remark: http://www.electroyou.it/phpBB2/viewtopic.php?f=4& t=18347&start=450#p301931 */ //zoom.setFocusable(false); JButton zoomFit; zoomFit=new JButton(Globals.messages.getString("Zoom_fit")); showGrid=new JToggleButton(Globals.messages.getString("ShowGrid")); snapGrid=new JToggleButton(Globals.messages.getString("SnapToGrid")); coords = new JLabel(""); setBorderPainted(false); layerSel = new JComboBox<LayerDesc>(new Vector<LayerDesc>(l)); layerSel.setToolTipText( Globals.messages.getString("tooltip_layerSel")); layerSel.setRenderer( new LayerCellRenderer()); changeListener=null; showLibs=new JToggleButton(Globals.messages.getString("Libs")); // MacOSX Quaqua information zoomFit.putClientProperty("Quaqua.Button.style","toggleWest"); showGrid.putClientProperty("Quaqua.Button.style","toggleCenter"); snapGrid.putClientProperty("Quaqua.Button.style","toggleCenter"); showLibs.putClientProperty("Quaqua.Button.style","toggleEast"); // VAqua7 information String style="recessed"; // order: recessed, textured, // segmentedCapsule, segmentedRoundRect, segmented, segmentedTextured zoomFit.putClientProperty("JButton.buttonType",style); zoomFit.putClientProperty("JButton.segmentPosition","first"); showGrid.putClientProperty("JButton.buttonType",style); showGrid.putClientProperty("JButton.segmentPosition","middle"); snapGrid.putClientProperty("JButton.buttonType",style); snapGrid.putClientProperty("JButton.segmentPosition","middle"); showLibs.putClientProperty("JButton.buttonType",style); showLibs.putClientProperty("JButton.segmentPosition","last"); zoom.addActionListener(this); zoomFit.addActionListener(this); showGrid.addActionListener(this); snapGrid.addActionListener(this); showLibs.addActionListener(this); layerSel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { if (layerSel.getSelectedIndex()>=0 && changeListener!=null) { changeLayerListener.changeSelectedLayer( layerSel.getSelectedIndex()); } } }); changeListener=null; add(zoom); add(zoomFit); add(showGrid); add(snapGrid); add(showLibs); add(layerSel); add(Box.createGlue()); add(coords); add(Box.createGlue()); coords.setPreferredSize(new Dimension (300,28)); coords.setMinimumSize(new Dimension (300,18)); coords.setMaximumSize(new Dimension (300,38)); setFloatable(true); setRollover(false); zoom.setEditable(true); showGrid.setSelected(true); snapGrid.setSelected(true); showLibs.setSelected(true); changeCoordinates(0, 0); } /** Add a layer listener (object implementing the ChangeSelectionListener interface) whose change method will be called when the current layer should be changed. @param c the change selection layer listener. */ public void addLayerListener(ChangeSelectedLayer c) { changeLayerListener=c; } /** Add a grid state listener whose methods will be called when the current grid state should be changed. @param c the wanted grid state */ public void addGridStateListener(ChangeGridState c) { changeListener=c; } /** Add a zoom change listener to be called when the zoom is changed by the user with the combo box slide. @param c the new listener. */ public void addChangeZoomListener(ChangeZoomListener c) { notifyZoomChangeListener=c; } /** Add a zoom to fit listener to be called when the user wants to fit @param c the new listener. */ public void addZoomToFitListener(ZoomToFitListener c) { actualZoomToFitListener=c; } /** The event listener to be called when the buttons are pressed, or the zoom setup is changed. @param evt the event to be processed. */ @Override public void actionPerformed(ActionEvent evt) { String s = evt.getActionCommand(); // Buttons if(s.equals(Globals.messages.getString("ShowGrid"))) { // Toggle grid visibility if(changeListener!=null) { changeListener.setGridVisibility(showGrid.isSelected()); } } else if(s.equals(Globals.messages.getString("SnapToGrid"))) { // Toggle snap to grid if(changeListener!=null) { changeListener.setSnapState(snapGrid.isSelected()); } } else if(s.equals(Globals.messages.getString("Zoom_fit"))) { // Zoom to fit if(actualZoomToFitListener!=null) { actualZoomToFitListener.zoomToFit(); } } else if(evt.getSource() instanceof JComboBox) { // ComboBox: the only one is about the zoom settings. handleZoomChangeEvents(evt); } else if(s.equals(Globals.messages.getString("Libs"))) { // Toggle library visibility actualZoomToFitListener.showLibs(showLibs.isSelected()); } } /** Set the current state of the button which controls the visibility of the library tree. This method is useful when the state is changed elsewhere and one needs to update the visible appearance of the button to follow the change. @param s the true if the libs are visible. */ public void setShowLibsState(boolean s) { showLibs.setSelected(s); } /** Handle events of zoom change from the combo box. @param evt the event object. */ private void handleZoomChangeEvents(ActionEvent evt) { if (notifyZoomChangeListener!=null) { try { String s=(String)zoom.getSelectedItem(); // The percent symbol should be eliminated. s=s.replace('%',' ').trim(); //System.out.println ("New zoom: "+s); double z=Double.parseDouble(s); // Very important: if I remove that, CPU goes to 100% // since this is called continuously! if(z==oldzoom) { return; } oldzoom=z; if(Globals.minZoomFactor<=z && z<=Globals.maxZoomFactor) { notifyZoomChangeListener.changeZoom(z/100); } } catch (NumberFormatException ee) { System.out.println("Exception while changing the zoom. "+ evt); } } } /** Change the zoom level and show it in the combo box @param z the new zoom level to be considered */ public void changeZoom(double z) { zoom.setSelectedItem(""+((int)(z*100))+"%"); } /** Change the cursor coordinates to be shown @param x the x value of the cursor coordinates (logical units) @param y the y value of the cursor coordinates (logical units) */ public void changeCoordinates(int x, int y) { int xum=x*127; int yum=y*127; float xmm=(float)xum/1000; float ymm=(float)yum/1000; Color c1=UIManager.getColor("Label.foreground"); Color c2=UIManager.getColor("Label.background"); if(c1!=null && c2!=null) { coords.setOpaque(false); coords.setForeground(c1); coords.setBackground(c2); } coords.setText(""+x+"; "+y+ " ("+xmm+" mm; "+ymm+" mm)"); } /** Change the strict compatibility mode with the old FidoCAD. @param strict true if a strict compatibility mode should be active. */ public void changeStrict(boolean strict) { // Does nothing. } /** Change the state of the show libs toggle button. @param s the state of the button. */ public void setShowLibs(boolean s) { showLibs.setSelected(s); } /** Change the state of the show grid toggle button. @param s the state of the button. */ public void setShowGrid(boolean s) { showGrid.setSelected(s); } /** Change the state of the show grid toggle button. @param s the state of the button. */ public void setSnapGrid(boolean s) { snapGrid.setSelected(s); } /** Change the infos. @param s the string to be shown. */ public void changeInfos(String s) { // Ensure that we will be able to restore colors back! Color c1=UIManager.getColor("Label.background"); Color c2=UIManager.getColor("Label.foreground"); if(c1!=null && c2!=null) { coords.setOpaque(true); coords.setForeground(Color.WHITE); coords.setBackground(Color.GREEN.darker().darker()); } coords.setText(s); } }
12,107
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ChangeZoomListener.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/toolbars/ChangeZoomListener.java
package net.sourceforge.fidocadj.toolbars; /** ChangeZoomListener interface @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 2008-2023 by Davide Bucci </pre> */ public interface ChangeZoomListener { /** Set the current zoom to the given parameter. @param z the new zoom */ void changeZoom(double z); }
1,053
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ChangeSelectionListener.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/toolbars/ChangeSelectionListener.java
package net.sourceforge.fidocadj.toolbars; /** Interface used to callback notify that the current selection state 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>. Copyright 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public interface ChangeSelectionListener { /** The callback method which is called when the current selection state has changed. @param s the actual selection state (see the CircuitPanel class for the definition of the constants used here). @param macroKey the key of the macro being used (if necessary). */ void setSelectionState(int s, String macroKey); /** Set if the strict FidoCAD compatibility mode is active @param strict true if the compatibility with FidoCAD should be obtained. */ void setStrictCompatibility(boolean strict); /** Get the actual selection state. @return the actual selection state (see the CircuitPanel class for the definition of the constants used here). */ int getSelectionState(); }
1,761
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ToolButton.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/toolbars/ToolButton.java
package net.sourceforge.fidocadj.toolbars; import javax.swing.*; import java.net.*; import net.sourceforge.fidocadj.globals.Globals; /** ToolButton class This class contains a constructor, which allows to create buttons for the FidoCadJ toolbar, {@link ToolbarTools}. Having the button created in this class allows to add a button in the <code>ToolbarTools</code> class by defining most of the button parameters on a single line. This also avoids code repetition and gives more flexibility to the design the buttons. <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, Jose Emilio Munoz */ public class ToolButton { private final JToggleButton toolButton; /** Class Constructor: Creates a new <code>JToggleButton</code> that has the specified text and image, and that is initially unselected. It also assigns an <code>actionCommand</code> and a <code>toolTip</code> to the button. @param tt the ToolbarTools object to which the button belongs. @param image Icon image file. @param toolText Button text, a <code>Globals</code> message. @param actionCommand Button action command. @param toolTip Button description/tip, a <code>Globals</code> message. */ public ToolButton (ToolbarTools tt, String image, String toolText, String actionCommand, String toolTip) { String base = tt.getBase(); boolean showText = tt.getShowText(); URL url = ToolbarTools.class.getResource(base+image); toolButton = new JToggleButton(showText?Globals.messages. getString(toolText):"", new ImageIcon(url)); toolButton.setActionCommand(actionCommand); toolButton.setToolTipText(Globals.messages.getString(toolTip)); toolButton.setVerticalTextPosition(SwingConstants.BOTTOM); toolButton.setHorizontalTextPosition(SwingConstants.CENTER); // This property is very useful when using the Quaqua style // with Apple Macintosh computers. toolButton.putClientProperty("Quaqua.Button.style","toolBarTab"); toolButton.putClientProperty("JButton.buttonType","segmented"); } /** With this method, the button can be passed to the <code>ToolbarTools</code> class as a <code>JToggleButton</code>. @return toolButton. */ public JToggleButton getToolButton() { return toolButton; } }
3,340
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ChangeSelectedLayer.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/toolbars/ChangeSelectedLayer.java
package net.sourceforge.fidocadj.toolbars; /** Interface used to callback notify that the current layer 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>. Copyright 2008 by Davide Bucci </pre> @author Davide Bucci */ public interface ChangeSelectedLayer { /** The callback method which is called when the current layer has changed. @param s the new layer. */ void changeSelectedLayer(int s); }
1,118
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ZoomToFitListener.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/toolbars/ZoomToFitListener.java
package net.sourceforge.fidocadj.toolbars; /** ZoomToFitListener interface @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 2008-2023 by Davide Bucci </pre> */ public interface ZoomToFitListener { /** Toggle a "zoom to fit" calculation */ void zoomToFit(); /** Set the library tree (and preview) visibility. @param s the state. */ void showLibs(boolean s); }
1,122
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ToolbarTools.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/toolbars/ToolbarTools.java
package net.sourceforge.fidocadj.toolbars; import java.awt.event.*; import javax.swing.*; import java.util.*; import net.sourceforge.fidocadj.circuit.controllers.ElementsEdtActions; /** SWING VERSION. ToolbarTools class <p>This class allows to add and organise the buttons in the toolbar. Buttons are instances of <code>JToggleButton</code>, i.e. they have two states, selected and not selected. To make it easier to add a button, they are defined first as a <code>ToolButton</code> ({@link ToolButton}), then they are assigned their variable name, and they are finally added to the toolbar using the appropriate method ({@link #addToolButton(JToggleButton, int)}).</p> <p>Once they are added to the toolbar, their action, when selected, must be defined. They implement their own <code>ActionListener</code> (inner classes) and <code>actionPerformed</code> methods so that they can each have a different behavior if required.</p> <p>When created they are automatically added to an <code>ArrayList</code> (to loop through this list and find the selected button, {@link #getSelectedButton()}, this is used in {@link #getSelectionState()}), to a <code>HashMap</code> (to assign and find the <code>CircuitPanel</code> constant of each button, this is used in {@link #setSelectionState(int, String)}) and to a <code>ButtonGroup</code>, so that only one button is selected at a time.</p> <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, Jose Emilio Munoz */ public final class ToolbarTools extends JToolBar implements ChangeSelectionListener { private ChangeSelectionListener selectionListener; //Instance variable of each button private final JToggleButton selection; private final JToggleButton zoom; private final JToggleButton hand; private final JToggleButton line; private final JToggleButton advtext; private final JToggleButton bezier; private final JToggleButton polygon; private final JToggleButton ellipse; private final JToggleButton complexcurve; private final JToggleButton rectangle; private final JToggleButton connection; private final JToggleButton pcbline; private final JToggleButton pcbpad; private final JLabel fileName; private final String base; private final boolean showText; private final ButtonGroup group; private final List<JToggleButton> toolButtonsList; private final Map<JToggleButton, Integer> circuitPanelConstants; /** On some operating systems, namely MacOS, the filename is shown in the toolbar. @param t the name to be shown. */ public void setTitle(String t) { fileName.setText(t); } /** <code>base</code> is passed to the <code>ToolbarTools</code> constructor to create the toolbar, but will need to be accessed by the <code>ToolButton</code> class to create each button. @return base */ public String getBase() { return base; } /** <code>showText</code> is passed to the <code>ToolbarTools</code> constructor to create the toolbar, but will need to be accessed by the <code>ToolButton</code> class to create each button. @return showText */ public boolean getShowText() { return showText; } /** This method effectively adds the defined button to the toolbar. @param button - Name of the button to be added to the toolbar. @param circuitPanelConstant - Determines its function, see <code>circuitPanel</code> class. */ public void addToolButton(JToggleButton button, int circuitPanelConstant) { add(button); group.add(button); toolButtonsList.add(button); circuitPanelConstants.put(button, Integer.valueOf(circuitPanelConstant)); } /** Class Constructor Creates the toolbar, consisting of all the buttons, which are displayed from left to right, in the order they were added. @param showText - True if the name of the tool is to be displayed underneath the icon. @param smallIcons - True if 16x16 size icons are to be displayed. */ public ToolbarTools (boolean showText, boolean smallIcons) { base = smallIcons ? "icons16/" : "icons32/"; this.showText = showText; putClientProperty("Quaqua.ToolBar.style", "title"); setBorderPainted(false); group = new ButtonGroup(); toolButtonsList = new ArrayList<JToggleButton>(); circuitPanelConstants = new HashMap<JToggleButton, Integer>(); /** First button to be added. Firstly a ToolButton object is created by defining an icon image, the text displaying the name of the tool, the button ActionCommand, and the tool description/tip. Then it is assigned to the appropriate instance variable using the ToolButton.getToolButton() method. Finally button behavior is defined. As the button circuitPanel constant was already defined when adding the button, the appropriate constant is now fetched from the circuitPanelConstants HashMap. */ ToolButton selectionToolButton = new ToolButton(this, "arrow.png", "Selection", "selection", "tooltip_selection"); selection = selectionToolButton.getToolButton(); addToolButton(selection, ElementsEdtActions.SELECTION); selection.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer)circuitPanelConstants.get(selection); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); /* End of button definition. */ ToolButton zoomToolButton = new ToolButton(this, "magnifier.png", "Zoom_p", "zoom", "tooltip_zoom"); zoom = zoomToolButton.getToolButton(); addToolButton(zoom, ElementsEdtActions.ZOOM); zoom.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(zoom); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); ToolButton handToolButton = new ToolButton(this, "move.png", "Hand", "hand", "tooltip_hand"); hand = handToolButton.getToolButton(); addToolButton(hand, ElementsEdtActions.HAND); hand.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(hand); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); ToolButton lineToolButton = new ToolButton(this, "line.png", "Line", "line", "tooltip_line"); line = lineToolButton.getToolButton(); addToolButton(line, ElementsEdtActions.LINE); line.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(line); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); ToolButton advtextToolButton = new ToolButton(this, "text.png", "Text", "text", "tooltip_text"); advtext = advtextToolButton.getToolButton(); addToolButton(advtext, ElementsEdtActions.TEXT); advtext.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(advtext); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); ToolButton bezierToolButton = new ToolButton(this, "bezier.png", "Bezier", "bezier", "tooltip_bezier"); bezier = bezierToolButton.getToolButton(); addToolButton(bezier, ElementsEdtActions.BEZIER); bezier.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(bezier); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); ToolButton polygonToolButton = new ToolButton(this, "polygon.png", "Polygon", "polygon", "tooltip_polygon"); polygon = polygonToolButton.getToolButton(); addToolButton(polygon, ElementsEdtActions.POLYGON); polygon.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(polygon); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); // TODO: add the description! ToolButton complexCurveToolButton = new ToolButton(this, "complexcurve.png", "Complexcurve", "complexcurve", "tooltip_curve"); complexcurve = complexCurveToolButton.getToolButton(); addToolButton(complexcurve, ElementsEdtActions.COMPLEXCURVE); complexcurve.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(complexcurve); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); ToolButton ellipseToolButton = new ToolButton(this, "ellipse.png", "Ellipse", "ellipse", "tooltip_ellipse"); ellipse = ellipseToolButton.getToolButton(); addToolButton(ellipse, ElementsEdtActions.ELLIPSE); ellipse.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(ellipse); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); ToolButton rectangleToolButton = new ToolButton(this, "rectangle.png", "Rectangle", "rectangle", "tooltip_rectangle"); rectangle = rectangleToolButton.getToolButton(); addToolButton(rectangle, ElementsEdtActions.RECTANGLE); rectangle.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(rectangle); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); ToolButton connectionToolButton = new ToolButton(this, "connection.png", "Connection", "connection", "tooltip_connection"); connection = connectionToolButton.getToolButton(); addToolButton(connection, ElementsEdtActions.CONNECTION); connection.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(connection); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); ToolButton pcblineToolButton = new ToolButton(this, "pcbline.png", "PCBline", "pcbline", "tooltip_pcbline"); pcbline = pcblineToolButton.getToolButton(); addToolButton(pcbline, ElementsEdtActions.PCB_LINE); pcbline.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(pcbline); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); ToolButton pcbpadToolButton = new ToolButton(this, "pcbpad.png", "PCBpad", "pcbpad", "tooltip_pcbpad"); pcbpad = pcbpadToolButton.getToolButton(); addToolButton(pcbpad, ElementsEdtActions.PCB_PAD); pcbpad.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { Integer circuitPanelConstantInteger = (Integer) circuitPanelConstants.get(pcbpad); int circuitPanelConstant = circuitPanelConstantInteger .intValue(); selectionListener. setSelectionState(circuitPanelConstant,""); } }); fileName=new JLabel(""); add(Box.createGlue()); add(fileName); add(Box.createGlue()); setFloatable(false); setRollover(true); } /** Add a selection listener (object implementing the ChangeSelection interface) whose change method will be called when the current selected action should be changed. @param c the change selection listener. */ public void addSelectionListener(ChangeSelectionListener c) { selectionListener=c; } /** This method finds the button selected at the moment. @return the selected button, or null if nothing is currently selected. */ public JToggleButton getSelectedButton() { for(JToggleButton button : toolButtonsList) { if (button.isSelected()) { return button; } } return null; } /** Get the current selection state. Required for implementing the ChangeSelectionListener interface. @return the actual selection state (see the CircuitPanel class for the definition of the constants used here). */ public int getSelectionState() { JToggleButton selectedButton = getSelectedButton(); if(selectedButton==null) { // No button is selected. There is a specific state for that. return ElementsEdtActions.NONE; } else { Integer circuitPanelConstantInteger = (Integer)circuitPanelConstants.get(selectedButton); return circuitPanelConstantInteger.intValue(); } } /** 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) { complexcurve.setEnabled(!strict); } /** Set the current selection state. Required for implementing the ChangeSelectionListener interface @param s the selection state (see the CircuitPanel class for the definition of the constants used here). @param m not used here (useful when playing with macros). */ public void setSelectionState(int s, String m) { for(JToggleButton button : toolButtonsList) { if(s == ElementsEdtActions.NONE || s == ElementsEdtActions.MACRO) { break; } Integer circuitPanelConstantInteger = (Integer)circuitPanelConstants.get(button); int circuitPanelConstant = circuitPanelConstantInteger.intValue(); if(s == circuitPanelConstant) { button.setSelected(true); } } } }
20,184
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MyTimer.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/timer/MyTimer.java
package net.sourceforge.fidocadj.timer; /** MyTimer.java Profiling class. **************************************************************************** Version History <pre> Version Date Author Remarks ------------------------------------------------------------------------------ 1.0 March 2007 D. Bucci First working version 1.1 December 2007 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> */ public class MyTimer { private final long start; /** Standard constructor. Time measurement begins from here. */ public MyTimer() { start = System.currentTimeMillis(); } /** Get the elapsed time from class construction. @return the elapsed time in milliseconds. Time resolution will depend on your operating system. */ public long getElapsed() { return System.currentTimeMillis() - start; } }
1,668
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/timer/package-info.java
/** Timing classes for profiling code execution. */ package net.sourceforge.fidocadj.timer;
94
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/macropicker/package-info.java
/** The macro picker tree on the right of the FidoCadJ application. */ package net.sourceforge.fidocadj.macropicker;
122
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
OperationPermissions.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/macropicker/OperationPermissions.java
package net.sourceforge.fidocadj.macropicker; /** Describe which permissions are available. <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> @author Kohta Ozaki, Davide Bucci */ public class OperationPermissions { public boolean copyAvailable; public boolean pasteAvailable; public boolean renameAvailable; public boolean removeAvailable; public boolean renKeyAvailable; /** Get the value of copyAvailable. @return true if it can be copied. */ public boolean isCopyAvailable() { return copyAvailable; } /** Get the value of pasteAvailable. @return true if the paste operation is possible */ public boolean isPasteAvailable() { return pasteAvailable; } /** Get the value of renameAvailable. @return true if it can be renamed. */ public boolean isRenameAvailable() { return renameAvailable; } /** Returns the value of removeAvailable. @return true if it can be removed/deleted. */ public boolean isRemoveAvailable() { return removeAvailable; } /** Returns the value of renKeyAvailable. @return true if its key can be changed. */ public boolean isRenKeyAvailable() { return renKeyAvailable; } /** Disable all permissions. */ public void disableAll() { copyAvailable=false; pasteAvailable=false; renameAvailable=false; removeAvailable=false; renKeyAvailable=false; } }
2,280
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
SearchField.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/macropicker/SearchField.java
package net.sourceforge.fidocadj.macropicker; import java.awt.*; import java.awt.event.*; import java.awt.font.LineMetrics; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import net.sourceforge.fidocadj.globals.Globals; /** * A text field for search/filter interfaces. The extra functionality includes * a placeholder string (when the user hasn't yet typed anything), and a button * to clear the currently-entered text. * * @author Elliott Hughes, Davide Bucci * http://elliotth.blogspot.com/2004/09/cocoa-like-search-field-for-java.html */ public final class SearchField extends JTextField implements FocusListener { private static final Border CANCEL_BORDER = new CancelBorder(); private boolean sendsNotificationForEachKeystroke = false; private static final boolean showingPlaceholderText = false; private boolean armed = false; private String placeholderText; /** Constructor. @param placeholderText the text to be shown as a placeholder when a search is not being done. */ public SearchField(String placeholderText) { super(15); putClientProperty("JTextField.style", "search"); putClientProperty("Quaqua.TextField.style", "search"); this.placeholderText = placeholderText; initBorder(); initKeyListener(); addFocusListener(this); } /** Standard constructor. The placeholder text will be "Search". */ public SearchField() { this("Search"); } /** We need to override the paintComponent method. For some reason, on MacOSX systems the background is not painted when the text field is rounded and appears like a standard search text field. This is quite embarassing when using an unified toolbar style like in Leopard and Snow Leopard. For this reason, here we paint the background if needed. @param g the graphic context to use. */ @Override public void paintComponent(Graphics g) { if(Globals.weAreOnAMac) { // This is useful only on Macintosh, since the text field shown is // rounded. Rectangle r = getBounds(); int x = r.x + 4; int y = r.y + 4; int width = r.width - 8; int height = r.height - 8; g.setColor(getBackground()); g.fillOval(x - 2, y, height, height); g.fillOval(x + width - height + 2, y, height, height); g.fillRect(x + height / 2, y, width - height, height); } // Once the new background is drawn, we can proceed with the rest of // the component. super.paintComponent(g); // At previous code, this document model had returned placeholder text // when waiting focus. // The model must be return zero length string in the situation. showPlaceHolder(g); } /** * Draws placeholder text. */ private void showPlaceHolder(Graphics g) { // It works fine on Windows. // Other environment have not been tested yet. int left; int bottom; float fontHeight; Font f; LineMetrics lm; // Get font height. f = g.getFont(); lm = f.getLineMetrics(placeholderText, g.getFontMetrics().getFontRenderContext()); fontHeight = lm.getHeight(); // Calculate text position. left = getBorder().getBorderInsets(this).left; bottom = (int) ((getHeight()-4) / 2.0 + fontHeight / 2.0); // Show placeholder text when focused. if (!isFocusOwner() && getText().length() == 0) { g.setColor(Color.GRAY); Graphics2D g2=(Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.drawString(placeholderText, left, bottom); } } private void initBorder() { setBorder(new CompoundBorder(getBorder(), CANCEL_BORDER)); MouseInputListener mouseInputListener = new CancelListener(); addMouseListener(mouseInputListener); addMouseMotionListener(mouseInputListener); setMaximumSize(new Dimension(5000, 30)); } /** Add a key listener */ private void initKeyListener() { addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { cancel(); } else if (sendsNotificationForEachKeystroke) { maybeNotify(); } } @Override public void keyPressed(KeyEvent e) { // If the search field has the focus, it will be the only // recipient of the key strokes (solves bug #50). // Do this only for R and S keys. // About this bug. // The top component takes all key events regardless of focus??? if(isFocusOwner() && (e.getKeyCode() == KeyEvent.VK_R || e.getKeyCode() == KeyEvent.VK_S)) { e.consume(); } } }); } private void cancel() { setText(""); postActionEvent(); } private void maybeNotify() { if (showingPlaceholderText) { return; } postActionEvent(); } /** Edit the send notification for each keystroke. @param eachKeystroke true if the property should be active. */ public void setSendsNotificationForEachKeystroke(boolean eachKeystroke) { this.sendsNotificationForEachKeystroke = eachKeystroke; } /** Draw the cancel button as a gray circle with a white cross inside. */ static class CancelBorder extends EmptyBorder { private static final Color GRAY = new Color(0.7f, 0.7f, 0.7f); /** Standard constructor. */ CancelBorder() { super(0, 20, 0, 15); } /** Paint the border of the button. @param c the component. @param gc the graphic context. @param x the x coordinate of the left side of the button. @param y the y coordinate of the top side of the button. @param width the width of the button. @param height the height of the button. */ @Override public void paintBorder(Component c, Graphics gc, int x, int y, int width, int height) { SearchField field = (SearchField) c; Graphics2D g = (Graphics2D) gc; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final int circleL = 14; final int lensX = x; final int lensY = y; final int lensL = 12; super.paintBorder(c, gc, x, y, width, height); g.setColor(Color.GRAY); g.fillOval(lensX, lensY, lensL, lensL); g.setStroke(new BasicStroke(3)); g.drawLine(lensX + lensL / 2, lensY + lensL / 2, lensX + circleL, lensY + circleL); g.setStroke(new BasicStroke(1)); g.setColor(Color.WHITE); g.fillOval(lensX + 2, lensY + 2, lensL - 4, lensL - 4); g.setColor(field.armed ? Color.GRAY : GRAY); if (field.showingPlaceholderText || field.getText().length() == 0) { return; } final int circleX = x + width - circleL; final int circleY = y + (height - 1 - circleL) / 2; g.setColor(field.armed ? Color.GRAY : GRAY); g.fillOval(circleX, circleY, circleL, circleL); final int lineL = circleL - 8; final int lineX = circleX + 4; final int lineY = circleY + 4; g.setColor(Color.WHITE); g.drawLine(lineX, lineY, lineX + lineL, lineY + lineL); g.drawLine(lineX, lineY + lineL, lineX + lineL, lineY); } } /** Handles a click on the cancel button by clearing the text and notifying any ActionListeners. */ class CancelListener extends MouseInputAdapter { private boolean isOverButton(MouseEvent e) { // If the button is down, we might be outside the component // without having had mouseExited invoked. if (!contains(e.getPoint())) { return false; } // In lieu of proper hit-testing for the circle, check that // the mouse is somewhere in the border. Rectangle innerArea = SwingUtilities.calculateInnerArea(SearchField.this, null); return !innerArea.contains(e.getPoint()); } @Override public void mouseDragged(MouseEvent e) { arm(e); } @Override public void mouseEntered(MouseEvent e) { arm(e); } @Override public void mouseExited(MouseEvent e) { disarm(); } @Override public void mousePressed(MouseEvent e) { arm(e); } @Override public void mouseReleased(MouseEvent e) { if (armed) { cancel(); } disarm(); } private void arm(MouseEvent e) { armed = isOverButton(e) && SwingUtilities.isLeftMouseButton(e); repaint(); } private void disarm() { armed = false; repaint(); } } /** For the FocusListener interface. The field gained focus. @param e the focus event. */ @Override public void focusGained(FocusEvent e) { repaint(); } /** For the FocusListener interface. The field lost focus. @param e the focus event. */ @Override public void focusLost(FocusEvent e) { repaint(); } }
10,233
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MacroTree.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/macropicker/MacroTree.java
package net.sourceforge.fidocadj.macropicker; import java.io.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.tree.*; import net.sourceforge.fidocadj.circuit.CircuitPanel; import net.sourceforge.fidocadj.circuit.controllers.ElementsEdtActions; import net.sourceforge.fidocadj.geom.DrawingSize; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.toolbars.ChangeSelectionListener; import net.sourceforge.fidocadj.librarymodel.LibraryModel; import net.sourceforge.fidocadj.librarymodel.Library; import net.sourceforge.fidocadj.librarymodel.Category; import net.sourceforge.fidocadj.layermodel.LayerModel; import net.sourceforge.fidocadj.librarymodel.event.LibraryListenerAdapter; import net.sourceforge.fidocadj.librarymodel.event.LibraryListener; import net.sourceforge.fidocadj.macropicker.model.MacroTreeModel; import net.sourceforge.fidocadj.primitives.MacroDesc; /** Library view component.<br> Features:<BR> Shows macros of libraries as tree and previews.<BR> Notice selected macro to related components.<BR> Provides interfaces of renaming, removing, moving and changing key for library.<BR> <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> @author Kohta Ozaki, Davide Bucci */ public class MacroTree extends JPanel { /** Indicates library */ public static final int LIBRARY = 0; /** Indicates category */ public static final int CATEGORY = 1; /** Indicates macro */ public static final int MACRO = 2; // View components. private ExpandableJTree treeComponent; private SearchField searchField; private CircuitPanel previewPanel; private JScrollPane treeScrollPane; // Models. private LibraryModel libraryModel; private LayerModel layerModel; private MacroTreeModel macroTreeModel; // A Listener for sending selected macro to CircuitPanel. private ChangeSelectionListener selectionListener; private java.util.List<ChangeListener> changeListeners; // NOPMD bug PMD? private TreePath copyTarget = null; private OperationPermissions permissionObject; /** Constructor. @param libraryModel library model. not null. @param layerModel layer model. not null. */ public MacroTree(LibraryModel libraryModel, LayerModel layerModel) { this.libraryModel = libraryModel; this.layerModel = layerModel; initComponents(); } /** 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(); } /** Initialize view components and relate models. */ private void initComponents() { JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.putClientProperty("JSplitPane.style","thick"); Box topBox = Box.createVerticalBox(); setLayout(new GridLayout(1, 0)); createListenerArray(); createTreeView(); createPreviewPanel(); createSearchField(); createPermissionObject(); createPopupMenu(); bindSearchField(); bindLibraryModel(); bindPreviewPanel(); topBox.add(searchField); topBox.add(treeScrollPane); splitPane.setTopComponent(topBox); splitPane.setBottomComponent(previewPanel); splitPane.setResizeWeight(0.9); add(splitPane); } /** Create the array of change listeners. */ private void createListenerArray() { changeListeners = new ArrayList<ChangeListener>(); } /** Add the provided change listener to the current pipeline. @param l the change listener to add. */ public void addChangeListener(ChangeListener l) { changeListeners.add(l); } /** Remove a change listener from the pipeline. @param l the change listener to remove. */ public void removeChangeListener(ChangeListener l) { changeListeners.remove(l); } /** Returns node type of selected. @return int A constant of LIBRARY or CATEGORY or MACRO or -1(other). */ public int getSelectedType() { TreePath path = treeComponent.getSelectionPath(); int type; if(path==null) { return -1; } type = macroTreeModel.getNodeType(path); switch(type) { case MacroTreeModel.LIBRARY: return LIBRARY; case MacroTreeModel.CATEGORY: return CATEGORY; case MacroTreeModel.MACRO: return MACRO; default: return -1; } } /** Removes library. @param library Library to remove. */ public void remove(Library library) { int result; if(library==null) { return; } result = JOptionPane.showConfirmDialog(null, Globals.messages.getString("remove_library_confirm")+ library.getName() + "?", Globals.messages.getString("remove_library"), JOptionPane.YES_NO_OPTION); if(result==JOptionPane.YES_OPTION) { try { libraryModel.remove(library); } catch (LibraryModel.IllegalLibraryAccessException e) { JOptionPane.showMessageDialog(null, e.getMessage(), Globals.messages.getString("error"), JOptionPane.ERROR_MESSAGE); } } } /** Removes category. @param category Category to remove. */ public void remove(Category category) { int result; if(category==null) { return; } result=JOptionPane.showConfirmDialog(null, Globals.messages.getString("remove_category_confirm")+ category.getName() + "?", Globals.messages.getString("remove_category"), JOptionPane.YES_NO_OPTION); if(result==JOptionPane.YES_OPTION) { try { libraryModel.remove(category); } catch (LibraryModel.IllegalLibraryAccessException e) { JOptionPane.showMessageDialog(null, e.getMessage(), Globals.messages.getString("error"), JOptionPane.ERROR_MESSAGE); } } } /** Remove macro. @param macro MacroDesc to remove. */ public void remove(MacroDesc macro) { int result; if(macro==null) { return; } result=JOptionPane.showConfirmDialog(null, Globals.messages.getString("remove_macro_confirm")+ macro.name + "?", Globals.messages.getString("remove_macro"), JOptionPane.YES_NO_OPTION); if(result==JOptionPane.YES_OPTION) { try { libraryModel.remove(macro); } catch (LibraryModel.IllegalLibraryAccessException e) { JOptionPane.showMessageDialog(null, e.getMessage(), Globals.messages.getString("error"), JOptionPane.ERROR_MESSAGE); } } } /** Renames macro. @param macro MacroDesc to rename. */ public void rename(MacroDesc macro) { String newName; if(macro==null) { return; } newName = JOptionPane.showInputDialog(null, Globals.messages.getString("new_macro_name"), macro.name); if(newName==null || newName.equals(macro.name)) { return; } try { libraryModel.rename(macro,newName); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), Globals.messages.getString("error"), JOptionPane.ERROR_MESSAGE); } } /** Rename a category. @param category Category to rename. */ public void rename(Category category) { String newName; if(category==null) { return; } newName = JOptionPane.showInputDialog(null, Globals.messages.getString("new_category_name"), category.getName()); if(newName==null || newName.equals(category.getName())) { return; } try { libraryModel.rename(category,newName); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), Globals.messages.getString("error"), JOptionPane.ERROR_MESSAGE); } } /** Renames a library. @param library Library to rename. */ public void rename(Library library) { String newName; if(library==null) { return; } newName = JOptionPane.showInputDialog(null, Globals.messages.getString("new_library_name"), library.getName()); if(newName==null || newName.equals(library.getName())) { return; } try { libraryModel.rename(library,newName); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), Globals.messages.getString("error"), JOptionPane.ERROR_MESSAGE); } } /** Ask to the user to change the key of the given macro. @param macro the macro to be modified. */ public void changeKey(MacroDesc macro) { String oldKey; String newKey; if(macro==null) { return; } int n = JOptionPane.showConfirmDialog(null, Globals.messages.getString("ChangeKeyWarning"), Globals.messages.getString("RenKey"), JOptionPane.YES_NO_OPTION); if(n==JOptionPane.NO_OPTION) { return; } oldKey = LibraryModel.getPlainMacroKey(macro); newKey = JOptionPane.showInputDialog(null, Globals.messages.getString("Key"), oldKey); if(newKey==null || newKey.equals(oldKey)) { return; } try { libraryModel.changeKey(macro,newKey); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), Globals.messages.getString("error"), JOptionPane.ERROR_MESSAGE); } } /** Called during a copy operation. Makes sort that the currently selected node will become the target for the copy. */ public void setSelectedNodeToCopyTarget() { copyTarget = treeComponent.getSelectionPath(); } /** Paste into the currently selected node. */ public void pasteIntoSelectedNode() { if(copyTarget==null){ return; } int copyTargetType = macroTreeModel.getNodeType(copyTarget); int selectedNodeType = getSelectedType(); if(copyTargetType==MacroTreeModel.CATEGORY && selectedNodeType==LIBRARY) { copyCategoryIntoLibrary(); } else if(copyTargetType==MacroTreeModel.MACRO && selectedNodeType==CATEGORY) { copyMacroIntoCategory(); } copyTarget = null; updateOperationPermission(); } /** Copy a category (which has been previously selected). */ private void copyCategoryIntoLibrary() { Category targetCategory; Library destLibrary; destLibrary = getSelectedLibrary(); targetCategory = macroTreeModel.getCategory(copyTarget); libraryModel.copy(targetCategory,destLibrary); } /** Copy a macro into a selected category. */ private void copyMacroIntoCategory() { MacroDesc targetMacro; Category destCategory; destCategory = getSelectedCategory(); targetMacro = macroTreeModel.getMacro(copyTarget); libraryModel.copy(targetMacro, destCategory); } /** Create the object describing permissions. */ private void createPermissionObject() { permissionObject = new OperationPermissions(); } /** Get a permission description object. @return the permission descriptor. */ public OperationPermissions getOperationPermission() { return permissionObject; } /** Update the permission descriptor. */ private void updateOperationPermission() { int selectedType; int copyTargetType; Library lib = getSelectedLibrary(); permissionObject.disableAll(); selectedType = getSelectedType(); //copy permission if(selectedType==CATEGORY || selectedType==MACRO) { permissionObject.copyAvailable = true; } if(!macroTreeModel.isSearchMode()) { //paste permission if(copyTarget!=null && lib!=null && !lib.isStdLib()){ copyTargetType = macroTreeModel.getNodeType(copyTarget); if(copyTargetType==MacroTreeModel.CATEGORY && selectedType==LIBRARY) { permissionObject.pasteAvailable = true; } else if (copyTargetType==MacroTreeModel.MACRO && selectedType==CATEGORY) { permissionObject.pasteAvailable = true; } } //rename/renkey permission if(lib!=null && !lib.isStdLib()) { permissionObject.renameAvailable = true; permissionObject.removeAvailable = true; if(selectedType==MACRO) { permissionObject.renKeyAvailable = true; } } } } /** Create the popup menu. */ private void createPopupMenu() { MacroTreePopupMenu popupMenu = new MacroTreePopupMenu(this); treeComponent.setComponentPopupMenu(popupMenu); addChangeListener(popupMenu); } /** Relate preview panel and JTree selection model.<br> Relate preview panel and library model. */ private void bindPreviewPanel() { // Relate with JTree. treeComponent.getSelectionModel(). addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { MacroDesc md; md = macroTreeModel.getMacro(e.getPath()); if(md!=null) { previewPanel.getParserActions().parseString( new StringBuffer(md.description)); MapCoordinates m = DrawingSize.calculateZoomToFit( previewPanel.dmp, previewPanel.getSize().width*85/100, previewPanel.getSize().height*85/100, true); m.setXCenter(-m.getXCenter()+10); m.setYCenter(-m.getYCenter()+10); previewPanel.setMapCoordinates(m); previewPanel.repaint(); } } }); // Relate with library model. LibraryListener l = new LibraryListenerAdapter() { public void libraryLoaded() { previewPanel.dmp.setLibrary(libraryModel.getAllMacros()); } }; libraryModel.addLibraryListener(l); } /** Sets the listener for selecting macro. @param l the new listener. It should not be null. */ public void setSelectionListener(ChangeSelectionListener l) { selectionListener=l; treeComponent.getSelectionModel(). addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { MacroDesc md; if (selectionListener!=null) { md = macroTreeModel.getMacro(e.getPath()); if(md==null){ selectionListener.setSelectionState( ElementsEdtActions.SELECTION, ""); } else { selectionListener.setSelectionState( ElementsEdtActions.MACRO, md.key); } } } }); } /** * Relate tree model and library model.<br> */ private void bindLibraryModel() { macroTreeModel = new MacroTreeModel(libraryModel); treeComponent.setModel((TreeModel)macroTreeModel); libraryModel.addLibraryListener(macroTreeModel); } /** * Create JTree with scroll pane. */ private void createTreeView() { treeComponent = new ExpandableJTree(); treeComponent.setCellRenderer(new MacroTreeCellRenderer()); treeComponent.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION); treeScrollPane = new JScrollPane(treeComponent); treeScrollPane.setMinimumSize(new Dimension(150, 100)); treeScrollPane.setPreferredSize(new Dimension(350, 600)); treeComponent.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { updateOperationPermission(); for(ChangeListener l:changeListeners) { l.stateChanged(new ChangeEvent(this)); } } }); } /** * Create search bar. */ private void createSearchField() { // I think this must be initialized with localized label string // means search. searchField = new SearchField(); } /** * Create preview panel. */ private void createPreviewPanel() { previewPanel = new CircuitPanel(false); previewPanel.dmp.setLayers(layerModel.getAllLayers()); previewPanel.dmp.setLibrary(libraryModel.getAllMacros()); previewPanel.setGridVisibility(false); previewPanel.setMinimumSize(new Dimension(150, 100)); previewPanel.setPreferredSize(new Dimension(350, 300)); } /** * Relate document model of search bar and tree model. */ private void bindSearchField() { DocumentListener searchFieldListener = new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { // Nothing to do } @Override public void removeUpdate(DocumentEvent e) { setWord(e); } @Override public void insertUpdate(DocumentEvent e) { setWord(e); } private void setWord(DocumentEvent e) { String word = null; Document d = e.getDocument(); try { word = d.getText(0, d.getLength()); } catch (BadLocationException ex) { word = ""; System.out.println( "[SearchFieldListener] BadLocationException"); } finally { if("".equals(word)) { treeComponent.collapseOnce(); } else { treeComponent.expandOnce(); } macroTreeModel.setFilterWord(word); } } }; searchField.getDocument().addDocumentListener(searchFieldListener); searchField.addKeyListener(new KeyListener() { @Override public void keyPressed(KeyEvent e) { // Nothing to do } @Override public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER) { if(e.isShiftDown()) { treeComponent.selectPrevLeaf(); } else { treeComponent.selectNextLeaf(); } } } @Override public void keyTyped(KeyEvent e) { // Nothing to do } }); } /** Set the current model for the library. @param libraryModel the library model to employ. */ public void setLibraryModel(LibraryModel libraryModel) { this.libraryModel = libraryModel; previewPanel.dmp.setLibrary(libraryModel.getAllMacros()); bindSearchField(); } /** Set the current layer model. @param layerModel the layer model. */ public void setLayerModel(LayerModel layerModel) { this.layerModel = layerModel; previewPanel.dmp.setLayers(layerModel.getAllLayers()); } /** Get the currently selected macro. @return the selected macro, or null if no macro is selected. */ public MacroDesc getSelectedMacro() { TreePath path = treeComponent.getSelectionPath(); if(path==null) { return null; } return macroTreeModel.getMacro(path); } /** Get the currently selected category. @return the selected category, or null if no category is selected. */ public Category getSelectedCategory() { TreePath path = treeComponent.getSelectionPath(); if(path==null) { return null; } return macroTreeModel.getCategory(path); } /** Get the currently selected library. @return the selected library, or null if no library is selected. */ public Library getSelectedLibrary() { TreePath path = treeComponent.getSelectionPath(); if(path==null) { return null; } return macroTreeModel.getLibrary(path); } }
23,450
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MacroTreeCellRenderer.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/macropicker/MacroTreeCellRenderer.java
package net.sourceforge.fidocadj.macropicker; import java.awt.*; import javax.swing.*; import javax.swing.tree.*; import net.sourceforge.fidocadj.macropicker.model.MacroTreeNode; /** The cell renderer: show the appropriate icon. <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> @author Kohta Ozaki, Davide Bucci */ public class MacroTreeCellRenderer extends DefaultTreeCellRenderer { /** Create a component able to generate a rendered apt to show the elements in the Macro Tree. In our version, the value is checked and if it is an instance of MacroTreeNode, it contains an icon which is retrieved and employed to show the state of the node. @param tree the tree on which the renderer should be employed. @param value the MacroTreeNode to render @param sel true if selected. @param expanded true if expanded. @param leaf true if it is a leaf. @param row the row index. @param hasFocus true if it has focus. */ @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component c = super.getTreeCellRendererComponent( tree, value, sel, expanded, leaf, row, hasFocus); if(value instanceof MacroTreeNode) { Icon icon = ((MacroTreeNode)value).getIcon(); if(icon == null) { return c; } else { setIcon(icon); } } return this; } }
2,448
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ExpandableJTree.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/macropicker/ExpandableJTree.java
package net.sourceforge.fidocadj.macropicker; import javax.swing.*; import javax.swing.tree.*; import java.awt.*; /** Extended JTree for searching node.<BR> Features:<BR> Expands or collapses all nodes on paint event if specified.<BR> Selects leaf cyclic.<BR> <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> @author Kohta Ozaki, Davide Bucci */ public final class ExpandableJTree extends JTree { // runOnce = true means that a change in the expansion state of the tree // has been requested and it should be taken into account during the next // painting event. private boolean runOnce = false; // direction = true means that during the next repaint the tree should be // expanded. private boolean direction = false; /** The creator. */ public ExpandableJTree() { super(); // Apply a correction for the text size depending on the screen // resolution. final int base=114; int res=Toolkit.getDefaultToolkit().getScreenResolution(); Font standardFont=getFont(); setFont(standardFont.deriveFont(standardFont.getSize()*res/base)); setRowHeight(getRowHeight()*res/base); } private void fillExpandState(boolean expand) { //NOTES: //This only switchs expand state. //Actually expanding/collapsing tree is on next repaint. TreePath path; for(int row=0; row<getRowCount(); ++row) { path = getPathForRow(row); if(!getModel().isLeaf(path.getLastPathComponent())) { setExpandedState(path, expand); } } } /** During the next repaint of the JTree, nodes will be expanded. */ public void expandOnce() { runOnce = true; direction = true; } /** During the next repaint of the JTree, nodes will be collapsed. */ public void collapseOnce() { runOnce = true; direction = false; } /** Select the next leaf, i.e. the one immediately after the one which is currently selected. If this is not possible (for example because the currently selected leaf is the last one available), it does nothing. */ public void selectNextLeaf() { int nextRow = searchNextLeaf(true); if(0 <= nextRow && nextRow < getRowCount()) { setSelectionRow(nextRow); scrollRowToVisible(nextRow); } } /** Select the previous leaf, i.e. the one immediately above the one which is currently selected. If this is not possible (for example because the currently selected leaf is the first one available), it does nothing. */ public void selectPrevLeaf() { int nextRow = searchNextLeaf(false); if(0 <= nextRow && nextRow < getRowCount()) { setSelectionRow(nextRow); scrollRowToVisible(nextRow); } } /** Get the currently selected row in the JTree. If more than one selected row is present, return the index of the first one found. @return the index of the first selected row, or -1 if no selection is available. */ private int getSelectedRow() { int selectedRow = -1; int[] selectedRows; selectedRows = getSelectionRows(); if(selectedRows == null || selectedRows.length == 0) { selectedRow = -1; } else { selectedRow = selectedRows[0]; } return selectedRow; } /** Search for the next leaf in a tree. @param searchForward true if the search is in the forward direction, false otherwise. @return the index (row number) of the next leaf, or -1 if no leaf has been found. */ private int searchNextLeaf(boolean searchForward) { int nextRow = getSelectedRow(); for(int i=0;i<getRowCount();i++){ if(searchForward){ nextRow++; } else { nextRow--; } // Circular search if(nextRow < 0){ nextRow = getRowCount(); continue; } else if(getRowCount() <= nextRow){ nextRow = -1; continue; } if(getModel().isLeaf(getPathForRow(nextRow). getLastPathComponent())) { return nextRow; } } return -1; } /** Standard method for painting the node. Determines wether the nodes should be expanded or not. @param g the graphics context. */ @Override public void paint(Graphics g) { if(runOnce) { fillExpandState(direction); runOnce = false; } super.paint(g); } }
5,598
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MacroTreePopupMenu.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/macropicker/MacroTreePopupMenu.java
package net.sourceforge.fidocadj.macropicker; import java.awt.event.*; import java.io.*; import javax.swing.*; import javax.swing.event.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.librarymodel.Library; import net.sourceforge.fidocadj.librarymodel.Category; import net.sourceforge.fidocadj.primitives.MacroDesc; /** PopupMenu for MacroTree.<BR> This class checks the appropriate menu state for items by OperationPermission class of MacroTree. <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> @author Kohta Ozaki, Davide Bucci */ public class MacroTreePopupMenu extends JPopupMenu implements ChangeListener { final private MacroTree macroTree; // Element employed to check the kind of actions which can be done on // an element (permissions). final private OperationPermissions permission; final private JMenuItem copyMenu; final private JMenuItem pasteMenu; final private JMenuItem renameMenu; final private JMenuItem removeMenu; final private JMenuItem renkeyMenu; /** Create the popupmenu. @param macroTree the tree on which the menu has to be associated. */ public MacroTreePopupMenu(MacroTree macroTree) { this.macroTree = macroTree; permission = macroTree.getOperationPermission(); copyMenu = new JMenuItem(Globals.messages.getString("Copy")); pasteMenu = new JMenuItem(Globals.messages.getString("Paste")); removeMenu = new JMenuItem(Globals.messages.getString("Delete")); renameMenu = new JMenuItem(Globals.messages.getString("Rename")); renkeyMenu = new JMenuItem(Globals.messages.getString("RenKey")); this.add(copyMenu); this.add(pasteMenu); this.add(removeMenu); this.add(renameMenu); this.add(renkeyMenu); copyMenu.addActionListener(createCopyActionListener()); pasteMenu.addActionListener(createPasteActionListener()); removeMenu.addActionListener(createRemoveActionListener()); renameMenu.addActionListener(createRenameActionListener()); renkeyMenu.addActionListener(createRenkeyActionListener()); } /** 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(); } /** Update all the "enabled" states of the menu items, depending on which element is currently selected. @param e the event change object. */ @Override public void stateChanged(ChangeEvent e) { copyMenu.setEnabled(permission.isCopyAvailable()); pasteMenu.setEnabled(permission.isPasteAvailable()); removeMenu.setEnabled(permission.isRemoveAvailable()); renameMenu.setEnabled(permission.isRenameAvailable()); renkeyMenu.setEnabled(permission.isRenKeyAvailable()); } /** Create an action listener associated to the menu, reacting to the different elements presented. This action listener is associated to the renaming action. @return the ActionListener created by the routine. */ private ActionListener createRenameActionListener() { final MacroTree mt = macroTree; return new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { switch(mt.getSelectedType()) { case MacroTree.MACRO: MacroDesc m = mt.getSelectedMacro(); if(m!=null){ mt.rename(m); } break; case MacroTree.CATEGORY: Category c = mt.getSelectedCategory(); if(c!=null){ mt.rename(c); } break; case MacroTree.LIBRARY: Library l = mt.getSelectedLibrary(); if(l!=null){ mt.rename(l); } break; default: break; } } }; } /** Create an action listener associated to the menu, reacting to the different elements presented. This action listener is associated to the delete/remove action on an element. @return the ActionListener created by the routine. */ private ActionListener createRemoveActionListener() { final MacroTree mt = macroTree; return new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { switch(mt.getSelectedType()) { case MacroTree.MACRO: MacroDesc m = mt.getSelectedMacro(); if(m!=null){ mt.remove(m); } break; case MacroTree.CATEGORY: Category c = mt.getSelectedCategory(); if(c!=null){ mt.remove(c); } break; case MacroTree.LIBRARY: Library l = mt.getSelectedLibrary(); if(l!=null){ mt.remove(l); } break; default: break; } } }; } /** Create an action listener associated to the menu, reacting to the different elements presented. This action listener is associated to the action of changing the key of a macro. It does not have any effect on categories or libraries since there is no key associated to them. @return the ActionListener created by the routine. */ private ActionListener createRenkeyActionListener() { final MacroTree mt = macroTree; return new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { switch(mt.getSelectedType()) { case MacroTree.MACRO: MacroDesc m = mt.getSelectedMacro(); if(m!=null){ mt.changeKey(m); } break; case MacroTree.CATEGORY: //NOP break; case MacroTree.LIBRARY: //NOP break; default: break; } } }; } /** Create an action listener associated to the menu, reacting to the different elements presented. This action listener is associated to the copy action. @return the ActionListener created by the routine. */ private ActionListener createCopyActionListener() { final MacroTree mt = macroTree; return new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { mt.setSelectedNodeToCopyTarget(); } }; } /** Create an action listener associated to the menu, reacting to the different elements presented. This action listener is associated to the paste action. @return the ActionListener created by the routine. */ private ActionListener createPasteActionListener() { final MacroTree mt = macroTree; return new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { mt.pasteIntoSelectedNode(); } }; } }
8,959
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MacroTreeModel.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/macropicker/model/MacroTreeModel.java
package net.sourceforge.fidocadj.macropicker.model; import java.util.*; import javax.swing.event.*; import javax.swing.tree.*; import javax.swing.*; import javax.swing.plaf.metal.MetalIconFactory; import net.sourceforge.fidocadj.librarymodel.LibraryModel; import net.sourceforge.fidocadj.librarymodel.Library; import net.sourceforge.fidocadj.librarymodel.Category; 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.primitives.MacroDesc; /** JTree model for showing macro 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> @author Kohta Ozaki, Davide Bucci */ public class MacroTreeModel implements TreeModel,LibraryListener { public static final int ROOT=0; public static final int LIBRARY=1; public static final int CATEGORY=2; public static final int MACRO=3; private RootNode rootNode; final private LibraryModel libraryModel; final private List<TreeModelListener> listeners; private Map<TreePath, AbstractMacroTreeNode> libraryNodeMap; private String filterWord; /** Constructor. @param libraryModel the library model to be associated to this class. */ public MacroTreeModel(LibraryModel libraryModel) { this.libraryModel = libraryModel; listeners = new ArrayList<TreeModelListener>(); createMap(); synchronizeTree(null); fireChanged(); } /** Set filtering word. @param filterWord words separated by space. */ public void setFilterWord(String filterWord) { this.filterWord = filterWord; if(filterWord == null || filterWord.length()==0) { synchronizeTree(null); this.filterWord = null; fireChanged(); } else { Locale lo = new Locale("en"); final String chainedWord = filterWord.toLowerCase(lo); synchronizeTree(new NodeFilterInterface() { public boolean accept(MacroTreeNode node) { String[] words = chainedWord.trim().split(" "); int matched=0; for(String word:words) { if(0<=node.toString().toLowerCase(lo).indexOf(word)) { matched++; } else if(word.length()==0) { matched++; } } return words.length==matched; } }); fireChanged(); } } /** Reset the current search mode. */ private void resetSearchMode() { filterWord = null; } /** Check if a search is currently being made. @return true if a search is active. */ public boolean isSearchMode() { return filterWord != null; } /** Create the map of nodes constituting the library. */ private void createMap() { libraryNodeMap = new HashMap<TreePath, AbstractMacroTreeNode>(); } /** Get the type of the specified node. @param path the node to analyze. @return the kind of the node: ROOT, LIBRARY, CATEGORY, MACRO or -1 if the type could not be retrieved. */ public int getNodeType(TreePath path) { Object o; if(path==null) { return -1; } o = path.getLastPathComponent(); if(o instanceof RootNode) { return ROOT; } else if(o instanceof LibraryNode) { return LIBRARY; } else if(o instanceof CategoryNode) { return CATEGORY; } else if(o instanceof MacroNode) { return MACRO; } return -1; } /** Return filtering word. @return null or filtering word. */ public String getFilterWord() { return filterWord; } /** Implements TreeModel interface. Add a tree model listener. @param l the tree model listener. */ @Override public void addTreeModelListener(TreeModelListener l) { listeners.add(l); } /** Implements TreeModel interface . Get the child object. @param parent the parent object. @param index the index of the child. @return the child object retrieved. */ @Override public Object getChild(Object parent, int index) { return ((TreeNode)parent).getChildAt(index); } /** Implements TreeModel interface. Get the number of children. @param parent the parent object. @return the number of the children. */ @Override public int getChildCount(Object parent) { return ((TreeNode)parent).getChildCount(); } /** Implements TreeModel interface. Get the index of the given child. @param parent the parent object. @param child the child to search for. @return the index of the child or -1 if the child has not been found. TODO: check if it is true that it is -1... */ @Override public int getIndexOfChild(Object parent, Object child) { return ((TreeNode)parent).getIndex((TreeNode)child); } /** Implements TreeModel interface. Get the root node. @return the root node. */ @Override public Object getRoot() { return rootNode; } /** Implements TreeModel interface. Check if the given node is a leaf. @param node the node to check. @return true if the node is a leaf (in this context, a macro). */ @Override public boolean isLeaf(Object node) { return ((TreeNode)node).isLeaf(); } /** Implements TreeModel interface. Remove the given listener. @param l the listener to remove. */ @Override public void removeTreeModelListener(TreeModelListener l) { listeners.remove(l); } /** Implements TreeModel interface. TODO: improve the documentation. What is that supposed to do? Is the implementation complete in the code? @param path the path. @param newValue the new value. */ @Override public void valueForPathChanged(TreePath path, Object newValue) { // NOP } /** Get a certain macro (leaf in this context). @param path the path where the macro has to be searched for. @return the macro. */ public MacroDesc getMacro(TreePath path) { Object o; if(path==null) { return null; } o = getPathComponentAt(path,3); if(o instanceof MacroNode) { return ((MacroNode)o).getMacro(); } else { return null; } } /** Get a certain category. @param path the path where the category has to be searched for. @return the category. */ public Category getCategory(TreePath path) { Object o; if(path==null) { return null; } o = getPathComponentAt(path,2); if(o instanceof CategoryNode) { return ((CategoryNode)o).getCategory(); } else { return null; } } /** Get a certain library. @param path the path where the library has to be searched for. @return the library. */ public Library getLibrary(TreePath path) { Object o; if(path==null) { return null; } o = getPathComponentAt(path,1); if(o instanceof LibraryNode) { return ((LibraryNode)o).getLibrary(); } else { return null; } } private Object getPathComponentAt(TreePath path,int index) { if(index <= path.getPathCount()-1) { return path.getPathComponent(index); } else { return null; } } /** Notify that the tree has changed and it requires a refresh. */ private void fireChanged() { for(TreeModelListener l:listeners) { l.treeStructureChanged(new TreeModelEvent((Object)this, new TreePath(rootNode),null,null)); } } private TreePath createAbsolutePath(TreeNode lastNode) { TreeNode parentNode = lastNode.getParent(); if(parentNode==null){ return new TreePath(lastNode); } else { return createAbsolutePath(parentNode).pathByAddingChild(lastNode); } } /** Called when a library node has to be renamed. @param e the rename event. */ public void libraryNodeRenamed(RenameEvent e) { Object renamedNode = e.getRenamedNode(); TreePath renamedPath; TreeNode renamedMacroTreeNode; if(renamedNode==null) { fireTreeNodeChanged(new TreePath(rootNode)); } else { for(TreePath path:(Set<TreePath>)libraryNodeMap.keySet()){ if(path.getLastPathComponent().equals(renamedNode)){ renamedMacroTreeNode = (TreeNode)libraryNodeMap.get(path); renamedPath = createAbsolutePath(renamedMacroTreeNode); fireTreeNodeChanged(renamedPath); } } } } /** Called when a library node has to be removed. @param e the ermove event. */ public void libraryNodeRemoved(RemoveEvent e) { Object parentNode; TreePath parentPath; TreeNode parentMacroTreeNode; resetSearchMode(); synchronizeTree(null); parentNode = e.getParentNode(); if(parentNode==null) { fireTreeStructureChanged(new TreePath(rootNode)); } else { for(TreePath path:(Set<TreePath>)libraryNodeMap.keySet()){ if(path.getLastPathComponent().equals(parentNode)){ parentMacroTreeNode = (TreeNode)libraryNodeMap.get(path); parentPath = createAbsolutePath(parentMacroTreeNode); fireTreeStructureChanged(parentPath); } } } } /** Called when a library node has to be daded. @param e the add event. */ public void libraryNodeAdded(AddEvent e) { Object parentNode; TreePath parentPath; TreeNode parentMacroTreeNode; resetSearchMode(); synchronizeTree(null); parentNode = e.getParentNode(); if(parentNode==null) { fireTreeStructureChanged(new TreePath(rootNode)); } else { for(TreePath path:(Set<TreePath>)libraryNodeMap.keySet()){ if(path.getLastPathComponent().equals(parentNode)){ parentMacroTreeNode = (TreeNode)libraryNodeMap.get(path); parentPath = createAbsolutePath(parentMacroTreeNode); fireTreeStructureChanged(parentPath); } } } } /** Called when a library node has to be changed. TODO: is this unimplemented? @param e the changed event. */ public void libraryNodeKeyChanged(KeyChangeEvent e) { // Nothing to do here } /** To be called when a new library has been loaded. */ public void libraryLoaded() { resetSearchMode(); synchronizeTree(null); fireChanged(); } private void fireTreeNodeChanged(TreePath path) { if(path!=null) { for(TreeModelListener l:listeners) { l.treeNodesChanged(new TreeModelEvent(this, path)); } } } private void fireTreeStructureChanged(TreePath path) { if(path!=null){ for(TreeModelListener l:listeners) { l.treeStructureChanged(new TreeModelEvent(this, path)); } } } /** Performs a synchronization of the library tree with the current contents of the library model. It can be called when a research is done, to obtain the results shown in the tree. @param filter filtering rules to be applied. */ private void synchronizeTree(NodeFilterInterface filter) { LibraryNode ln; CategoryNode cn; MacroNode mn; TreePath libraryPath; TreePath categoryPath; TreePath macroPath; // Save a copy of the current library note Map<TreePath,AbstractMacroTreeNode> tmpMap =libraryNodeMap; libraryNodeMap = new HashMap<TreePath, AbstractMacroTreeNode>(); if(rootNode==null) { rootNode = new RootNode(); } if(filter==null) { rootNode.setLabel("FidoCadJ"); } else { rootNode.setLabel("Search results..."); } rootNode.clearChildNodes(); for(Library library:libraryModel.getAllLibraries()) { libraryPath = new TreePath(library); if(libraryNodeMap.containsKey(libraryPath)){ ln = (LibraryNode)tmpMap.get(libraryPath); ln.clearChildNodes(); } else { ln = new LibraryNode(library); } for(Category category:library.getAllCategories()) { if(category.isHidden()) { continue; } categoryPath = libraryPath.pathByAddingChild(category); if(tmpMap.containsKey(categoryPath)){ cn = (CategoryNode)tmpMap.get(categoryPath); cn.clearChildNodes(); } else { cn = new CategoryNode(category); } for(MacroDesc macro:category.getAllMacros()) { macroPath = categoryPath.pathByAddingChild(macro); if(tmpMap.containsKey(macroPath)){ mn = (MacroNode)tmpMap.get(macroPath); } else { mn = new MacroNode(macro); } if(filter!=null && !filter.accept(mn)) { // If the search hasn't been successful, don't show the // current macro in the category. continue; } cn.addMacroNode(mn); libraryNodeMap.put(macroPath,mn); } if(filter!=null && cn.getChildCount()==0) { // If the no macros are to be shown, don't show the // current category in the library. continue; } ln.addCategoryNode(cn); libraryNodeMap.put(categoryPath,cn); } if(filter!=null && ln.getChildCount()==0) { // If no categories are to be shown, don't show the // current library. continue; } rootNode.addLibraryNode(ln); libraryNodeMap.put(libraryPath,ln); } rootNode.sortTree(); } private static class RootNode extends AbstractMacroTreeNode { RootNode() { parent = null; label = "FidoCadJ"; icon = MetalIconFactory.getTreeComputerIcon(); } RootNode(String label) { parent=null; this.label=label; icon = MetalIconFactory.getTreeComputerIcon(); } RootNode(String label,Icon icon) { parent=null; this.label=label; this.icon = icon; } public void addLibraryNode(LibraryNode node) { childNodes.add(node); node.setParent((TreeNode)this); } public void setLabel(String label) { this.label = label; } } private static class LibraryNode extends AbstractMacroTreeNode implements Comparable<LibraryNode> { final private Library library; LibraryNode(Library library) { this.library = library; if(library.isStdLib()) { icon = MetalIconFactory.getTreeHardDriveIcon(); } else { icon = MetalIconFactory.getTreeFloppyDriveIcon(); } } public Library getLibrary() { return library; } public void addCategoryNode(CategoryNode node) { childNodes.add(node); node.setParent((TreeNode)this); } @Override public int compareTo(LibraryNode node) { Library l1 = this.library; Library l2 = node.getLibrary(); if(l1.isStdLib() == l2.isStdLib()) { return l1.getName().compareToIgnoreCase(l2.getName()); } else { if(l1.isStdLib()) { return -1; } else { return 1; } } } /** Convert to string. @return the name of the node. */ @Override public String toString() { return library.getName(); } /** Inherit the behavior of compareTo. */ @Override public boolean equals(Object node) { return node instanceof LibraryNode && compareTo((LibraryNode)node)==0; } /** No implementation of the hashCode for the moment @return 42, because it is The Answer. */ @Override public int hashCode() { assert false : "hashCode not designed"; return 42; // any arbitrary constant will do } } private static class CategoryNode extends AbstractMacroTreeNode implements Comparable<CategoryNode> { final private Category category; CategoryNode(Category category) { this.category = category; icon = null; } public Category getCategory() { return category; } public void addMacroNode(MacroNode node) { childNodes.add(node); node.setParent((TreeNode)this); } @Override public int compareTo(CategoryNode node) { Category c1 = this.category; Category c2 = node.getCategory(); return c1.getName().compareToIgnoreCase(c2.getName()); } @Override public String toString() { return category.getName(); } /** Inherit the behavior of compareTo. */ @Override public boolean equals(Object node) { return node instanceof CategoryNode && compareTo((CategoryNode)node)==0; } /** No implementation of the hashCode for the moment @return 42, because it is The Answer. */ @Override public int hashCode() { assert false : "hashCode not designed"; return 42; // any arbitrary constant will do } } private static class MacroNode extends AbstractMacroTreeNode implements Comparable<MacroNode> { final MacroDesc macro; MacroNode(MacroDesc macroDesc) { this.macro = macroDesc; icon = null; } public MacroDesc getMacro() { return macro; } @Override public boolean isLeaf() { return true; } /** Compare two nodes. The comparison is done with respect to the name and if the name is equal, then the key is compared too. */ @Override public int compareTo(MacroNode node) { MacroDesc m1 = this.macro; MacroDesc m2 = node.getMacro(); // At first, compare the two nodes using their name int r=m1.name.compareToIgnoreCase(m2.name); // If they have the same name, look at the keys. if(r==0) { r=m1.key.compareToIgnoreCase(m2.key); } return r; } @Override public String toString() { return macro.name; } /** Inherit the behavior of compareTo. */ @Override public boolean equals(Object node) { return node instanceof MacroNode && compareTo((MacroNode)node)==0; } /** No implementation of the hashCode for the moment @return 42, because it is The Answer. */ @Override public int hashCode() { assert false : "hashCode not designed"; return 42; // any arbitrary constant will do } } }
21,652
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/macropicker/model/package-info.java
/** Classes for handling the database (model) of the nodes in the macro picker tree. */ package net.sourceforge.fidocadj.macropicker.model;
149
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
NodeFilterInterface.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/macropicker/model/NodeFilterInterface.java
package net.sourceforge.fidocadj.macropicker.model; /** Interface for implementing filtering of the shown nodes. <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> @author Kohta Ozaki, Davide Bucci */ public interface NodeFilterInterface { /** Specify if a node has to be filtered in or not. @param node the node to be checked. @return true if the node is accepted. */ boolean accept(MacroTreeNode node); }
1,182
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MacroTreeNode.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/macropicker/model/MacroTreeNode.java
package net.sourceforge.fidocadj.macropicker.model; import javax.swing.*; import javax.swing.tree.*; /** Extended interface of JTree node for showing macros. <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> @author Kohta Ozaki, Davide Bucci */ public interface MacroTreeNode extends TreeNode { /** Sort child nodes. This must be called recursively. */ void sortTree(); /** Return icon for identifying node type. @return the icon. */ Icon getIcon(); /** Return string for label. @return the text label. */ @Override String toString(); }
1,350
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
AbstractMacroTreeNode.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/macropicker/model/AbstractMacroTreeNode.java
package net.sourceforge.fidocadj.macropicker.model; import java.util.*; import javax.swing.*; import javax.swing.tree.*; /** Abstract class for MacroTreeNode. <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> @author Kohta Ozaki, Davide Bucci */ public abstract class AbstractMacroTreeNode implements MacroTreeNode { protected Vector<AbstractMacroTreeNode> childNodes; // NOPMD protected TreeNode parent; protected String label; // The description of the node protected Icon icon; /** Standard constructor. */ AbstractMacroTreeNode() { childNodes = new Vector<AbstractMacroTreeNode>(); label=""; } /** Implements TreeNode interface. Get the children nodes. @return the child nodes elements. */ public Enumeration children() { return childNodes.elements(); } /** Implements TreeNode interface @return true if children are allowed. */ public boolean getAllowsChildren() { return true; } /** Implements TreeNode interface. Retrieve a particular child. @param childIndex the index of the child @return the node containing the child. */ public TreeNode getChildAt(int childIndex) { return (TreeNode)childNodes.get(childIndex); } /** Implements TreeNode interface @return the number of children. */ public int getChildCount() { return childNodes.size(); } /** Implements TreeNode interface. Get the index of a particular node. @param node the node to be searched for. @return the index of the node or -1 if the node has not been found. */ public int getIndex(TreeNode node) { return childNodes.indexOf(node); } /** Implements TreeNode interface. Get the parent node. @return the parent node. */ public TreeNode getParent() { return (TreeNode)parent; } /** Set the parent node. @param parent the parent node. */ public void setParent(TreeNode parent) { this.parent = parent; } /** Implements TreeNode interface. Check if it is a leaf. @return boolean false default. */ public boolean isLeaf() { return false; } /** Sort recursively. */ public void sortTree() { Collections.sort(childNodes, new Comparator<AbstractMacroTreeNode>(){ @Override public int compare(AbstractMacroTreeNode o1, AbstractMacroTreeNode o2) { return o1.toString().compareTo(o2.toString()); } }); for(Object n:childNodes) { ((AbstractMacroTreeNode)n).sortTree(); } } /** Remove a child node. @param node the node to be removed. */ public void removeChildNode(TreeNode node) { childNodes.remove(node); } /** Get the index of the provided node. @param node the node to be searched for. @return the node index, or -1 if the node has not been found. */ public int getIndexAt(TreeNode node) { return childNodes.indexOf(node); } /** Get the icon associated to the tree. @return the icon. */ public Icon getIcon() { return icon; } /** Get a string describing the tree. @return the description (the label). */ @Override public String toString() { return label; } /** Clear (remove) all child nodes. */ public void clearChildNodes() { childNodes.clear(); } }
4,409
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/graphic/package-info.java
/** Interfaces (and implementation, as sub-packages) of everything needed to draw on each kind of technology: Swing and Android, for example. */ package net.sourceforge.fidocadj.graphic;
191
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DecoratedText.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/DecoratedText.java
package net.sourceforge.fidocadj.graphic; /** Decorated text is a class that provides advanced text functions. It is possible to do things as follows: I_dsat R^2 V^2e x^2^3_-3_-4 to indicate indices or exponents. The command _ indicates that the next character will be an index. The command ^ indicates that the next character is an exponent. If more of one character must be put, put them in braces. Use \_ to enter a bar and \^ to enter a caret. <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 DecoratedText { private TextInterface g; private String btoken; private String bstr; private int currentIndex; private int lastIndex; private int exponentLevel; final static int CHUNK = 0; final static int INDEX = 1; final static int EXPONENT = 2; final static int END = 3; /** The creator. @param g the graphic object where to draw. */ public DecoratedText(TextInterface g) { this.g=g; } /** 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 g.getStringWidth(s); } private int getToken() { StringBuffer processToken; if(currentIndex >= lastIndex) { return END; } char c=bstr.charAt(currentIndex); char cp=0; if(currentIndex < lastIndex-1) { cp=bstr.charAt(currentIndex+1); } if(c=='\\') { c=cp; ++currentIndex; } else if(c=='_') { ++currentIndex; return INDEX; } else if (c=='^') { ++currentIndex; return EXPONENT; } processToken=new StringBuffer(); while(true) { processToken.append(c); ++currentIndex; if(currentIndex>=lastIndex) { break; } c=bstr.charAt(currentIndex); if(c=='_' || c=='^' || c=='\\') { break; } } btoken=processToken.toString(); return CHUNK; } private void resetTokenization(String s) { bstr=s; currentIndex=0; exponentLevel=0; lastIndex=s.length(); } private float getSizeMultLevel() { switch((int)Math.abs(exponentLevel)){ case 0: return 1f; case 1: return 0.8f; case 2: return 0.7f; case 3: return 0.6f; default: return 0.5f; } } /** 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) { /* [FIDOCAD] FJC A 0.35 TY 1 2 4 3 0 0 0 Helvetica 1^2^3^4^5^6^7^8^9 */ resetTokenization(str); int xc=x; double fontSize=g.getFontSize(); int t; while((t=getToken())!=END) { switch(t) { case CHUNK: g.setFontSize(fontSize*getSizeMultLevel()); // Font size is given in points, i.e. 1/72 of an inch. // FidoCadJ has a 200 dpi internal resolution. g.drawString(btoken, xc, y-(int)Math.round( exponentLevel*fontSize*getSizeMultLevel()*0.5)); xc+=g.getStringWidth(btoken); break; case EXPONENT: ++exponentLevel; break; case INDEX: --exponentLevel; break; case END: break; default: } } } }
4,846
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ShapeInterface.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/ShapeInterface.java
package net.sourceforge.fidocadj.graphic; /** ShapeInterface is an interface used to specify a generic graphical shape. <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 ShapeInterface { /** Obtain the bounding box of the curve. @return the bounding box. */ RectangleG getBounds(); /** 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. */ void createCubicCurve(int x0, int y0, int x1, int y1, int x2, int y2, int x3, int y3); /** Create a general path with the given number of points. @param npoints the number of points. */ void createGeneralPath(int npoints); /** Move the current position to the given coordinates. @param x the x coordinate. @param y the y coordinate. */ void moveTo(float x, float 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. */ void curveTo(float x0, float y0, float x1, float y1, float x2, float y2); /** Close the current path. */ void closePath(); }
2,592
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ColorInterface.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/ColorInterface.java
package net.sourceforge.fidocadj.graphic; /** Provides a general way to access colors. <P> D.B.: WHY THE HELL THERE ARE TWO DIFFERENT CLASSES java.awt.Color AND android.graphics.Color. TWO DIFFERENT INCOMPATIBLE THINGS TO DO EXACTLY THE SAME STUFF. SHAME SHAME SHAME! </P> <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 ColorInterface { /** Get a white color. @return a white color. */ ColorInterface white(); /** Get a gray color. @return a gray color. */ ColorInterface gray(); /** Get a green color. @return a green color. */ ColorInterface green(); /** Get a red color. @return a red color. */ ColorInterface red(); /** Get a black color. @return a black color. */ ColorInterface black(); /** Get the green component of the color. @return the component. */ int getGreen(); /** Get the red component of the color. @return the component. */ int getRed(); /** Get the blue component of the color. @return the component. */ int getBlue(); /** Get the RGB description of the color. @return the description, packed in an int. */ int getRGB(); /** Set the color from a RGB description packed in a int. @param rgb the packed description.. */ void setRGB(int rgb); }
2,136
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
FontG.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/FontG.java
package net.sourceforge.fidocadj.graphic; /** FontG is a class containing font information. <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 FontG { public String fontFamily; /** Standard constructor. @param n the name of the font family. */ public FontG(String n) { fontFamily=n; } /** Get the font family. @return the font family. */ public String getFamily() { return fontFamily; } }
1,214
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DimensionG.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/DimensionG.java
package net.sourceforge.fidocadj.graphic; /** DimensionG <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 DimensionG { public int width; public int height; /** Standard constructor. @param width the width (or x dimension). @param height the height (or y dimension). */ public DimensionG(int width, int height) { this.width=width; this.height=height; } /** Standard creator. Width and hight are put equal to zero. */ public DimensionG() { this.width=0; this.height=0; } }
1,318
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PointDouble.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/PointDouble.java
package net.sourceforge.fidocadj.graphic; /** PointDouble is a class implementing a point with its coordinates (double). <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 PointDouble { public double x; public double y; /** Standard constructor. @param x the x coordinate of the point. @param y the y coordinate of the point. */ public PointDouble(double x, double y) { this.x=x; this.y=y; } /** Standard constructor. The x and y coordinates are put equal to zero. */ public PointDouble() { this.x=0; this.y=0; } }
1,360
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
GraphicsInterface.java
/FileExtraction/Java_unseen/DarwinNE_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
TextInterface.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/TextInterface.java
package net.sourceforge.fidocadj.graphic; /** Provides a general way to access text. <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 interface TextInterface { /** Get the font size. @return the font size. */ double getFontSize(); /** Set the font size. @param size the font size. */ void setFontSize(double 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. */ 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); }
1,623
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
RectangleG.java
/FileExtraction/Java_unseen/DarwinNE_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/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/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/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/src/net/sourceforge/fidocadj/graphic/nil/PolygonNull.java
package net.sourceforge.fidocadj.graphic.nil; import java.awt.*; import net.sourceforge.fidocadj.graphic.PolygonInterface; /** SWING 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 <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 by Davide Bucci </pre> */ public class PolygonNull implements PolygonInterface { private final Polygon p; /** Standard constructor. */ public PolygonNull() { p=new Polygon(); } /** 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) { p.addPoint(x,y); } /** Reset the current polygon by deleting all the points. */ public void reset() { p.reset(); } /** Get the current number of points in the polygon. @return the number of points. */ public int getNpoints() { return p.npoints; } /** Get a vector containing the x coordinates of the points. @return a vector containing the x coordinates of all points. */ public int[] getXpoints() { return p.xpoints; } /** Get a vector containing the y coordinates of the points. @return a vector containing the y coordinates of all points. */ public int[] getYpoints() { return p.ypoints; } /** 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) { return p.contains(x,y); } }
2,518
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ShapeNull.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/nil/ShapeNull.java
package net.sourceforge.fidocadj.graphic.nil; import java.awt.*; import java.awt.geom.*; import net.sourceforge.fidocadj.graphic.ShapeInterface; import net.sourceforge.fidocadj.graphic.RectangleG; /** SWING 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 <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 by Davide Bucci </pre> */ public class ShapeNull implements ShapeInterface { Shape s; /** Standard constructor. */ public ShapeNull() { s=null; } /** 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) { s = new CubicCurve2D.Float(x0, y0, 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) { s = new GeneralPath(GeneralPath.WIND_EVEN_ODD, npoints); } /** Obtain the bounding box of the curve. @return the bounding box. */ public RectangleG getBounds() { Rectangle r=s.getBounds(); return new RectangleG(r.x, r.y, r.width, r.height); } /** 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) { GeneralPath gp=(GeneralPath)s; gp.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) { GeneralPath gp=(GeneralPath)s; gp.curveTo(x0, y0,x1, y1,x2, y2); } /** Close the current path. */ public void closePath() { GeneralPath gp=(GeneralPath)s; gp.closePath(); } }
3,465
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
GraphicsNull.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/nil/GraphicsNull.java
package net.sourceforge.fidocadj.graphic.nil; import java.awt.*; import java.awt.geom.*; import java.awt.image.*; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.graphic.ShapeInterface; import net.sourceforge.fidocadj.graphic.TextInterface; import net.sourceforge.fidocadj.graphic.PolygonInterface; import net.sourceforge.fidocadj.graphic.ColorInterface; /** SWING VERSION Null graphic class. Does nothing. Nil. Zero. :-) Except... calculating text size correctly! Yes. There is a reason for that. This is used for calculating the size of a drawing. In practice, a redraw is launched to keep track of all the drawing elements. They are not drawn, but the program keeps track of their positions and size. <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 class GraphicsNull implements GraphicsInterface, TextInterface { private FontMetrics fm; Graphics g; /** Standard constructor. */ public GraphicsNull() { // Unfortunately, to get the image size, we need to redraw it. // I do not like it, even if here we are not in a speed sensitive // context! // Create a dummy image on which the drawing will be done BufferedImage bufferedImage = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB); // Create a graphics contents on the buffered image g = bufferedImage.createGraphics(); fm = g.getFontMetrics(); /* Is that useful??? */ ((Graphics2D) g).setRenderingHint( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); } /** Retrieves an object implementing an appropriate TextInterface. @return an object implementing TextInterface. */ public TextInterface getTextInterface() { return this; } /** Set the current color. Here nothing is done. @param c the current color. */ public void setColor(ColorInterface c) { // nothing to do } /** 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 } /** Get the current zoom factor. Currently employed for resizing the dash styles. @return the current zoom factor (pixels for logical units). */ public double getZoom() { return 1.0; } /** 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 false; } /** 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 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) { /*Font f = new Font(name, Font.PLAIN+(isItalic?Font.ITALIC:0)+(isBold?Font.BOLD:0), size);*/ Font ft = new Font(name, Font.PLAIN+(isItalic?Font.ITALIC:0)+(isBold?Font.BOLD:0), 100); Font f = ft.deriveFont( AffineTransform.getScaleInstance( (double)size/100.0,(double)size/100.0)); fm=g.getFontMetrics(f); } /** Get the font size. @return the size. */ public double getFontSize() { return g.getFont().getSize(); } /** Set the font size. @param size the fort size. */ public void setFontSize(double size) { g.setFont(g.getFont().deriveFont((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() { // TODO: is there a way to implement something without a graphic // context? return fm.getAscent(); } /** Get the descent metric of the current font. @return the value of the descent, in pixels. */ public int getFontDescent() { return fm.getDescent(); } /** 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) { //System.out.println("nil: "+fm.stringWidth(s)); return fm.stringWidth(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() { // If GraphicsNull is used correctly, this magic number should not // be very important. return 72; } }
13,947
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ColorNull.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/nil/ColorNull.java
package net.sourceforge.fidocadj.graphic.nil; import net.sourceforge.fidocadj.graphic.ColorInterface; /** SWING VERSION Null color class. Does nothing :-) Class like this one are useful when calculating the size of the drawings. <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 class ColorNull implements ColorInterface { /** Does nothing. @return a new ColorNull instance. */ public ColorInterface white() { return new ColorNull(); } /** Does nothing. @return a new ColorNull instance. */ public ColorInterface gray() { return new ColorNull(); } /** Does nothing. @return a new ColorNull instance. */ public ColorInterface green() { return new ColorNull(); } /** Does nothing. @return a new ColorNull instance. */ public ColorInterface red() { return new ColorNull(); } /** Does nothing. @return a new ColorNull instance. */ public ColorInterface black() { return new ColorNull(); } /** Does nothing. @return 0. */ public int getRed() { return 0; } /** Does nothing. @return 0. */ public int getGreen() { return 0; } /** Does nothing. @return 0. */ public int getBlue() { return 0; } /** Does nothing. @return 0. */ public int getRGB() { return 0; } /** Does nothing. @param rgb not used. */ public void setRGB(int rgb) { // Does nothing. } }
2,370
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PolygonSwing.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/swing/PolygonSwing.java
package net.sourceforge.fidocadj.graphic.swing; import java.awt.*; import net.sourceforge.fidocadj.graphic.PolygonInterface; /** 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-2015 by Davide Bucci </pre> */ public class PolygonSwing implements PolygonInterface { private final Polygon p; /** Standard constructor. */ public PolygonSwing() { p=new Polygon(); } /** 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) { p.addPoint(x,y); } /** Get the Swing version of the polygon. @return the Swing polygon. */ public Polygon getSwingPolygon() { return p; } /** Reset the current polygon by deleting all the points. */ public void reset() { p.reset(); } /** Get the current number of points in the polygon. @return the number of points. */ public int getNpoints() { return p.npoints; } /** Get a vector containing the x coordinates of the points. @return a vector containing the x coordinates of all points. */ public int[] getXpoints() { return p.xpoints; } /** Get a vector containing the y coordinates of the points. @return a vector containing the y coordinates of all points. */ public int[] getYpoints() { return p.ypoints; } /** 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) { return p.contains(x,y); } }
2,617
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ColorSwing.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/swing/ColorSwing.java
package net.sourceforge.fidocadj.graphic.swing; import java.awt.Color; import net.sourceforge.fidocadj.graphic.ColorInterface; /** This class maps the general interface to java.awt.Color. We need this because there is no unified color description between Swing/PC versions of Java and Android's ones (GRRRRR!!!!). <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 class ColorSwing implements ColorInterface { Color c; /** Standard constructor. The default color is black. */ public ColorSwing() { c= Color.black; } /** Standard constructor. @param c the Swing color to be employed. */ public ColorSwing(Color c) { this.c=c; } /** Get the Swing color. @return the Swing color. */ public Color getColorSwing() { return c; } /** Get a white color. @return a white color. */ public ColorInterface white() { return new ColorSwing(Color.white); } /** Get a gray color. @return a gray color. */ public ColorInterface gray() { return new ColorSwing(Color.gray); } /** Get a green color. @return a green color. */ public ColorInterface green() { return new ColorSwing(Color.green); } /** Get a red color. @return a red color. */ public ColorInterface red() { return new ColorSwing(Color.red); } /** Get a black color. @return a black color. */ public ColorInterface black() { return new ColorSwing(Color.black); } /** Get the red component. @return the component. */ public int getRed() { return c.getRed(); } /** Get the green component. @return the component. */ public int getGreen() { return c.getGreen(); } /** Get the blue component. @return the component. */ public int getBlue() { return c.getBlue(); } /** Get the RGB description of the color. @return the description, packed in an int. */ public int getRGB() { return c.getRGB(); } /** Set the color from a RGB description packed in a int. @param rgb the packed description.. */ public void setRGB(int rgb) { c=new Color(rgb); } }
3,115
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ShapeSwing.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/swing/ShapeSwing.java
package net.sourceforge.fidocadj.graphic.swing; import java.awt.*; import java.awt.geom.*; import net.sourceforge.fidocadj.graphic.ShapeInterface; import net.sourceforge.fidocadj.graphic.RectangleG; /** ShapeSwing is a wrapper around the Shape Swing 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 2014-2023 by Davide Bucci </pre> */ public class ShapeSwing implements ShapeInterface { Shape s; /** Standard constructor. */ public ShapeSwing() { s=null; } /** 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) { s = new CubicCurve2D.Float(x0, y0, 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) { s = new GeneralPath(GeneralPath.WIND_EVEN_ODD, npoints); } /** Obtain the bounding box of the curve. @return the bounding box. */ public RectangleG getBounds() { Rectangle r=s.getBounds(); return new RectangleG(r.x, r.y, r.width, r.height); } /** 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) { GeneralPath gp=(GeneralPath)s; gp.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) { GeneralPath gp=(GeneralPath)s; gp.curveTo(x0, y0,x1, y1,x2, y2); } /** Close the current path. */ public void closePath() { GeneralPath gp=(GeneralPath)s; gp.closePath(); } /** Get the Swing version of the shape. @return the Swing version of the shape. */ public Shape getShapeInSwing() { return s; } }
3,566
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
Graphics2DSwing.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/graphic/swing/Graphics2DSwing.java
package net.sourceforge.fidocadj.graphic.swing; import java.awt.*; import java.awt.geom.*; import java.awt.image.*; // Used in drawGrid import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.graphic.DecoratedText; import net.sourceforge.fidocadj.graphic.ColorInterface; import net.sourceforge.fidocadj.graphic.PolygonInterface; import net.sourceforge.fidocadj.graphic.ShapeInterface; import net.sourceforge.fidocadj.graphic.TextInterface; import net.sourceforge.fidocadj.graphic.GraphicsInterface; /** This class maps the general interface to java.awt.Graphics2D. It also provides a method to draw grid. It turns out that it is not trivial to draw grids in an efficient way, and the best strategy generally depends on the particular context. So the drawGrid method is present in the GraphicsInterface and of course its implementation is here. <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 class Graphics2DSwing implements GraphicsInterface, TextInterface { // Practical sizes to the image used a "brush" for the tiled fill. // Larger images may yield faster results, until the memory penalty will // decrease performance. Used to be 1000x1000, but it seems that this is // too big on some Linux systems (see issue #166). private final static int maxAllowableGridBrushWidth = 500; private final static int maxAllowableGridBrushHeight = 500; Graphics2D g; // Here are some other local variables made global for avoiding memory // allocations (used in drawGrid). private BufferedImage bufferedImage; // Useful for grid calculation private double oldZoom; // TODO: maybe the same as actualZoom? private TexturePaint tp; private int width; // NOPMD (complains -> local variable) private int height; // NOPMD (complains -> local variable) private BasicStroke[] strokeList; private float actual_w; private double zoom; private double actualZoom; /* Strategy in 0.24.7: ------------------- The font size affects the way the font is drawn. For this reason (as things such as the zoom and scaling should not change the relative size of the text), the font size is kept always equal to 100. Then, a coordinate change is applied to the font so that it is rescaled to the wanted size. Strategy in 0.24.8: ------------------- Due to a strange bug for some (large) font sizes, I (DB) reverted the mechanism and I derive a new font of a given calculated size from the original font. The situation does not seem to be now much worse than 0.24.7 as I can set up the font size as a float and thus cope better with smaller font sizes. */ private final static int FONTSIZE=100; // The size of the unscaled font. private Font f; // This is the scaled font. private double fontScale=1.0; // This is the scaling factor. private Font mf; // This is the original (unscaled) font. /** Constructor: fabricate a new object form a java.awt.Graphics2D object. @param gg the java.awt.Graphics2D graphic context. */ public Graphics2DSwing(Graphics2D gg) { g=gg; oldZoom = -1; actualZoom = -1; zoom=1; /* Is that useful??? */ g.setRenderingHint( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); g.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } /** Constructor: fabricate a new object form a java.awt.Graphics object. @param gg the java.awt.Graphics graphic context. */ public Graphics2DSwing(Graphics gg) { g=(Graphics2D)gg; oldZoom = -1; actualZoom = -1; zoom=1; /* Is that useful??? */ /*g.setRenderingHint( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);*/ /*g.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIASING_ON);*/ } /** Constructor: fabricate a new object without associating a graphic object. You should use {@link #setGraphicContext} method to setup a graphic object in a second time to avoid a runtime exception. */ public Graphics2DSwing() { g=null; oldZoom = -1; actualZoom = -1; zoom=1; } /** Retrieves an object implementing an appropriate TextInterface. @return an object implementing TextInterface. */ public TextInterface getTextInterface() { return this; } /** 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) { if (w!=actual_w && w>0 || zoom!=actualZoom) { strokeList = new BasicStroke[Globals.dashNumber]; // If the line width has been changed, we need to update the // stroke table // The first entry is non dashed strokeList[0]=new BasicStroke(w, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); // Resize the dash sizes depending on the current zoom size. float[] dashArrayStretched; // Then, the dashed stroke styles are created. if(zoom<1.0) { zoom=1.0; } for(int i=1; i<Globals.dashNumber; ++i) { // Prepare the resized dash array. dashArrayStretched = new float[Globals.dash[i].length]; for(int j=0; j<Globals.dash[i].length;++j) { dashArrayStretched[j]=Globals.dash[i][j]*(float)zoom/2.0f; } strokeList[i]=new BasicStroke(w, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, (float)(10.0f*zoom), dashArrayStretched, 0.0f); } actual_w=w; actualZoom=zoom; } // Here we retrieve the stroke style corresponding to the given // dashStyle BasicStroke stroke=(BasicStroke)strokeList[dashStyle]; // Apparently, on some systems (like my iMac G5 with MacOSX 10.4.11) // setting the stroke takes a lot of time! if(!stroke.equals(g.getStroke())) { g.setStroke(stroke); } } /** 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) { zoom=z; } /** Get the current zoom factor. Currently employed for resizing the dash styles. @return the current zoom factor (pixels for logical units). */ public double getZoom() { return zoom; } /** This is a Swing-related method: it sets the current graphic context to the given Swing one. @param gg the Swing graphic context. */ public void setGraphicContext(Graphics2D gg) { g=gg; } /** This is a Swing-related method: it gets the current graphic context. @return the Swing graphic context */ public Graphics2D getGraphicContext() { return g; } /** Sets the current color. @param c the color to be set. Must be cast-able to ColorSwing class. */ public void setColor(ColorInterface c) { ColorSwing cc = (ColorSwing) c; g.setColor(cc.getColorSwing()); } /** Gets the current color. @return the actual color. Can be cast-able to ColorSwing class. */ public ColorInterface getColor() { return new ColorSwing(g.getColor()); } /** Draw 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) { g.drawRect(x,y,width,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 */ public void fillRect(int x, int y, int width, int height) { g.fillRect(x,y,width,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 */ public void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) { g.fillRoundRect(x,y,width,height,arcWidth,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. */ public boolean hitClip(int x, int y, int width, int height) { return g.hitClip(x,y,width,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. */ public void drawLine(int x1, int y1, int x2, int y2) { g.drawLine(x1,y1,x2,y2); } /** Set 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) { mf = new Font(name, Font.PLAIN+(isItalic?Font.ITALIC:0)+(isBold?Font.BOLD:0), FONTSIZE); fontScale=size; f = mf.deriveFont((float)size); // Check if there is the need to change the current font. Apparently, // on some systems (I have seen this on MacOSX), setting up the font // takes a surprisingly long amount of time. if(!g.getFont().equals(f)) { g.setFont(f); } } /** 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 font size. @return the font size. */ public double getFontSize() { return fontScale; } /** Set the font size. @param size the font size. */ public void setFontSize(double size) { fontScale=size; if(mf==null) { return; } f = mf.deriveFont((float)size); if(!g.getFont().equals(f)) { g.setFont(f); } } /** Get the ascent metric of the current font. @return the value of the ascent, in pixels. */ public int getFontAscent() { FontMetrics fm = g.getFontMetrics(g.getFont()); return fm.getAscent(); } /** Get the descent metric of the current font. @return the value of the descent, in pixels. */ public int getFontDescent() { FontMetrics fm = g.getFontMetrics(g.getFont()); return fm.getDescent(); } /** 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) { FontMetrics fm = g.getFontMetrics(g.getFont()); return fm.stringWidth(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) { g.drawString(str,x,y); } /** 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) { g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 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. */ public void fillOval(int x, int y, int width, int height) { g.fillOval(x,y,width,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. */ public void drawOval(int x, int y, int width, int height) { g.drawOval(x,y,width,height); } /** Fill a given shape. @param s the shape to be filled. */ public void fill(ShapeInterface s) { ShapeSwing ss=(ShapeSwing) s; g.fill(ss.getShapeInSwing()); } /** Draw a given shape. @param s the shape to be drawn. */ public void draw(ShapeInterface s) { ShapeSwing ss=(ShapeSwing) s; g.draw(ss.getShapeInSwing()); } /** Fill a given polygon. @param p the polygon to be filled. */ public void fillPolygon(PolygonInterface p) { PolygonSwing pp=(PolygonSwing) p; g.fillPolygon(pp.getSwingPolygon()); } /** Draw a given polygon. @param p the polygon to be drawn. */ public void drawPolygon(PolygonInterface p) { PolygonSwing pp=(PolygonSwing) p; g.drawPolygon(pp.getSwingPolygon()); } /** 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) { // We blend the layer color with green, in such a way that the // selected objects bear a certain reminescence of their original // color. if (l==null) { g.setColor(Color.green); } else { ColorSwing c =(ColorSwing) l.getColor(); g.setColor(blendColors(Color.green, c.getColorSwing(), 0.6f)); } g.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 1.0f)); } /** Blend two colors. From http://www.java2s.com/Code/Java/2D-Graphics-GUI/Commoncolorutilities.htm @param color1 First color to blend. @param color2 Second color to blend. @param r Blend ratio. 0.5 will give even blend, 1.0 will return color1, 0.0 will return color2 and so on. @return Blended color. */ public static Color blendColors (Color color1, Color color2, float r) { float ir = (float) 1.0 - r; float rgb1[] = new float[3]; float rgb2[] = new float[3]; color1.getColorComponents (rgb1); color2.getColorComponents (rgb2); return new Color (rgb1[0] * r + rgb2[0] * ir, rgb1[1] * r + rgb2[1] * ir, rgb1[2] * r + rgb2[2] * ir); } /** 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) { // TODO: is it possible to unify qq and ya? For example, get rid of qq? /* At first, I tried to use an affine transform on the font, without pratically touching the graphic context. This technique worked well, but I noticed it produced bugs on the case of a jar packed on a MacOSX application bundle. I therefore choose (from v. 0.20.2) to use only graphic context transforms. What a pity! February 20, 2009: I noticed this is in fact a bug on JRE < 1.5 December 14, 2015: Maybe it is a way to obtain a more consistant text output? Now FidoCadJ requires Java 1.7, get back to it? */ AffineTransform at=(AffineTransform)g.getTransform().clone(); // Ats is used to save the current coordinate transform. AffineTransform ats=(AffineTransform)at.clone(); AffineTransform stretching= new AffineTransform(); AffineTransform mm= new AffineTransform(); DecoratedText dt=new DecoratedText(this); stretching.scale(1,xyfactor); if (mirror) { mm.scale(-1,1); } // If it's a simple normal text, draw it in the simple (fastest) way. if(orientation==0) { if (mirror) { // Here the text is mirrored at.scale(-1,xyfactor); g.setTransform(at); if(g.hitClip(-xa,qq,w,h)) { if(!g.getFont().equals(f)) { g.setFont(f); } dt.drawString(txt,-xa,qq+h); } } else { // Here the text is normal if(needsStretching) { at.concatenate(stretching); g.setTransform(at); } if(g.hitClip(xa,qq, w, th)){ if(th<Globals.textSizeLimit) { g.drawLine(xa,qq,xa+w,qq); if(needsStretching) { g.setTransform(ats); } return; } else { if(!g.getFont().equals(f)) { g.setFont(f); } dt.drawString(txt,xa,qq+h); if(needsStretching) { g.setTransform(ats); } return; } } } } else { // Text is rotated. if(mirror) { // Here the text is rotated and mirrored at.concatenate(mm); at.rotate(Math.toRadians(orientation),-xa, ya); if(needsStretching) { at.concatenate(stretching); } g.setTransform(at); if(!g.getFont().equals(f)) { g.setFont(f); } dt.drawString(txt,-xa,qq+h); } else { // Here the text is just rotated at.rotate(Math.toRadians(-orientation),xa,ya); if(needsStretching) { at.concatenate(stretching); } g.setTransform(at); if(!g.getFont().equals(f)) { g.setFont(f); } dt.drawString(txt,xa,qq+h); } } g.setTransform(ats); } /** 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(); // Horizontal grid pitch in logical units. int dy=cs.getYGridStep(); // Vertical grid pitch in logical units. int mul=1; double toll=0.01; double z=cs.getYMagnitude(); // DB: I tried with d/2 instead of 0, but I get some very // unpleasant aliasing effects for zoom such as 237% double dd=0; double x; double y; // Fabricate a new image only if necessary, to save time. if(oldZoom!=z || bufferedImage == null || tp==null) { // It turns out that drawing the grid in an efficient way is not a // trivial task. The program here 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 (int l=1; l<105; ++l) { if (Math.abs(l*z-Math.round(l*z))<toll) { mul=l; break; } } tp = 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)); double d=1; // This code applies a correction: draws lines if the pitch // is very large, or draw much less dots if it is too dense. if (ddx>35 || ddy>35) { // Lines! bufferedImage=null; d=2; // The loops are done in logical units. g.setColor(new Color(220,220,220)); for (x=cs.unmapXsnap(xmin); x<=cs.unmapXsnap(xmax); x+=dx) { g.drawLine( (int)Math.round(cs.mapXr(x,0)),ymin, (int)Math.round(cs.mapXr(x,0)), ymax); } for (y=cs.unmapYsnap(ymin); y<=cs.unmapYsnap(ymax); y+=dy) { g.drawLine( xmin,(int)Math.round(cs.mapYr(0,y)), xmax, (int)Math.round(cs.mapYr(0,y))); } return; } else if (ddx<3 || ddy <3) { // Less dots dx=5*cs.getXGridStep(); dy=5*cs.getYGridStep(); ddx=Math.abs(cs.mapXi(dx,0,false)-cs.mapXi(0,0,false)); } width=Math.abs(cs.mapX(mul*dx,0)-cs.mapX(0,0)); if (width<=0) { width=1; } height=Math.abs(cs.mapY(0,0)-cs.mapY(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>maxAllowableGridBrushWidth || height>maxAllowableGridBrushHeight) { // Simpler (and generally less efficient) version of the grid g.setColor(Color.gray); for (x=cs.unmapXsnap(xmin); x<=cs.unmapXsnap(xmax); x+=dx) { for (y=cs.unmapYsnap(ymin); y<=cs.unmapYsnap(ymax); y+=dy) { g.fillRect((int)Math.round(cs.mapXr(x,y)-dd), (int)Math.round(cs.mapYr(x,y)-dd),(int)d,(int)d); } } return; } try { // Create a buffered image in which to draw GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = env.getDefaultScreenDevice(); GraphicsConfiguration config = device.getDefaultConfiguration(); bufferedImage = config.createCompatibleImage(width, height, Transparency.TRANSLUCENT); } catch (OutOfMemoryError e) { System.out.println("Out of memory error when painting grid"); return; } // Create a graphics contents on the buffered image Graphics2D g2d = bufferedImage.createGraphics(); g2d.setColor(Color.white); g2d.setColor(Color.gray); // Prepare the image with the grid. for (x=0; x<=cs.unmapXsnap(width); x+=dx) { for (y=0; y<=cs.unmapYsnap(height); y+=dy) { g2d.fillRect((int)Math.round(cs.mapXr(x,y)-dd), (int)Math.round(cs.mapYr(x,y)-dd),(int)d,(int)d); } } oldZoom=z; Rectangle anchor = new Rectangle(width, height); tp = new TexturePaint(bufferedImage, anchor); } // Textured paint :-) g.setPaint(tp); g.fillRect(0, 0, xmax, ymax); // TODO: sometimes I get an exception. } /** Create a polygon object, compatible with Graphics2DSwing. @return a polygon object (instance of PolygonSwing). */ public PolygonInterface createPolygon() { return new PolygonSwing(); } /** Create a shape object, compatible with Graphics2DSwing. @return a shape object (instance of ShapeSwing). */ public ShapeInterface createShape() { return new ShapeSwing(); } /** Create a color object, compatible with Graphics2DSwing. @return a color object (instance of ColorSwing). */ public ColorInterface createColor() { return new ColorSwing(g.getColor()); } /** Retrieve the current screen density in dots-per-inch. @return the screen resolution (density) in dots-per-inch. */ public float getScreenDensity() { return Toolkit.getDefaultToolkit().getScreenResolution(); } }
29,907
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitiveConnection.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitiveConnection.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; /** Class to handle the Connection 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 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class PrimitiveConnection extends GraphicPrimitive { // A connection is defined by one points. // We take into account the optional Name and Value text tags. static final int N_POINTS=3; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. private int x1; // NOPMD private int y1; // NOPMD private int xa1; // NOPMD private int ya1; // NOPMD private int ni; // NOPMD private double nn; // NOPMD private float w; // NOPMD /** Gets the number of control points used. @return the number of points used by the primitive */ public int getControlPointNumber() { return N_POINTS; } /** Constructor. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveConnection(String f, int size) { super(); initPrimitive(-1, f, size); } /** Create a connection in the given point. @param x the x coordinate (logical unit) of the connection. @param y the y coordinate (logical unit) of the connection. @param layer the layer to be used. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveConnection(int x, int y, int layer, String f, int size) { super(); initPrimitive(-1, f, size); virtualPoint[0].x=x; virtualPoint[0].y=y; virtualPoint[getNameVirtualPointNumber()].x=x+5; virtualPoint[getNameVirtualPointNumber()].y=y+5; virtualPoint[getValueVirtualPointNumber()].x=x+5; virtualPoint[getValueVirtualPointNumber()].y=y+10; setLayer(layer); } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { if(!selectLayer(g,layerV)) { return; } drawText(g, coordSys, layerV, -1); if (changed) { changed=false; /* in the Connection primitive, the virtual point represents the position of the center of the circle to be drawn. */ x1=virtualPoint[0].x; y1=virtualPoint[0].y; nn=Math.abs(coordSys.mapXr(0,0)- coordSys.mapXr(10,10))*Globals.diameterConnection/10.0; // a little boost for small zooms :-) if (nn<2.0) { nn=(int)(Math.abs(coordSys.mapXr(0,0)- coordSys.mapXr(20,20))*Globals.diameterConnection/12); } xa1=(int)Math.round(coordSys.mapX(x1,y1)-nn/2.0); ya1=(int)Math.round(coordSys.mapY(x1,y1)-nn/2.0); ni=(int)Math.round(nn); // Make sure that something is drawn even for very small // connections if(ni==0) { ni=1; } w = (float)(Globals.lineWidth*coordSys.getXMagnitude()); if (w<D_MIN) { w=D_MIN; } } if(!g.hitClip(xa1, ya1, ni, ni)) { return; } g.applyStroke(w, 0); // When the circle is very small, it is better to set a single pixel // than trying to fill the oval. if(ni>1) { g.fillOval(xa1, ya1, ni, ni); } else { g.fillRect(xa1, ya1, ni, ni); } } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array @throws IOException if the arguments are incorrect or the primitive is invalid. */ public void parseTokens(String[] tokens, int nn) throws IOException { changed=true; if ("SA".equals(tokens[0])) { // Connection if (nn<3) { throw new IOException("Bad arguments on SA"); } // Load the points in the virtual points associated to the // current primitive. int x1 = virtualPoint[0].x=Integer.parseInt(tokens[1]); int y1 = virtualPoint[0].y=Integer.parseInt(tokens[2]); virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; if(nn>3) { parseLayer(tokens[3]); } } else { throw new IOException("Invalid primitive:"+ " programming error?"); } } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { // Here we check if the given point lies inside the text areas if(checkText(px, py)) { return 0; } // If not, we check for the distance with the connection center. return GeometricDistances.pointToPoint( virtualPoint[0].x,virtualPoint[0].y, px,py)-1; } /** Obtain a string command descripion of the primitive. @param extensions true if FidoCadJ extensions to the old FidoCAD format should be active. @return the FIDOCAD command line. */ public String toString(boolean extensions) { StringBuffer s=new StringBuffer(100); s.append("SA "); s.append(virtualPoint[0].x); s.append(" "); s.append(virtualPoint[0].y); s.append(" "); s.append(getLayer()); s.append("\n"); s.append(saveText(extensions)); return s.toString(); } /** Export the primitive on a vector graphic format. @param exp the export interface to employ. @param cs the coordinate mapping to employ. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { exportText(exp, cs, -1); exp.exportConnection(cs.mapX(virtualPoint[0].x,virtualPoint[0].y), cs.mapY(virtualPoint[0].x,virtualPoint[0].y), getLayer(), Globals.diameterConnection*cs.getXMagnitude()); } /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public int getNameVirtualPointNumber() { return 1; } /** Get the number of the virtual point associated to the Value property @return the number of the virtual point associated to the Value property */ public int getValueVirtualPointNumber() { return 2; } }
9,068
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/primitives/package-info.java
/** The implemented graphic primitives (and related classes). They are stored in the circuit.model.DrawingModel class. They are responsible of knowing everything about themselves: how to be drawn, how to be exported, how to calculate their size and so on. <p> All drawing primitives extends the GraphicPrimitive base class, which is a virtual class providing some basic functions. */ package net.sourceforge.fidocadj.primitives;
452
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitiveLine.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitiveLine.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.dialogs.DashInfo; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.graphic.PointG; /** Class to handle the line 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 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class PrimitiveLine extends GraphicPrimitive { static final int N_POINTS=4; // Info about arrow. private final Arrow arrowData; private int dashStyle; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. private int xa; private int ya; private int xb; // NOPMD private int yb; // NOPMD private int x1; // NOPMD private int x2; // NOPMD private int y1; // NOPMD private int y2; // NOPMD private float w; private int length2; private int xbpap1; private int ybpap1; private boolean arrows; /** Constructor. @param x1 the x coordinate of the start point of the line. @param y1 the y coordinate of the start point of the line. @param x2 the x coordinate of the end point of the line. @param y2 the y coordinate of the end point of the line. @param layer the layer to be used. @param arrowS true if there is an arrow at the beginning of the line. @param arrowE true if there is an arrow at the end of the line. @param arrowSt style of the arrow. @param arrowLe length of the arrow. @param arrowWi width of the arrow. @param dashSt the dashing style. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveLine(int x1, int y1, int x2, int y2, int layer, boolean arrowS, boolean arrowE, int arrowSt, int arrowLe, int arrowWi, int dashSt, String f, int size) { super(); arrowData=new Arrow(); arrowData.setArrowStart(arrowS); arrowData.setArrowEnd(arrowE); arrowData.setArrowHalfWidth(arrowWi); arrowData.setArrowLength(arrowLe); arrowData.setArrowStyle(arrowSt); dashStyle = dashSt; initPrimitive(-1, f, size); virtualPoint[0].x=x1; virtualPoint[0].y=y1; virtualPoint[1].x=x2; virtualPoint[1].y=y2; virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; setLayer(layer); } /** Constructor. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveLine(String f, int size) { super(); arrowData=new Arrow(); initPrimitive(-1, f, size); } /** Gets the number of control points used. @return the number of points used by the primitive */ public int getControlPointNumber() { return N_POINTS; } /** Get the control parameters of the given primitive. @return a vector of ParameterDescription containing each control parameter. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v=super.getControls(); arrowData.getControlsForArrow(v); ParameterDescription pd = new ParameterDescription(); pd.parameter=new DashInfo(dashStyle); pd.description=Globals.messages.getString("ctrl_dash_style"); pd.isExtension = true; v.add(pd); return v; } /** Set the control parameters of the given primitive. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. @return the next index in v to be scanned (if needed) after the execution of this function. */ public int setControls(List<ParameterDescription> v) { int i=super.setControls(v); i=arrowData.setParametersForArrow(v, i); ParameterDescription pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof DashInfo) { dashStyle=((DashInfo)pd.parameter).style; } else { System.out.println("Warning: 6-unexpected parameter!"+pd); } // Parameters validation and correction if(dashStyle>=Globals.dashNumber) { dashStyle=Globals.dashNumber-1; } if(dashStyle<0) { dashStyle=0; } return i; } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { if(!selectLayer(g,layerV)) { return; } drawText(g, coordSys, layerV, -1); if(changed) { changed=false; // in the line primitive, the first two virtual points represent // the beginning and the end of the segment to be drawn. x1=coordSys.mapX(virtualPoint[0].x,virtualPoint[0].y); y1=coordSys.mapY(virtualPoint[0].x,virtualPoint[0].y); x2=coordSys.mapX(virtualPoint[1].x,virtualPoint[1].y); y2=coordSys.mapY(virtualPoint[1].x,virtualPoint[1].y); // We store the coordinates in an ordered way in order to ease // the determination of the clip rectangle. if (x1>x2) { xa=x2; xb=x1; } else { xa=x1; xb=x2; } if (y1>y2) { ya=y2; yb=y1; } else { ya=y1; yb=y2; } // Calculate the width of the stroke in pixel. It should not // make our lines disappear, even at very small zoom ratios. // So we put a limit D_MIN. w = (float)(Globals.lineWidth*coordSys.getXMagnitude()); if (w<D_MIN) { w=D_MIN; } // Calculate the square of the length in pixel. length2=(xa-xb)*(xa-xb)+(ya-yb)*(ya-yb); arrows = arrowData.atLeastOneArrow(); // This correction solves bug #3101041 (old SF code) // We do need to apply a correction to the clip calculation // rectangle if necessary to take into account the arrow heads if (arrows) { int h=arrowData.prepareCoordinateMapping(coordSys); xa -= Math.abs(h); ya -= Math.abs(h); xb += Math.abs(h); yb += Math.abs(h); } xbpap1=xb-xa+1; ybpap1=yb-ya+1; } // This is a trick. We skip drawing the line if it is too short. if(length2>2) { if(!g.hitClip(xa,ya, xbpap1,ybpap1)) { return; } g.applyStroke(w, dashStyle); int xstart=x1; int ystart=y1; int xend=x2; int yend=y2; // If needed, we draw the arrows at the extremes. if (arrows) { arrowData.prepareCoordinateMapping(coordSys); if (arrowData.isArrowStart()) { PointG p=arrowData.drawArrow(g,x1,y1,x2,y2); // This fixes issue #172 // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if(arrowData.getArrowLength()>0) { xstart=p.x; ystart=p.y; } } if (arrowData.isArrowEnd()) { PointG p=arrowData.drawArrow(g,x2,y2,x1,y1); // This fixes issue #172 // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if(arrowData.getArrowLength()>0) { xend=p.x; yend=p.y; } } } g.drawLine(xstart,ystart,xend,yend); } } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array. @throws IOException if the arguments are incorrect or the primitive is invalid. */ public void parseTokens(String[] tokens, int nn) throws IOException { changed=true; // assert it is the correct primitive if ("LI".equals(tokens[0])) { // Line if (nn<5) { throw new IOException("Bad arguments on LI"); } // Load the points in the virtual points associated to the // current primitive. int x1 = virtualPoint[0].x=Integer.parseInt(tokens[1]); int y1 = virtualPoint[0].y=Integer.parseInt(tokens[2]); virtualPoint[1].x=Integer.parseInt(tokens[3]); virtualPoint[1].y=Integer.parseInt(tokens[4]); virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; if(nn>5) { parseLayer(tokens[5]); } // FidoCadJ extensions if(nn>6 && "FCJ".equals(tokens[6])) { int i=arrowData.parseTokens(tokens, 7); dashStyle = checkDashStyle(Integer.parseInt(tokens[i])); } } else { throw new IOException("LI: Invalid primitive:"+tokens[0]+ " programming error?"); } } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { // Here we check if the given point lies inside the text areas if(checkText(px, py)) { return 0; } // Check if the point is in the arrows. Correct the starting and ending // points if needed. if (arrowData.atLeastOneArrow()) { boolean r=false; boolean t=false; // We work with logic coordinates (default for MapCoordinates). MapCoordinates m=new MapCoordinates(); arrowData.prepareCoordinateMapping(m); PointG pp=new PointG(); if (arrowData.isArrowStart()) { t=arrowData.isInArrow(px, py, virtualPoint[0].x, virtualPoint[0].y, virtualPoint[1].x, virtualPoint[1].y, pp); } if (arrowData.isArrowEnd()) { r=arrowData.isInArrow(px, py, virtualPoint[1].x, virtualPoint[1].y, virtualPoint[0].x, virtualPoint[0].y, pp); } // Click on one of the arrows. if(r||t) { return 1; } } return GeometricDistances.pointToSegment( virtualPoint[0].x,virtualPoint[0].y, virtualPoint[1].x,virtualPoint[1].y, px,py); } /** Obtain a string command descripion of the primitive. @param extensions true if FidoCadJ extensions to the old FidoCAD format should be active. @return the FIDOCAD command line. */ public String toString(boolean extensions) { // A single point line without anything is not worth converting. if (name.length()==0 && value.length()==0 && virtualPoint[0].x==virtualPoint[1].x && virtualPoint[0].y==virtualPoint[1].y) { return ""; } String s= "LI "+virtualPoint[0].x+" "+virtualPoint[0].y+" "+ +virtualPoint[1].x+" "+virtualPoint[1].y+" "+ getLayer()+"\n"; if(extensions && (arrowData.atLeastOneArrow() || dashStyle>0 || name!=null && name.length()!=0) || value!=null && value.length()!=0) { String text = "0"; // We take into account that there may be some text associated // to that primitive. if (hasName() || hasValue()) { text = "1"; } s+="FCJ "+arrowData.createArrowTokens()+" "+dashStyle+ " "+text+"\n"; } // The false is needed since saveText should not write the FCJ tag. s+=saveText(false); return s; } /** Export the primitive on a vector graphic format. @param exp the export interface to employ. @param cs the coordinate mapping to employ. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { exportText(exp, cs, -1); exp.exportLine(cs.mapX(virtualPoint[0].x,virtualPoint[0].y), cs.mapY(virtualPoint[0].x,virtualPoint[0].y), cs.mapX(virtualPoint[1].x,virtualPoint[1].y), cs.mapY(virtualPoint[1].x,virtualPoint[1].y), getLayer(), arrowData.isArrowStart(), arrowData.isArrowEnd(), arrowData.getArrowStyle(), (int)(arrowData.getArrowLength()*cs.getXMagnitude()), (int)(arrowData.getArrowHalfWidth()*cs.getXMagnitude()), dashStyle, Globals.lineWidth*cs.getXMagnitude()); } /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public int getNameVirtualPointNumber() { return 2; } /** Get the number of the virtual point associated to the Value property @return the number of the virtual point associated to the Value property */ public int getValueVirtualPointNumber() { return 3; } }
16,530
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitivePCBPad.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitivePCBPad.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; /** Class to handle the PCB pad 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 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class PrimitivePCBPad extends GraphicPrimitive { private int rx; private int ry; private int sty; private int ri; // The radius of the rounded corner in logical units. This is hardcoded // here as it has been done for FidoCadJ, but one may consider let this // value to be changed by the user interactively private static final int CORNER_DIAMETER = 5; private boolean drawOnlyPads; // A PCB pad is defined by one points, plus text tags static final int N_POINTS=3; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. private int x1; // NOPMD private int y1; // NOPMD private int rrx; private int rry; private int xa; private int ya; private int rox; private int roy; private int rix; private int riy; private int rrx2; private int rry2; private int rix2; private int riy2; /** Gets the number of control points used. @return the number of points used by the primitive */ public int getControlPointNumber() { return N_POINTS; } /** Create a PCB pad @param x1 the x coordinate (logical unit). @param y1 the y coordinate (logical unit). @param wx the width of the pad @param wy the height of the pad @param radi the internal radius. @param st the style of the pad @param layer the layer to be used. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitivePCBPad(int x1, int y1, int wx, int wy, int radi, int st, int layer, String f, int size) { super(); initPrimitive(-1, f, size); virtualPoint[0].x=x1; virtualPoint[0].y=y1; virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; rx=wx; ry=wy; ri=radi; sty=st; setLayer(layer); } /** Constructor. Create an empty PCBPad object with all the sizes and dimensions set to zero. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitivePCBPad(String f, int size) { super(); rx=0; ry=0; sty=0; ri=0; initPrimitive(-1, f, size); } /** Check if the holes should be drawn. @return true for a PCBpad. */ @Override public boolean needsHoles() { return true; } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { if(!selectLayer(g,layerV)) { return; } drawText(g, coordSys, layerV, -1); if(changed) { changed=false; /* in the PCB pad primitive, the the virtual points represent the position of the pad to be drawn. */ x1=virtualPoint[0].x; y1=virtualPoint[0].y; xa=coordSys.mapXi(x1,y1,false); ya=coordSys.mapYi(x1,y1,false); rrx=Math.abs(xa-coordSys.mapXi(x1+rx,y1+ry, false)); rry=Math.abs(ya-coordSys.mapYi(x1+rx,y1+ry, false)); rrx2 = rrx/2; rry2 = rry/2; coordSys.trackPoint(xa-rrx2,ya-rry2); coordSys.trackPoint(xa+rrx2,ya+rry2); rox=Math.abs(xa-coordSys.mapXi(x1+CORNER_DIAMETER, y1+CORNER_DIAMETER, false)); roy=Math.abs(ya-coordSys.mapYi(x1+CORNER_DIAMETER, y1+CORNER_DIAMETER, false)); rix=Math.abs(xa-coordSys.mapXi(x1+ri,y1+ri, false)); riy=Math.abs(ya-coordSys.mapYi(x1+ri,y1+ri, false)); rix2 = rix/2; riy2 = riy/2; } // Exit if the primitive is offscreen. This is a simplification, but // ensures that the primitive is correctly drawn when it is // partially visible. if(!g.hitClip(xa-rrx2,ya-rry2, rrx, rry)) { return; } g.applyStroke(1, 0); if (drawOnlyPads) { g.setColor(g.getColor().white()); // Drill the hole g.fillOval(xa-rix2, ya-riy2,rix,riy); } else { switch(sty) { case 1: // Rectangular pad g.fillRect(xa-rrx2, ya-rry2,rrx,rry); break; case 2: // Rounded corner rectangular pad g.fillRoundRect(xa-rrx2, ya-rry2,rrx,rry,rox,roy); break; case 0: //NOPMD default: // Oval Pad g.fillOval(xa-rrx2, ya-rry2,rrx,rry); break; } } } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array. @throws IOException if the arguments are incorrect or the primitive is invalid. */ public void parseTokens(String[] tokens, int nn) throws IOException { changed=true; // assert it is the correct primitive if ("PA".equals(tokens[0])) { // PCB Area pad /* Example PA 752 50 15 15 4 1 1 */ if (nn<7) { throw new IOException("bad arguments on PA"); } // Load the points in the virtual points associated to the // current primitive. int x1 = virtualPoint[0].x=Integer.parseInt(tokens[1]); int y1 = virtualPoint[0].y=Integer.parseInt(tokens[2]); virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; rx=Integer.parseInt(tokens[3]); ry=Integer.parseInt(tokens[4]); ri=Integer.parseInt(tokens[5]); sty=Integer.parseInt(tokens[6]); if(nn>7) { parseLayer(tokens[7]); } } else { throw new IOException("PA: Invalid primitive:"+tokens[0]+ " programming error?"); } } /** Set the draw only pads flag. @param pd the value of the flag. */ public void setDrawOnlyPads(boolean pd) { drawOnlyPads=pd; } /** Get the control parameters of the given primitive. @return a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v=super.getControls(); ParameterDescription pd = new ParameterDescription(); pd.parameter= Integer.valueOf(rx); pd.description=Globals.messages.getString("ctrl_x_radius"); v.add(pd); pd = new ParameterDescription(); pd.parameter= Integer.valueOf(ry); pd.description=Globals.messages.getString("ctrl_y_radius"); v.add(pd); pd = new ParameterDescription(); pd.parameter= Integer.valueOf(ri); pd.description=Globals.messages.getString("ctrl_internal_radius"); v.add(pd); pd = new ParameterDescription(); pd.parameter= Integer.valueOf(sty); // A list should be better pd.description=Globals.messages.getString("ctrl_pad_style"); v.add(pd); return v; } /** Set the control parameters of the given primitive. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. @return the next index in v to be scanned (if needed) after the execution of this function. */ public int setControls(List<ParameterDescription> v) { int i=super.setControls(v); ParameterDescription pd; pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof Integer) { rx=((Integer)pd.parameter).intValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof Integer) { ry=((Integer)pd.parameter).intValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof Integer) { ri=((Integer)pd.parameter).intValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof Integer) { sty=((Integer)pd.parameter).intValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } return i; } /** Rotate the primitive. Here we just rotate 90° by 90° by swapping the x and y size of the pad @param bCounterClockWise specify if the rotation should be done counterclockwise. @param ix the x coordinate of the rotation point. @param iy the y coordinate of the rotation point. */ public void rotatePrimitive(boolean bCounterClockWise, int ix, int iy) { super.rotatePrimitive(bCounterClockWise, ix, iy); int swap=rx; rx=ry; ry=swap; } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { // Here we check if the given point lies inside the text areas if(checkText(px, py)) { return 0; } int distance=GeometricDistances.pointToPoint( virtualPoint[0].x,virtualPoint[0].y, px,py)-Math.min(rx,ry)/2; return distance>0?distance:0; } /** Obtain a string command descripion of the primitive. @param extensions true if FidoCadJ extensions to the old FidoCAD format should be active. @return the FIDOCAD command line. */ public String toString(boolean extensions) { String s = "PA "+virtualPoint[0].x+" "+virtualPoint[0].y+" "+ rx+" "+ry+" "+ri+" "+sty+" "+getLayer()+"\n"; s+=saveText(extensions); return s; } /** Export the primitive on a vector graphic format. @param exp the export interface to employ. @param cs the coordinate mapping to employ. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { exportText(exp, cs, -1); exp.exportPCBPad(cs.mapX(virtualPoint[0].x,virtualPoint[0].y), cs.mapY(virtualPoint[0].x,virtualPoint[0].y), sty, Math.abs(cs.mapX(virtualPoint[0].x+rx, virtualPoint[0].y+ry)- cs.mapX(virtualPoint[0].x,virtualPoint[0].y)), Math.abs(cs.mapY(virtualPoint[0].x+rx, virtualPoint[0].y+ry)- cs.mapY(virtualPoint[0].x,virtualPoint[0].y)), (int)(ri*cs.getXMagnitude()), getLayer(),drawOnlyPads); } /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public int getNameVirtualPointNumber() { return 1; } /** Get the number of the virtual point associated to the Value property @return the number of the virtual point associated to the Value property */ public int getValueVirtualPointNumber() { return 2; } }
14,738
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitivePolygon.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitivePolygon.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.dialogs.DashInfo; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.graphic.PointDouble; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.PolygonInterface; /** Class to handle the Polygon 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 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class PrimitivePolygon extends GraphicPrimitive { private int nPoints; private boolean isFilled; private int dashStyle; private PolygonInterface p; // If needed, we might increase this stuff. // In other words, we initially create space for storing 5 points and // we increase that if needed. int storageSize=5; // Some private data cached. private int xmin; private int ymin; private int width; private int height; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. private float w; /** Gets the number of control points used. @return the number of points used by the primitive */ public int getControlPointNumber() { return nPoints+2; } /** Constructor. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitivePolygon(String f, int size) { super(); isFilled=false; nPoints=0; p = null; initPrimitive(storageSize, f, size); } /** Create a polygon. Add points with the addPoint method. @param f specifies if the polygon should be filled @param layer the layer to be used. @param dashSt the dash style @param font the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitivePolygon(boolean f, int layer, int dashSt, String font, int size) { super(); p = null; initPrimitive(storageSize, font, size); nPoints=0; isFilled=f; dashStyle=dashSt; setLayer(layer); } /** Remove the control point of the polygon closest to the given coordinates, if the distance is less than a certain tolerance @param x the x coordinate of the target @param y the y coordinate of the target @param tolerance the tolerance */ public void removePoint(int x, int y, double tolerance) { // We can not have a polygon with less than three vertices if (nPoints<=3) { return; } double distance; double minDistance= GeometricDistances.pointToPoint(virtualPoint[0].x, virtualPoint[0].y,x,y); int selI=-1; for(int i=1;i<nPoints;++i) { distance = GeometricDistances.pointToPoint(virtualPoint[i].x, virtualPoint[i].y,x,y); if (distance<minDistance) { minDistance=distance; selI=i; } } // Check if the control node losest to the given coordinates // is closer than the given tolerance if(minDistance<=tolerance){ --nPoints; for(int i=0;i<nPoints;++i) { // Shift all the points subsequent to the one which needs // to be erased. if(i>=selI) { virtualPoint[i].x=virtualPoint[i+1].x; virtualPoint[i].y=virtualPoint[i+1].y; } changed=true; } } } /** Add a point in the polygon, by splitting the closes side to the point inserted. @param px x coordinates of the point to insert. @param py y coordinates of the point to insert. */ public void addPointClosest(int px, int py) { int[] xp=new int[storageSize]; int[] yp=new int[storageSize]; int k; for(k=0;k<nPoints;++k){ xp[k]=virtualPoint[k].x; yp[k]=virtualPoint[k].y; } // we calculate the distance between the // given point and all the segments composing the polygon and we // take the smallest one. int distance=(int)Math.sqrt((px-xp[0])*(px-xp[0])+ (py-yp[0])*(py-yp[0])); int j; int d; int minv=0; for(int i=0; i<nPoints; ++i) { j=i; if (j==nPoints-1) { j=-1; } d=GeometricDistances.pointToSegment(xp[i], yp[i], xp[j+1], yp[j+1], px,py); if(d<distance) { distance = d; minv=j+1; } } // Now minv contains the index of the vertex before the one which // should be entered. We begin to enter the new vertex at the end... addPoint(px, py); // ...then we do the swap for(int i=nPoints-1; i>minv; --i) { virtualPoint[i].x=virtualPoint[i-1].x; virtualPoint[i].y=virtualPoint[i-1].y; } virtualPoint[minv].x=px; virtualPoint[minv].y=py; changed = true; } /** Add a point at 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+2>=storageSize) { int oN=storageSize; int i; storageSize += 10; PointG[] nv = new PointG[storageSize]; for(i=0;i<oN;++i) { nv[i]=virtualPoint[i]; } for(;i<storageSize;++i) { nv[i]=new PointG(); } virtualPoint=nv; } // And now we enter the position of the point we are interested with virtualPoint[nPoints].x=x; virtualPoint[nPoints++].y=y; // We do need to shift the two points describing the position // of the text lines virtualPoint[getNameVirtualPointNumber()].x=x+5; virtualPoint[getNameVirtualPointNumber()].y=y+5; virtualPoint[getValueVirtualPointNumber()].x=x+5; virtualPoint[getValueVirtualPointNumber()].y=y+10; changed = true; } /** Store the polygon, which must be already calculated. @param coordSys the coordinates mapping system. @param g the graphic context. */ public void createPolygon(MapCoordinates coordSys, GraphicsInterface g) { int j; xmin = Integer.MAX_VALUE; ymin = Integer.MAX_VALUE; int xmax = -Integer.MAX_VALUE; int ymax = -Integer.MAX_VALUE; int x; int y; p=g.createPolygon(); p.reset(); for(j=0;j<nPoints;++j) { x = coordSys.mapX(virtualPoint[j].x,virtualPoint[j].y); y = coordSys.mapY(virtualPoint[j].x,virtualPoint[j].y); p.addPoint(x,y); if (x<xmin) { xmin=x; } if (x>xmax) { xmax=x; } if(y<ymin) { ymin=y; } if(y>ymax) { ymax=y; } } width = xmax-xmin; height = ymax-ymin; } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { if(!selectLayer(g,layerV)) { return; } drawText(g, coordSys, layerV, -1); if(changed) { changed=false; createPolygon(coordSys, g); w = (float)(Globals.lineWidth*coordSys.getXMagnitude()); if (w<D_MIN) { w=D_MIN; } } if(!g.hitClip(xmin,ymin, width, height)) { return; } g.applyStroke(w, dashStyle); // Here we implement a small optimization: when the polygon is very // small, it is not filled. if (isFilled && width>=2 && height >=2) { g.fillPolygon(p); } g.drawPolygon(p); // It seems that under MacOSX, drawing a polygon by cycling with // the lines is much more efficient than the drawPolygon method. // Probably, a further investigation is needed to determine if // this situation is the same with more recent Java runtimes // (mine is 1.5.something on an iMac G5 at 2 GHz and I made // the same comparison with the same results with a MacBook 2GHz). /* for(int i=0; i<nPoints-1; ++i) { g.drawLine(p.xpoints[i], p.ypoints[i], p.xpoints[i+1], p.ypoints[i+1]); } g.drawLine(p.xpoints[nPoints-1], p.ypoints[nPoints-1], p.xpoints[0], p.ypoints[0]); */ } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array @throws IOException if the arguments are incorrect or the primitive is invalid. */ public void parseTokens(String[] tokens, int nn) throws IOException { changed=true; // assert it is the correct primitive if ("PP".equals(tokens[0])||"PV".equals(tokens[0])) { if (nn<6) { throw new IOException("Bad arguments on PP/PV"); } // Load the points in the virtual points associated to the // current primitive. int j=1; int i=0; int x1 = 0; int y1 = 0; while(j<nn-1){ if (j+1<nn-1 && "FCJ".equals(tokens[j+1])) { break; } x1 = Integer.parseInt(tokens[j++]); y1 = Integer.parseInt(tokens[j++]); ++i; addPoint(x1,y1); } nPoints=i; virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; if(nn>j) { parseLayer(tokens[j++]); if(j<nn-1 && "FCJ".equals(tokens[j])) { dashStyle = checkDashStyle(Integer.parseInt(tokens[++j])); } ++j; } if ("PP".equals(tokens[0])) { isFilled=true; } else { isFilled=false; } } else { throw new IOException("PP/PV: Invalid primitive:"+tokens[0]+ " programming error?"); } } /** Get the control parameters of the given primitive. @return a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v=super.getControls(); ParameterDescription pd = new ParameterDescription(); pd.parameter=Boolean.valueOf(isFilled); pd.description=Globals.messages.getString("ctrl_filled"); v.add(pd); pd = new ParameterDescription(); pd.parameter=new DashInfo(dashStyle); pd.description=Globals.messages.getString("ctrl_dash_style"); pd.isExtension = true; v.add(pd); return v; } /** Set the control parameters of the given primitive. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. @return the next index in v to be scanned (if needed) after the execution of this function. */ public int setControls(List<ParameterDescription> v) { int i=super.setControls(v); ParameterDescription pd; pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof Boolean) { isFilled=((Boolean)pd.parameter).booleanValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof DashInfo) { dashStyle=((DashInfo)pd.parameter).style; } else { System.out.println("Warning: unexpected parameter!"+pd); } // Parameters validation and correction if(dashStyle>=Globals.dashNumber) { dashStyle=Globals.dashNumber-1; } if(dashStyle<0) { dashStyle=0; } return i; } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { // Here we check if the given point lies inside the text areas if(checkText(px, py)) { return 0; } int[] xp=new int[storageSize]; int[] yp=new int[storageSize]; int k; for(k=0;k<nPoints;++k){ xp[k]=virtualPoint[k].x; yp[k]=virtualPoint[k].y; } if(isFilled&&GeometricDistances.pointInPolygon(xp,yp,nPoints, px,py)) { return 1; } // If the curve is not filled, we calculate the distance between the // given point and all the segments composing the curve and we // take the smallest one. int distance=(int)Math.sqrt((px-xp[0])*(px-xp[0])+ (py-yp[0])*(py-yp[0])); int j; int d; for(int i=0; i<nPoints; ++i) { j=i; if (j==nPoints-1) { j=-1; } d=GeometricDistances.pointToSegment(xp[i], yp[i], xp[j+1], yp[j+1], px,py); if(d<distance) { distance = d; } } return distance; } /** Obtain a string command descripion of the primitive. @param extensions true if FidoCadJ extensions to the old FidoCAD format should be active. @return the FIDOCAD command line. */ public String toString(boolean extensions) { StringBuffer temp=new StringBuffer(25); if(isFilled) { temp.append("PP "); } else { temp.append("PV "); } for(int i=0; i<nPoints;++i) { temp.append(virtualPoint[i].x); temp.append(" "); temp.append(virtualPoint[i].y); temp.append(" "); } temp.append(getLayer()); temp.append("\n"); String cmd=temp.toString(); if(extensions && (dashStyle>0 || hasName() || hasValue())) { String text = "0"; if (name.length()!=0 || value.length()!=0) { text = "1"; } cmd+="FCJ "+dashStyle+" "+text+"\n"; } // The false is needed since saveText should not write the FCJ tag. cmd+=saveText(false); return cmd; } /** Export the primitive on a vector graphic format. @param exp the export interface to employ. @param cs the coordinate mapping to employ. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { exportText(exp, cs, -1); PointDouble[] vertices = new PointDouble[nPoints]; for(int i=0; i<nPoints;++i){ vertices[i]=new PointDouble(); vertices[i].x=cs.mapX(virtualPoint[i].x,virtualPoint[i].y); vertices[i].y=cs.mapY(virtualPoint[i].x,virtualPoint[i].y); } exp.exportPolygon(vertices, nPoints, isFilled, getLayer(), dashStyle, Globals.lineWidth*cs.getXMagnitude()); } /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public int getNameVirtualPointNumber() { return nPoints; } /** Get the number of the virtual point associated to the Value property @return the number of the virtual point associated to the Value property */ public int getValueVirtualPointNumber() { return nPoints+1; } }
18,648
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
GraphicPrimitive.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/GraphicPrimitive.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.dialogs.LayerInfo; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.graphic.DecoratedText; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.GraphicsInterface; /** GraphicPrimitive is an abstract class implementing the basic behaviour of a graphic primitive, which should be derived from 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 2008-2023 by Davide Bucci, phylum2 </pre> */ public abstract class GraphicPrimitive { // Tell that the dragging handle is invalid public static final int NO_DRAG=-1; // Tell that we are dragging the whole primitive public static final int DRAG_PRIMITIVE=-2; // Tell that we want to perform a selection in a rectangular area public static final int RECT_SELECTION=-3; // Indicates wether the primitive is selected or not public boolean selectedState; // Minimum width size of a line in pixel protected static final float D_MIN = 0.5f; // The layer public int layer; // The multiplication factor which is calculated for adjusting the screen // resolution, so that the size of handles or other important graphic stuff // is more or less the same. private float mult; // This is the screen resolution of the laptop on which I do most of the // development (DB), in dpi private static final int BASE_RESOLUTION=112; // Handle dimension. This is rescaled depending of the screen pixel // density. It is the size in pixel for a BASE_RESOLUTION dpi monitor. private static final int HANDLE_WIDTH=10; // Internal tolerance for snapping a double precision value to an integer. // Employed by roundIntelligently. private static final double INT_TOLERANCE=1E-5; // Array containing the points defining the primitive public PointG[] virtualPoint; // If changed is true, this means that the redraw operation should involve // an in-depth calculation of the primitive. Otherwise, a lot of // information is stored to speed up the redraw. protected boolean changed; private int macroFontSize; protected String macroFont; protected String name; protected String value; // Some caching data private LayerDesc currentLayer; private float alpha; private static float oldalpha=1.0f; private int old_layer=-1; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. private int xa; private int ya; private int xb; private int yb; // Text sizes in pixels private int h; private int th; private int w1; private int w2; // Text sizes in logical units. private int t_th; private int t_w1; private int t_w2; private int x2; // NOPMD private int y2; // NOPMD private int x3; // NOPMD private int y3; // NOPMD /* At first, non abstract methods */ /** Standard constructor. @param f the font to be employed for the associated text. @param size the size to be employed for the associated text. */ public GraphicPrimitive(String f, int size) { selectedState=false; layer=0; changed=true; name = ""; value = ""; mult = 1.0f; setMacroFontSize(size); macroFont=f; } /** Standard constructor. */ public GraphicPrimitive() { selectedState=false; layer=0; changed=true; name = ""; value = ""; mult = 1.0f; setMacroFontSize(4); macroFont=""; } /** Set the font to be used for name and value. @param f the font name. @param size the font size. */ public void setMacroFont(String f, int size) { macroFont = f; setMacroFontSize(size); changed=true; } /** Prepare the array of points for storing the different virtual points needed by the primitive. This method also prepares the name and value strings, as well as the font to be used. @param number if number is negative, obtain the number of points by using getControlPointNumber(); if it is positive, use the number of points given for the size of the array. @param font the font to be employed for the associated text. @param size the size to be employed for the associated text. */ public void initPrimitive(int number, String font, int size) { // Not very elegant. In fact, it would be better to use settings // present in DrawingModel, and not to have to use prefs here. setMacroFontSize(size); macroFont= font; name = ""; value = ""; int npoints=number; if (npoints<0) { npoints = getControlPointNumber(); } virtualPoint = new PointG[npoints]; for(int i=0;i<npoints;++i) { virtualPoint[i]=new PointG(); } } /** Get the font used for name and value @return the font name */ public String getMacroFont() { return macroFont; } /** Get the size of the macro font. @return the size of the macro font. */ public int getMacroFontSize() { return macroFontSize; } /** Set the size of the macro font. @param size the size of the macro font. */ public void setMacroFontSize(int size) { macroFontSize=size; // Silently correct a wrong size. This should never happen (the dialog // has a control, but avoids a wrong configuration to sneak somewhere // else. if(macroFontSize<=0) { macroFontSize=1; } } /** Check and correct if necessary the dashStyle number. @param dashStyle the style number to be checked. @return the checked dash style index. */ public int checkDashStyle(int dashStyle) { if(dashStyle>=Globals.dashNumber) { return Globals.dashNumber-1; } else if(dashStyle<0) { return 0; } return dashStyle; } /** Writes the macro name and value fields. This method uses heavily the caching system implemented via the precalculation of the sizes and positions. This means that the "changed" flag is tested, BUT NOT UPDATED, since this method should be one of the first to be called when a primitive implements its drawing. The primitive will HAVE TO update the "changed" flag accordingly to its needs, BEFORE calling drawText. @param g the graphic context. @param coordSys the current coordinate mapping system. @param layerV the list containing the layers. @param drawOnlyLayer current layer which should be drawn (or -1). */ protected void drawText(GraphicsInterface g, MapCoordinates coordSys, List layerV, int drawOnlyLayer) { // If this method is not needed, exit immediately. if (value==null && name==null) { return; } if ("".equals(value) && "".equals(name)) { return; } if(drawOnlyLayer>=0 && drawOnlyLayer!=getLayer()) { return; } if(changed) { // Calculate the positions of the text lines x2=virtualPoint[getNameVirtualPointNumber()].x; y2=virtualPoint[getNameVirtualPointNumber()].y; x3=virtualPoint[getValueVirtualPointNumber()].x; y3=virtualPoint[getValueVirtualPointNumber()].y; xa=coordSys.mapX(x2,y2); ya=coordSys.mapY(x2,y2); xb=coordSys.mapX(x3,y3); yb=coordSys.mapY(x3,y3); // At first, write the name and the value fields in the given // positions g.setFont(macroFont, (int)(macroFontSize*12*coordSys.getYMagnitude()/7+.5)); h = g.getFontAscent(); th = h+g.getFontDescent(); if(name==null) { w1=0; } else { w1 = g.getStringWidth(name); } if(value==null) { w2 = 0; } else { w2 = g.getStringWidth(value); } // Calculates the size of the text in logical units. This is // useful for calculating wether the user has clicked inside a // text line (see getDistanceToPoint) t_w1 = (int)(w1/coordSys.getXMagnitude()); t_w2 = (int)(w2/coordSys.getXMagnitude()); t_th = (int)(th/coordSys.getYMagnitude()); // Track the points for calculating the drawing size coordSys.trackPoint(xa,ya); coordSys.trackPoint(xa+w1,ya+th); coordSys.trackPoint(xb,yb); coordSys.trackPoint(xb+w2, yb+th); } // If there is no need to draw the text, just exit. if(!g.hitClip(xa,ya, w1,th) && !g.hitClip(xb,yb, w2,th)) { return; } // This is useful and faster for small zooms if(th<Globals.textSizeLimit) { g.drawLine(xa,ya, xa+w1-1,ya); g.drawLine(xb,yb, xb+w2-1,yb); return; } if(!changed) { g.setFont(macroFont, (int)(macroFontSize*12*coordSys.getYMagnitude()/7+.5)); } DecoratedText dt=new DecoratedText(g.getTextInterface()); /* The if's have been added thanks to this information: http://sourceforge.net/projects/fidocadj/forums/forum/997486 /topic/3474689?message=7798139 */ if (name!=null && name.length()!=0) { dt.drawString(name,xa,ya+h); } if (value!=null && value.length()!=0) { dt.drawString(value,xb,yb+h); } } /** Creates the text strings containing the name and value of the primitive. @param extensions if true, outputs the FCJ tag before the two TY commands. @return a string containing the commands. */ public String saveText(boolean extensions) { String subsFont; StringBuffer s2=new StringBuffer(); // Check if the font is default and in this case, just put an asterisk. if (macroFont.equals(Globals.defaultTextFont)) { subsFont = "*"; } else { StringBuffer s1=new StringBuffer(""); for (int i=0; i<macroFont.length(); ++i) { if(macroFont.charAt(i)==' ') { s1.append("++"); } else { s1.append(macroFont.charAt(i)); } } subsFont=s1.toString(); } // Write down the extensions only if needed if (name!=null && !"".equals(name) || value!=null && !"".equals(value)) { if(extensions) { s2.append("FCJ\n"); } s2.append("TY "); s2.append(virtualPoint[getNameVirtualPointNumber()].x); s2.append(" "); s2.append(virtualPoint[getNameVirtualPointNumber()].y); s2.append(" "); s2.append(macroFontSize*4/3); s2.append(" "); s2.append(macroFontSize); s2.append(" 0 0 "); s2.append(getLayer()); s2.append(" "); s2.append(subsFont); s2.append(" "); s2.append(name==null?"":name); s2.append("\n"); s2.append("TY "); s2.append(virtualPoint[getValueVirtualPointNumber()].x); s2.append(" "); s2.append(virtualPoint[getValueVirtualPointNumber()].y); s2.append(" "); s2.append(macroFontSize*4/3); s2.append(" "); s2.append(macroFontSize); s2.append(" 0 0 "); s2.append(getLayer()); s2.append(" "); s2.append(subsFont); s2.append(" "); s2.append(value==null?"":value); s2.append("\n"); } return s2.toString(); } /** Export the name and the value text lines associated to the primitive. This is done rather automatically by exploiting the export of the advanced text feature. It should be noted that the export is done only if necessary. @param exp the ExportInterface to be used. @param cs the coordinate mapping system to be used. @param drawOnlyLayer the layer to be drawn (or -1). @throws IOException if something wrong happens during the export, such as it is, or becomes impossible to write on the output file. */ public void exportText(ExportInterface exp, MapCoordinates cs, int drawOnlyLayer) throws IOException { double size= Math.abs(cs.mapXr(macroFontSize,macroFontSize)-cs.mapXr(0,0)); // Export the text associated to the name and value of the macro if(drawOnlyLayer<0 || drawOnlyLayer==getLayer()) { if(!"".equals(name)) { exp.exportAdvText (cs.mapX( virtualPoint[getNameVirtualPointNumber()].x, virtualPoint[getNameVirtualPointNumber()].y), cs.mapY(virtualPoint[getNameVirtualPointNumber()].x, virtualPoint[getNameVirtualPointNumber()].y), (int)size, (int)(size*12/7+.5), macroFont, false, false, false, 0, getLayer(), name); } if(!"".equals(value)) { exp.exportAdvText (cs.mapX( virtualPoint[getValueVirtualPointNumber()].x, virtualPoint[getValueVirtualPointNumber()].y), cs.mapY( virtualPoint[getValueVirtualPointNumber()].x, virtualPoint[getValueVirtualPointNumber()].y), (int)size, (int)(size*12/7+.5), macroFont, false, false, false, 0, getLayer(), value); } } } /** Check if the given point (in logical units) lies inside one of the two text lines associated to the primitive. @param px the x coordinates of the given point. @param py the y coordinates of the given point. @return true if the point is inside one of the two text lines. */ public boolean checkText(int px, int py) { return !"".equals(name) && GeometricDistances.pointInRectangle( virtualPoint[getNameVirtualPointNumber()].x, virtualPoint[getNameVirtualPointNumber()].y,t_w1,t_th,px,py) || !"".equals(value) && GeometricDistances.pointInRectangle( virtualPoint[getValueVirtualPointNumber()].x, virtualPoint[getValueVirtualPointNumber()].y,t_w2,t_th,px,py); } /** Reads the TY line describing the "value" field @param tokens the array of tokens to be parsed @param nn the number of tokens to be parsed. @throws IOException if something goes wrong, for example there is an invalid primitive found at an incongruous place (probably a programming error). */ public void setValue(String[] tokens, int nn) throws IOException { StringBuffer txtb=new StringBuffer(); int j=8; changed=true; if ("TY".equals(tokens[0])) { // Text (advanced) if (nn<9) { throw new IOException("Bad arguments on TY"); } virtualPoint[getValueVirtualPointNumber()].x= Integer.parseInt(tokens[1]); virtualPoint[getValueVirtualPointNumber()].y= Integer.parseInt(tokens[2]); if("*".equals(tokens[8])) { macroFont = Globals.defaultTextFont; } else { macroFont = tokens[8].replaceAll("\\+\\+"," "); } // Adding the following line should fix bug #3522962 setMacroFontSize(Integer.parseInt(tokens[4])); while(j<nn-1){ txtb.append(tokens[++j]); if (j<nn-1) { txtb.append(" "); } } value=txtb.toString(); } else { throw new IOException("Invalid primitive: "+tokens[0]+ " programming error?"); } } /** Reads the TY line describing the "name" field @param tokens the array of tokens to be parsed @param nn the number of tokens to be parsed. @throws IOException if something goes wrong, for example there is an invalid primitive found at an incongruous place (probably a programming error). */ public void setName(String[] tokens, int nn) throws IOException { StringBuffer txtb=new StringBuffer(); int j=8; changed=true; if ("TY".equals(tokens[0])) { // Text (advanced) if (nn<9) { throw new IOException("bad arguments on TY"); } virtualPoint[getNameVirtualPointNumber()].x= Integer.parseInt(tokens[1]); virtualPoint[getNameVirtualPointNumber()].y= Integer.parseInt(tokens[2]); while(j<nn-1) { txtb.append(tokens[++j]); if (j<nn-1) { txtb.append(" "); } } name=txtb.toString(); } else { throw new IOException("Invalid primitive:"+tokens[0]+ " programming error?"); } } /** Specifies that the current primitive has been modified or not. If it is true, during the redraw all parameters should be calulated from scratch. @param c the wanted changed state. */ public void setChanged(boolean c) { changed=c; } /** Get the first control point of the primitive @return the coordinates of the first control point of the object. */ public PointG getFirstPoint() { return virtualPoint[0]; } /** Move the primitive. @param dx the relative x displacement (logical units) @param dy the relative y displacement (logical units) */ public void movePrimitive(int dx, int dy) { for(int a=0; a<getControlPointNumber(); ++a) { virtualPoint[a].x+=dx; virtualPoint[a].y+=dy; } changed=true; } /** Mirror the primitive. Adapted from Lorenzo Lutti's original code. @param xPos is the symmetry axis */ public void mirrorPrimitive(int xPos) { int xtmp; for(int a=0; a<getControlPointNumber(); ++a) { xtmp = virtualPoint[a].x; virtualPoint[a].x = 2*xPos - xtmp; } changed=true; } /** Rotate the primitive. Adapted from Lorenzo Lutti's original code. @param bCounterClockWise specify if the rotation should be done counterclockwise. @param ix the x coordinate of the center of rotation @param iy the y coordinate of the center of rotation */ public void rotatePrimitive(boolean bCounterClockWise, int ix, int iy) { PointG ptTmp=new PointG(); PointG pt=new PointG(); pt.x=ix; pt.y=iy; for(int b=0; b<getControlPointNumber(); ++b) { ptTmp.x = virtualPoint[b].x; ptTmp.y = virtualPoint[b].y; if(bCounterClockWise) { virtualPoint[b].x = pt.x + ptTmp.y-pt.y; virtualPoint[b].y = pt.y - (ptTmp.x-pt.x); // NOPMD } else { virtualPoint[b].x = pt.x - (ptTmp.y-pt.y); // NOPMD virtualPoint[b].y = pt.y + ptTmp.x-pt.x; } } changed=true; } /** Specifies that only the given layer should be drawn. This is in practice useful only for macros, since they have an internal layer structure. @param i the layer to be used. */ public void setDrawOnlyLayer (int i) { // Normally, this does nothing, except for macros. } /** Returns true if the primitive contains the specified layer. @param l the index of the layer to check. @return true or false, if the specified layer is contained in the primitive. */ public boolean containsLayer(int l) { return l==layer; } /** Obtains the maximum layer which is contained by this primitive. It should redefined for macros, since they can contain more than one layer. The standard implementation returns the layer of the primitive, since this is the only one which is used. @return the maximum value of the layer contained in the primitive. */ public int getMaxLayer() { return layer; } /** Set the primitive as selected. @param s the new state. */ final public void setSelected(boolean s) { selectedState=s; } /** Get the selection state of the primitive. @return true if the primitive is selected, false otherwise. */ final public boolean getSelected() { return selectedState; } /** Get the layer of the current primitive. @return the layer number. */ public final int getLayer() { return layer; } /** Parse the current string and interpret it as a layer indication. If this is correct, the layer is saved in the current primitive. @param token the token which corresponds to the layer. */ public void parseLayer(String token) { int l; try { l=Integer.parseInt(token); } catch (NumberFormatException e) { // We are unable to get the layer. Just suppose it's zero. l=0; } // We do check if everything is OK. if (l<0 || l>=LayerDesc.MAX_LAYERS) { layer=0; } else { layer=l; } changed=true; } /** Set the layer of the current primitive. A quick check is done. @param l the desired layer. */ final public void setLayer(int l) { if (l<0 || l>=LayerDesc.MAX_LAYERS) { layer=0; } else { layer=l; } changed=true; } /** Treat the current layer. In particular, select the corresponding color in the actual graphic context. If the primitive is selected, select the corrisponding color. This is a speed sensitive context. @param g the graphic context used for the drawing. @param layerV a LayerDesc vector with the descriptions of the layers being used. @return true if the layer is visible, false otherwise. */ protected final boolean selectLayer(GraphicsInterface g, List layerV) { // At first, we see if we need to retrieve the current layer. // It is important to check also the changed flag, since if not we // would now show changes apported to the layer being drawn when it is // modified. if(old_layer != layer || changed) { if(layer>=layerV.size()) { layer=layerV.size()-1; } currentLayer= (LayerDesc)layerV.get(layer); old_layer = layer; } // If the layer is not visible, we just exit, returning false. This // will made the caller not to draw the graphical element. if (!currentLayer.isVisible) { return false; } if(selectedState) { // We change the color for selected objects g.activateSelectColor(currentLayer); } else { if(g.getColor()!=currentLayer.getColor() || oldalpha!=alpha) { g.setColor(currentLayer.getColor()); alpha=currentLayer.getAlpha(); oldalpha = alpha; g.setAlpha(alpha); } } return true; } /** Draw the handles for the current primitive. @param g the graphic context to be used. @param cs the coordinate mapping used. */ public void drawHandles(GraphicsInterface g, MapCoordinates cs) { int xa; int ya; g.setColor(g.getColor().red()); g.applyStroke(2.0f,0); // Calculation of the reasonable multiplication factor. mult=g.getScreenDensity()/BASE_RESOLUTION; int sizeX=(int)Math.round(mult*HANDLE_WIDTH); int sizeY=(int)Math.round(mult*HANDLE_WIDTH); for(int i=0;i<getControlPointNumber();++i) { if (!testIfValidHandle(i)) { continue; } xa=cs.mapX(virtualPoint[i].x,virtualPoint[i].y); ya=cs.mapY(virtualPoint[i].x,virtualPoint[i].y); if(!g.hitClip(xa-sizeX/2,ya-sizeY/2, sizeX,sizeY)) { continue; } // A handle is a small red rectangle g.fillRect(xa-sizeX/2,ya-sizeY/2, sizeX,sizeY); } } /** Tells if the pointer is on an handle. The handles associated to the name and value strings are not considered if they are not defined. @param cs the coordinate mapping used. @param px the x (screen) coordinate of the pointer. @param py the y (screen) coordinate of the pointer. @return NO_DRAG if the pointer is not on an handle, or the index of the selected handle. */ public int onHandle(MapCoordinates cs, int px, int py) { int xa; int ya; int increase = 5; int hw2=(int)Math.round(mult*HANDLE_WIDTH/2); int hl2=(int)Math.round(mult*HANDLE_WIDTH/2); for(int i=0;i<getControlPointNumber();++i) { if (!testIfValidHandle(i)) { continue; } xa=cs.mapX(virtualPoint[i].x,virtualPoint[i].y); ya=cs.mapY(virtualPoint[i].x,virtualPoint[i].y); // Recognize if we have clicked on a handle. Basically, we check // if the point lies inside the rectangle given by the handle. if(GeometricDistances.pointInRectangle( xa-hw2-(int)Math.round(mult*increase), ya-hl2-(int)Math.round(mult*increase), (int)Math.round(mult*(HANDLE_WIDTH+2*increase)), (int)Math.round(mult*(HANDLE_WIDTH+2*increase)), px,py)) { return i; } } return NO_DRAG; } /** Select the primitive if one of its virtual point is in the specified 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 xa; int ya; for(int i=0;i<getControlPointNumber();++i) { if (!testIfValidHandle(i)) { continue; } xa=virtualPoint[i].x; ya=virtualPoint[i].y; if(px<=xa && xa<px+w && py<=ya&& ya< py+h) { setSelected(true); return true; } } return false; } /** Function to determine if the name field is set @return true if the name field is set */ public boolean hasName() { return name!=null && name.length()!=0; } /** Function to determine if the value field is set @return true if the value field is set */ public boolean hasValue() { return value!=null && value.length()!=0; } /** Determines whether the handle specified is valid or is disabled. Are disabled in particular the handles associated to the name and value strings when they are not defined. @return true if the handle is active */ protected boolean testIfValidHandle(int i) { if (i==getNameVirtualPointNumber()) { if (name==null) { return false; } if(name.length()==0) { return false; } } if (i==getValueVirtualPointNumber()) { if(value==null) { return false; } if(value.length()==0) { return false; } } return true; } /** Get the control parameters of the given primitive. Each primitive should probably overload this version. We give here a very general implementation, allowing to change only virtual points. @return a vector of ParameterDescription containing each control parameter. The first parameters should always be the name and the value fields, followed by the layer. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v = new Vector<ParameterDescription>(10); ParameterDescription pd = new ParameterDescription(); pd.parameter=(name==null?"":name); pd.description=Globals.messages.getString("ctrl_name"); pd.isExtension = true; v.add(pd); pd = new ParameterDescription(); pd.parameter=(value==null?"":value); pd.description=Globals.messages.getString("ctrl_value"); pd.isExtension = true; v.add(pd); pd = new ParameterDescription(); pd.parameter=new LayerInfo(layer); pd.description=Globals.messages.getString("ctrl_layer"); v.add(pd); return v; } /** Set the control parameters of the given primitive. Each primitive should probably overload this version. We give here a very general implementation, allowing to change only virtual points. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. @return the index of the next parameter which remains to be read after this function ends. */ public int setControls(List<ParameterDescription> v) { int i=0; ParameterDescription pd; changed=true; pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof String) { name=((String)pd.parameter); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof String) { value=((String)pd.parameter); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd = (ParameterDescription)v.get(i); // Check, just for sure... if (pd.parameter instanceof LayerInfo) { layer=((LayerInfo)pd.parameter).getLayer(); } else { System.out.println("Warning: unexpected parameter! (layer)"); } return ++i; } /** This function should be redefined if the graphic primitive needs holes. This implies that the redraw strategy should include a final pass to be sure that the holes are drawn correctly. Override this function if the primitive needs holes. The standard implementation just returns false. @return true if there are elements in the drawing which need holes. */ public boolean needsHoles() { return false; } /** Specify whether during the drawing phase the primitive should draw only the pads. This is useful only for the PrimitiveMacro and PrimitivePCBPad subclasses. @param t the wanted state. */ public void setDrawOnlyPads(boolean t) { // Does nothing, except for macros and pcbpads. } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerDesc the layer description. */ public abstract void draw(GraphicsInterface g, MapCoordinates coordSys, List layerDesc); /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the correct layer. An IOException is thrown if there is an error. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array. @throws IOException if something goes wrong. */ public abstract void parseTokens(String[] tokens, int nn) throws IOException; /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @param px the x coordinate of the given point. @param py the y coordinate of the given point. @return the distance to point in logical coordinates. */ public abstract int getDistanceToPoint(int px, int py); /** Gets the number of control points used. @return the number of points used by the primitive */ public abstract int getControlPointNumber(); /** Obtain a string command descripion of the primitive. @param extensions produce a string eventually containing FidoCadJ extensions over the original FidoCad format. @return the FIDOCAD command line. */ public abstract String toString(boolean extensions); /** Each graphic primitive should call the appropriate exporting method of the export interface specified. @param exp the export interface that should be used. @param cs the actual coordinate mapping. @throws IOException if an error occurs, for example because it becomes impossible to access to the files being written. */ public abstract void export(ExportInterface exp, MapCoordinates cs) throws IOException; /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public abstract int getNameVirtualPointNumber(); /** Get the number of the virtual point associated to the Value property. @return the number of the virtual point associated to the Value property. */ public abstract int getValueVirtualPointNumber(); /** Get the size of the current element. @return the size. */ public DimensionG getSize() { GraphicPrimitive p = this; int qx = 0; int qy = 0; for (int i = 0; i < p.getControlPointNumber(); i++) { if (i == p.getNameVirtualPointNumber() || i == p.getValueVirtualPointNumber()) { continue; } for (int j = i + 1; j < p.getControlPointNumber(); j++) { if (j == p.getNameVirtualPointNumber() || j == p.getValueVirtualPointNumber()) { continue; } qx = Math.abs(p.virtualPoint[i].x - p.virtualPoint[j].x); qy = Math.abs(p.virtualPoint[i].y - p.virtualPoint[j].y); } } return new DimensionG(qx,qy); } /** Get the minimum x and y values of all control points of the element. @return the minimum x and y coordinates. */ public PointG getPosition() { GraphicPrimitive p = this; int qx = Integer.MAX_VALUE; int qy = Integer.MAX_VALUE; for (int i = 0; i < p.getControlPointNumber(); i++) { if (i == p.getNameVirtualPointNumber() || i == p.getValueVirtualPointNumber()) { continue; } if (p.virtualPoint[i].x<qx) { qx = p.virtualPoint[i].x; } if (p.virtualPoint[i].y<qy) { qy = p.virtualPoint[i].y; } } return new PointG(qx,qy); } /** Check wether we are very close to an integer value. In this case, the output will be done as an integer. This improves backward compatibility in cases where the fractional part is not needed. The output code is also marginally more compact. For example, roundIntelligently(1.00) produces "1" whereas roundIntelligently(1.23) produces "1.23". @param v the value to be rounded. @return a string containing the rounded value. */ public StringBuffer roundIntelligently(double v) { StringBuffer sb; if(Math.abs(v-Math.round(v))<INT_TOLERANCE) { int w=(int)Math.round(v); sb = new StringBuffer(""+w); } else { sb = new StringBuffer(""+v); } return sb; } }
39,194
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MacroDesc.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/MacroDesc.java
package net.sourceforge.fidocadj.primitives; /** Class MacroDesc provides a standard description of the macro. It provides its name, its description and its category <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-2013 by Davide Bucci </pre> */ public class MacroDesc { public String name; // The one which is shown public String key; // Unequivocally used to identify the macro public String description; // The list of commands included in the macro public String category; // The category on which the macro is put public String library; // The library name public String filename; // The library file name public int level; // The level (0: macro 1:category 2:library) // The library file name is usually identical to the library name, except // when an existing library is already present with a different filename. // This is a legacy from previous versions of FidoCadJ. /** Standard constructor. Give the macro's name, description and category. @param ke the key to be used. @param na the name of the macro. @param de the description of the macro (the list of commands). @param cat the category of the macro. @param lib the library name (prefix). @param fn the library file name. */ public MacroDesc(String ke, String na, String de, String cat, String lib, String fn) { name = na; key=ke; description = de; category = cat; library = lib; filename = fn; level = 0; } /** Provide a text describing the macro, usually for debug purposes. @return the description. */ @Override public String toString() { String s; switch (level) { case 1: s=category; break; case 2: s=library; break; case 0: default: s=name; break; } return s.trim(); } }
2,771
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitiveOval.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitiveOval.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.dialogs.DashInfo; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; /** Class to handle the Oval 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 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class PrimitiveOval extends GraphicPrimitive { // An oval is defined by two points. static final int N_POINTS=4; private boolean isFilled; private int dashStyle; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. private int xa; private int ya; private int xb; private int yb; private int x1; // NOPMD private int x2; // NOPMD private int y1; // NOPMD private int y2; // NOPMD private float w; /** Gets the number of control points used. @return the number of points used by the primitive */ public int getControlPointNumber() { return N_POINTS; } /** Standard constructor. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveOval(String f, int size) { super(); isFilled=false; initPrimitive(-1, f, size); } /** Create an oval defined by two points. @param x1 the start x coordinate (logical unit). @param y1 the start y coordinate (logical unit). @param x2 the end x coordinate (logical unit). @param y2 the end y coordinate (logical unit). @param f specifies if the ellipse should be filled. @param layer the layer to be used. @param dashSt the style of the dashing to be used. @param font the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveOval(int x1, int y1, int x2, int y2, boolean f, int layer, int dashSt, String font, int size) { super(); initPrimitive(-1, font, size); virtualPoint[0].x=x1; virtualPoint[0].y=y1; virtualPoint[1].x=x2; virtualPoint[1].y=y2; virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; isFilled=f; dashStyle =dashSt; setLayer(layer); } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { if(!selectLayer(g,layerV)) { return; } drawText(g, coordSys, layerV, -1); // in the oval primitive, the first two virtual points represent // the two corners of the oval diagonal if(changed) { changed=false; x1=coordSys.mapX(virtualPoint[0].x,virtualPoint[0].y); y1=coordSys.mapY(virtualPoint[0].x,virtualPoint[0].y); x2=coordSys.mapX(virtualPoint[1].x,virtualPoint[1].y); y2=coordSys.mapY(virtualPoint[1].x,virtualPoint[1].y); // Sort the coordinates if (x1>x2) { xa=x2; xb=x1; } else { xa=x1; xb=x2; } if (y1>y2) { ya=y2; yb=y1; } else { ya=y1; yb=y2; } coordSys.trackPoint(xa,ya); coordSys.trackPoint(xb,yb); w = (float)(Globals.lineWidth*coordSys.getXMagnitude()); if (w<D_MIN) { w=D_MIN; } } if(!g.hitClip(xa,ya, xb-xa+1,yb-ya+1)) { return; } g.applyStroke(w, dashStyle); // Draw the oval, filled or not. if (isFilled) { g.fillOval(xa,ya,xb-xa,yb-ya); } else { if(xa!=xb && ya!=yb) { g.drawOval(xa,ya,xb-xa,yb-ya); } else { // Degenerate to a single line. g.drawLine(xa,ya,xb,yb); } } } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array @throws IOException if the arguments are incorrect or the primitive is invalid. */ public void parseTokens(String[] tokens, int nn) throws IOException { changed=true; // assert it is the correct primitive if ("EV".equals(tokens[0])||"EP".equals(tokens[0])) { // Oval if (nn<5) { throw new IOException("Bad arguments on EV/EP"); } int x1 = virtualPoint[0].x=Integer.parseInt(tokens[1]); int y1 = virtualPoint[0].y=Integer.parseInt(tokens[2]); virtualPoint[1].x=Integer.parseInt(tokens[3]); virtualPoint[1].y=Integer.parseInt(tokens[4]); virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; if(nn>5) { parseLayer(tokens[5]); } if("EP".equals(tokens[0])) { isFilled=true; } else { isFilled=false; } if(nn>6 && "FCJ".equals(tokens[6])) { dashStyle = checkDashStyle(Integer.parseInt(tokens[7])); } } else { throw new IOException("EV/EP: Invalid primitive:"+tokens[0]+ " programming error?"); } } /** Get the control parameters of the given primitive. @return a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v=super.getControls(); ParameterDescription pd = new ParameterDescription(); pd.parameter=Boolean.valueOf(isFilled); pd.description=Globals.messages.getString("ctrl_filled"); v.add(pd); pd = new ParameterDescription(); pd.parameter=new DashInfo(dashStyle); pd.description=Globals.messages.getString("ctrl_dash_style"); pd.isExtension = true; v.add(pd); return v; } /** Set the control parameters of the given primitive. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. @return the next index in v to be scanned (if needed) after the execution of this function. */ public int setControls(List<ParameterDescription> v) // NOPMD bug in PMD? { int i=super.setControls(v); ParameterDescription pd; pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof Boolean) { isFilled=((Boolean)pd.parameter).booleanValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof DashInfo) { dashStyle=((DashInfo)pd.parameter).style; } else { System.out.println("Warning: unexpected parameter!"+pd); } // Parameters validation and correction if(dashStyle>=Globals.dashNumber) { dashStyle=Globals.dashNumber-1; } if(dashStyle<0) { dashStyle=0; } return i; } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { // Here we check if the given point lies inside the text areas if(checkText(px, py)) { return 0; } int xa=Math.min(virtualPoint[0].x,virtualPoint[1].x); int ya=Math.min(virtualPoint[0].y,virtualPoint[1].y); int xb=Math.max(virtualPoint[0].x,virtualPoint[1].x); int yb=Math.max(virtualPoint[0].y,virtualPoint[1].y); if(isFilled){ if(GeometricDistances.pointInEllipse(xa,ya,xb-xa,yb-ya,px,py)) { return 0; } else { return 1000; } } else { return GeometricDistances.pointToEllipse(xa,ya, xb-xa,yb-ya,px,py); } } /** Obtain a string command descripion of the primitive. @param extensions true if FidoCadJ extensions to the old FidoCAD format should be active. @return the FIDOCAD command line. */ public String toString(boolean extensions) { String cmd; if (isFilled) { cmd="EP "; } else { cmd="EV "; } cmd+=virtualPoint[0].x+" "+virtualPoint[0].y+" "+ +virtualPoint[1].x+" "+virtualPoint[1].y+" "+ getLayer()+"\n"; if(extensions && (dashStyle>0 || hasName() || hasValue())) { String text = "0"; if (name.length()!=0 || value.length()!=0) { text = "1"; } cmd+="FCJ "+dashStyle+" "+text+"\n"; } // The false is needed since saveText should not write the FCJ tag. cmd+=saveText(false); return cmd; } /** Export the primitive on a vector graphic format. @param exp the export interface to employ. @param cs the coordinate mapping to employ. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { exportText(exp, cs, -1); exp.exportOval(cs.mapX(virtualPoint[0].x,virtualPoint[0].y), cs.mapY(virtualPoint[0].x,virtualPoint[0].y), cs.mapX(virtualPoint[1].x,virtualPoint[1].y), cs.mapY(virtualPoint[1].x,virtualPoint[1].y), isFilled, getLayer(), dashStyle, Globals.lineWidth*cs.getXMagnitude()); } /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public int getNameVirtualPointNumber() { return 2; } /** Get the number of the virtual point associated to the Value property @return the number of the virtual point associated to the Value property */ public int getValueVirtualPointNumber() { return 3; } }
12,982
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitivePCBLine.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitivePCBLine.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; /** Class to handle the PCB line 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 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class PrimitivePCBLine extends GraphicPrimitive { private float width; // A PCB segment is defined by two points. static final int N_POINTS=4; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. private int xa; private int ya; private int xb; // NOPMD private int yb; // NOPMD private int x1; private int y1; private int x2; private int y2; private float wiPix; private int xbpap1; private int ybpap1; /** Gets the number of control points used. @return the number of points used by the primitive */ public int getControlPointNumber() { return N_POINTS; } /** Standard constructor. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitivePCBLine(String f, int size) { super(); width=0; initPrimitive(-1, f, size); } /** Create a PCB line between two points @param x1 the start x coordinate (logical unit). @param y1 the start y coordinate (logical unit). @param x2 the end x coordinate (logical unit). @param y2 the end y coordinate (logical unit). @param w specifies the line width. @param layer the layer to be used. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitivePCBLine(int x1, int y1, int x2, int y2, float w, int layer, String f, int size) { super(); initPrimitive(-1, f, size); virtualPoint[0].x=x1; virtualPoint[0].y=y1; virtualPoint[1].x=x2; virtualPoint[1].y=y2; virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; width=w; setLayer(layer); } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { if(!selectLayer(g,layerV)) { return; } drawText(g, coordSys, layerV, -1); /* in the PCB line primitive, the first two virtual points represent the beginning and the end of the segment to be drawn. */ if(changed) { changed=false; x1=coordSys.mapX(virtualPoint[0].x,virtualPoint[0].y); y1=coordSys.mapY(virtualPoint[0].x,virtualPoint[0].y); x2=coordSys.mapX(virtualPoint[1].x,virtualPoint[1].y); y2=coordSys.mapY(virtualPoint[1].x,virtualPoint[1].y); wiPix=(float)Math.abs(coordSys.mapXr(virtualPoint[0].x, virtualPoint[0].y) -coordSys.mapXr(virtualPoint[0].x+width, virtualPoint[0].y+width)); xa=(int)(Math.min(x1, x2)-wiPix/2.0f); ya=(int)(Math.min(y1, y2)-wiPix/2.0f); xb=(int)(Math.max(x1, x2)+wiPix/2.0f); yb=(int)(Math.max(y1, y2)+wiPix/2.0f); coordSys.trackPoint(xa,ya); coordSys.trackPoint(xb,yb); xbpap1=xb-xa+1; ybpap1=yb-ya+1; } // Exit if the primitive is offscreen. This is a simplification, but // ensures that the primitive is correctly drawn when it is // partially visible. if(!g.hitClip(xa,ya, xbpap1,ybpap1)) { return; } g.applyStroke(wiPix, 0); g.drawLine(x1, y1, x2, y2); } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array. @throws IOException if the arguments are incorrect or the primitive is invalid. */ public void parseTokens(String[] tokens, int nn) throws IOException { changed=true; // assert it is the correct primitive if ("PL".equals(tokens[0])) { // Line if (nn<6) { throw new IOException("Bad arguments on PL"); } // Load the points in the virtual points associated to the // current primitive. int x1 = virtualPoint[0].x=Integer.parseInt(tokens[1]); int y1 = virtualPoint[0].y=Integer.parseInt(tokens[2]); virtualPoint[1].x=Integer.parseInt(tokens[3]); virtualPoint[1].y=Integer.parseInt(tokens[4]); virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; width=Float.parseFloat(tokens[5]); if(nn>6) { parseLayer(tokens[6]); } } else { throw new IOException("PL: Invalid primitive:"+tokens[0]+ " programming error?"); } } /** Get the control parameters of the given primitive. @return a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v=super.getControls(); ParameterDescription pd = new ParameterDescription(); pd.parameter= Float.valueOf(width); pd.description=Globals.messages.getString("ctrl_width"); v.add(pd); return v; } /** Set the control parameters of the given primitive. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. @return the next index in v to be scanned (if needed) after the execution of this function. */ public int setControls(List<ParameterDescription> v) { int i=super.setControls(v); ParameterDescription pd; pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof Float) { width=((Float)pd.parameter).floatValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } return i; } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { // Here we check if the given point lies inside the text areas if(checkText(px, py)) { return 0; } int distance=(int)(GeometricDistances.pointToSegment( virtualPoint[0].x,virtualPoint[0].y, virtualPoint[1].x,virtualPoint[1].y, px,py)-width/2.0f); return distance<0?0:distance; } /** Obtain a string command descripion of the primitive. @param extensions true if FidoCadJ extensions to the old FidoCAD format should be active. @return the FIDOCAD command line. */ public String toString(boolean extensions) { String s= "PL "+virtualPoint[0].x+" "+virtualPoint[0].y+" "+ +virtualPoint[1].x+" "+virtualPoint[1].y+" "+ roundIntelligently(width)+" "+getLayer()+"\n"; s+=saveText(extensions); return s; } /** Export the primitive on a vector graphic format. @param exp the export interface to employ. @param cs the coordinate mapping to employ. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { exportText(exp, cs, -1); exp.exportPCBLine(cs.mapX(virtualPoint[0].x,virtualPoint[0].y), cs.mapY(virtualPoint[0].x,virtualPoint[0].y), cs.mapX(virtualPoint[1].x,virtualPoint[1].y), cs.mapY(virtualPoint[1].x,virtualPoint[1].y), (int)(width*cs.getXMagnitude()), getLayer()); } /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public int getNameVirtualPointNumber() { return 2; } /** Get the number of the virtual point associated to the Value property @return the number of the virtual point associated to the Value property */ public int getValueVirtualPointNumber() { return 3; } }
11,049
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitiveAdvText.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitiveAdvText.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.dialogs.LayerInfo; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.FontG; import net.sourceforge.fidocadj.graphic.nil.GraphicsNull; /** Class to handle the advanced text 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 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class PrimitiveAdvText extends GraphicPrimitive { private String txt; private int six; private int siy; private int sty; private int o; private String fontName; private boolean recalcSize; // Text style patterns static final int TEXT_BOLD=1; static final int TEXT_MIRRORED=4; static final int TEXT_ITALIC=2; // Maximum and minimum size allowed for the text. static final int MAXSIZE=2000; static final int MINSIZE=1; // A text is defined by one point. static final int N_POINTS=1; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. private int xaSCI; // NOPMD private int yaSCI; // NOPMD private int orientationSCI; // NOPMD private int hSCI; // NOPMD private int thSCI; // NOPMD private int wSCI; // NOPMD private int[] xpSCI, ypSCI; // NOPMD private boolean mirror; private int orientation; private int h; private int th; private int w; private double ymagnitude; private boolean coordmirroring; private int x1; // NOPMD private int y1; // NOPMD private int xa; private int ya; private int qq; private double xyfactor; private double si; // NOPMD private double co; // NOPMD private boolean needsStretching; /** Gets the number of control points used. @return the number of points used by the primitive. */ public int getControlPointNumber() { return N_POINTS; } /** Standard "empty" constructor. */ public PrimitiveAdvText() { super(); six=3; siy=4; o=0; txt=""; fontName = Globals.defaultTextFont; virtualPoint = new PointG[N_POINTS]; for(int i=0;i<N_POINTS;++i) { virtualPoint[i]=new PointG(); } changed=true; recalcSize=true; } /** Complete constructor. @param x the x position of the control point of the text. @param y the y position of the control point of the text. @param sx the x size of the font. @param sy the y size of the font. @param fn font name. @param or the orientation of the text. @param st the style of the text. @param t the text to be used. @param l the layer to be used. */ public PrimitiveAdvText(int x, int y, int sx, int sy, String fn, int or, int st, String t, int l) { this(); virtualPoint[0]=new PointG(x,y); six=sx; siy=sy; sty=st; txt=t; o=or; fontName=fn; setLayer(l); changed=true; recalcSize=true; } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { if(!selectLayer(g,layerV)) { return; } /* For this: http://sourceforge.net/tracker/?func=detail&aid=2908420&group_id= 274886&atid=1167997 we are now checking if the text is "" before printing it. */ if(txt.length()==0) { return; } changed=true; ymagnitude=coordSys.getYMagnitude(); coordmirroring=coordSys.getMirror(); if(changed) { changed=false; mirror=false; recalcSize =true; /* in the simple text primitive, the the virtual point represents the position of the text to be drawn. */ x1=virtualPoint[0].x; y1=virtualPoint[0].y; xa=coordSys.mapX(x1,y1); ya=coordSys.mapY(x1,y1); /* siy is the font horizontal size in mils (1/1000 of an inch). 1 typographical point is 1/72 of an inch. */ g.setFont(fontName, six*12*coordSys.getYMagnitude()/7+.5, (sty & TEXT_ITALIC)!=0, (sty & TEXT_BOLD)!=0); orientation=o; mirror=false; if((sty & TEXT_MIRRORED)!=0){ mirror=!mirror; orientation=-orientation; } if (six==0 || siy==0) { siy=10; six=7; } orientation-=coordSys.getOrientation()*90; if(coordmirroring){ mirror=!mirror; orientation=-orientation; } // Determination of the size of the text string. h = g.getFontAscent(); th = h+g.getFontDescent(); w = g.getStringWidth(txt); xyfactor=1.0; needsStretching = false; if(siy/six != 10/7){ // Create a transformation for the font. xyfactor=(double)siy/(double)six*22.0/40.0; needsStretching = true; } if(orientation==0) { if (mirror){ coordSys.trackPoint(xa-w,ya); coordSys.trackPoint(xa,ya+(int)(th*xyfactor)); } else { coordSys.trackPoint(xa+w,ya); coordSys.trackPoint(xa,ya+(int)(h*xyfactor)); } } else { if(mirror){ si=Math.sin(Math.toRadians(-orientation)); co=Math.cos(Math.toRadians(-orientation)); } else { si=Math.sin(Math.toRadians(orientation)); co=Math.cos(Math.toRadians(orientation)); } // Calculate the bounding box. double bbx1=xa; double bby1=ya; double bbx2=xa+th*si; double bby2=ya+th*co*xyfactor; double bbx3=xa+w*co+th*si; double bby3=ya+(th*co-w*si)*xyfactor; double bbx4=xa+w*co; double bby4=ya-w*si*xyfactor; if(mirror) { bbx2=xa-th*si; bbx3=xa-w*co-th*si; bbx4=xa-w*co; } coordSys.trackPoint((int)bbx1,(int)bby1); coordSys.trackPoint((int)bbx2,(int)bby2); coordSys.trackPoint((int)bbx3,(int)bby3); coordSys.trackPoint((int)bbx4,(int)bby4); } qq=(int)(ya/xyfactor); } g.drawAdvText(xyfactor, xa, ya, qq, h, w, h, needsStretching, orientation, mirror, txt); } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array. @throws IOException if the arguments are incorrect or a problem occurs. */ public void parseTokens(String[] tokens, int nn) throws IOException { // assert it is the correct primitive changed=true; recalcSize = true; if ("TY".equals(tokens[0])) { // Text (advanced) if (nn<9) { throw new IOException("bad arguments on TY"); } virtualPoint[0].x=Integer.parseInt(tokens[1]); virtualPoint[0].y=Integer.parseInt(tokens[2]); // We may accept non-integer data in the future. siy=(int)Math.round(Double.parseDouble(tokens[3])); six=(int)Math.round(Double.parseDouble(tokens[4])); checkSizes(); o=Integer.parseInt(tokens[5]); sty=Integer.parseInt(tokens[6]); parseLayer(tokens[7]); int j=8; StringBuffer txtb=new StringBuffer(); if("*".equals(tokens[8])) { fontName = Globals.defaultTextFont; } else { fontName = tokens[8].replaceAll("\\+\\+"," "); } /* siy is the font horizontal size in mils (1/1000 of an inch). 1 typographical point is 1/72 of an inch. */ while(j<nn-1){ txtb.append(tokens[++j]); if (j<nn-1) { txtb.append(" "); } } txt=txtb.toString(); } else if ("TE".equals(tokens[0])) { // Text (simple) if (nn<4) { throw new IOException("bad arguments on TE"); } virtualPoint[0].x=Integer.parseInt(tokens[1]); virtualPoint[0].y=Integer.parseInt(tokens[2]); // Default sizes and styles six=3; siy=4; o=0; sty=0; int j=2; txt=""; while(j<nn-1) { txt+=tokens[++j]+" "; } // In the original simple text primitive, the layer was not // handled. Here we just suppose it is always 0. parseLayer("0"); } else { throw new IOException("Invalid primitive:"+ " programming error?"); } } /** Check and correct if necessary the text size range. */ public void checkSizes() { // Safety checks! if(siy<MINSIZE) { siy=MINSIZE; } if(six<MINSIZE) { six=MINSIZE; } if(siy>MAXSIZE) { siy=MAXSIZE; } if(six>MAXSIZE) { six=MAXSIZE; } } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { // This calculation takes a lot of time, since we need to obtain the // size of the font used, calculate the area which is active for the // mouse and so on. For this reason, we make it only when necessary, // by exploiting exactly the same principle of the optimized drawing // routines. if (changed||recalcSize) { if(changed) { GraphicsNull gSCI = new GraphicsNull(); gSCI.setFont(fontName, (int)(six*12.0/7.0+.5), (sty & TEXT_ITALIC)!=0, (sty & TEXT_BOLD)!=0); hSCI = gSCI.getFontAscent(); thSCI = hSCI+gSCI.getFontDescent(); wSCI = gSCI.getStringWidth(txt); } else { hSCI =(int)(h/ymagnitude); thSCI=(int)(th/ymagnitude); wSCI=(int)(w/ymagnitude); } // recalcSize is set to true when the draw method detects that the // graphical appearance of the text should be recalculated. recalcSize = false; xaSCI=virtualPoint[0].x; yaSCI=virtualPoint[0].y; orientationSCI=o; if(siy/six != 10/7){ hSCI=(int)Math.round(hSCI*((double)siy*22.0/40.0/(double)six)); thSCI=(int)Math.round((double)thSCI*((double)siy* 22.0/40.0/(double)six)); } // TODO: the calculation fails when mirrored text or rotated is // included into a mirrored or rotated macro. // Corrections for the mirrored text. if((sty & TEXT_MIRRORED)!=0){ orientationSCI=-orientationSCI; wSCI=-wSCI; } if (coordmirroring) { //orientationSCI=-orientationSCI; wSCI=-wSCI; } // If there is a tilt of the text, we calculate the four corner // of the tilted text area and we put them in a polygon. if(orientationSCI!=0){ double si=Math.sin(Math.toRadians(orientation)); double co=Math.cos(Math.toRadians(orientation)); xpSCI=new int[4]; ypSCI=new int[4]; xpSCI[0]=xaSCI; ypSCI[0]=yaSCI; xpSCI[1]=(int)(xaSCI+thSCI*si); ypSCI[1]=(int)(yaSCI+thSCI*co); xpSCI[2]=(int)(xaSCI+thSCI*si+wSCI*co); ypSCI[2]=(int)(yaSCI+thSCI*co-wSCI*si); xpSCI[3]=(int)(xaSCI+wSCI*co); ypSCI[3]=(int)(yaSCI-wSCI*si); } } if(orientationSCI==0) { if(GeometricDistances.pointInRectangle(Math.min(xaSCI, xaSCI+wSCI),yaSCI,Math.abs(wSCI),thSCI,px,py)) { return 0; } } else { if(GeometricDistances.pointInPolygon(xpSCI,ypSCI,4, px,py)) { return 0; } } // It is better not to obtain Integer.MAX_VALUE, but a value which // is very large yet smaller than Integer.MAX_VALUE. In fact, in some // cases, a test is done to see if a layer is present and this test // tries to see if the distance of a symbol is less than // Integer.MAX_VALUE, as this should be true when a symbol is present // and visible on the screen. return Integer.MAX_VALUE/2; } /** Get the control parameters of the given primitive. @return a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v = new Vector<ParameterDescription>(10); ParameterDescription pd = new ParameterDescription(); pd.parameter=txt; pd.description=Globals.messages.getString("ctrl_text"); v.add(pd); pd = new ParameterDescription(); pd.parameter=new LayerInfo(getLayer()); pd.description=Globals.messages.getString("ctrl_layer"); v.add(pd); pd = new ParameterDescription(); pd.parameter=Integer.valueOf(six); pd.description=Globals.messages.getString("ctrl_xsize"); v.add(pd); pd = new ParameterDescription(); pd.parameter=Integer.valueOf(siy); pd.description=Globals.messages.getString("ctrl_ysize"); v.add(pd); pd = new ParameterDescription(); pd.parameter=Integer.valueOf(o); pd.description=Globals.messages.getString("ctrl_angle"); v.add(pd); pd = new ParameterDescription(); pd.parameter=Boolean.valueOf((sty & TEXT_MIRRORED)!=0); pd.description=Globals.messages.getString("ctrl_mirror"); v.add(pd); pd = new ParameterDescription(); pd.parameter=Boolean.valueOf((sty & TEXT_ITALIC)!=0); pd.description=Globals.messages.getString("ctrl_italic"); v.add(pd); pd = new ParameterDescription(); pd.parameter=Boolean.valueOf((sty & TEXT_BOLD)!=0); pd.description=Globals.messages.getString("ctrl_boldface"); v.add(pd); pd = new ParameterDescription(); pd.parameter=new FontG(fontName); pd.description=Globals.messages.getString("ctrl_font"); v.add(pd); return v; } /** Set the control parameters of the given primitive. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. @return the next index in v to be scanned (if needed) after the execution of this function. */ public int setControls(List<ParameterDescription> v) { int i=0; changed=true; recalcSize = true; ParameterDescription pd; pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof String) { txt=(String)pd.parameter; } else { System.out.println("Warning: unexpected parameter!"+pd); } pd = (ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof LayerInfo) { setLayer(((LayerInfo)pd.parameter).getLayer()); } else { System.out.println("Warning: unexpected parameter!"); } pd=(ParameterDescription)v.get(i); ++i; if (pd.parameter instanceof Integer) { six=((Integer)pd.parameter).intValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i); ++i; if (pd.parameter instanceof Integer) { siy=((Integer)pd.parameter).intValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i); ++i; if (pd.parameter instanceof Integer) { o=((Integer)pd.parameter).intValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof Boolean) { sty = ((Boolean)pd.parameter).booleanValue()? sty | TEXT_MIRRORED: sty & (~TEXT_MIRRORED); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof Boolean) { sty = ((Boolean)pd.parameter).booleanValue() ? sty | TEXT_ITALIC: sty & (~TEXT_ITALIC); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof Boolean) { sty= ((Boolean)pd.parameter).booleanValue() ? sty | TEXT_BOLD: sty & (~TEXT_BOLD); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof FontG) { fontName = ((FontG)pd.parameter).getFamily(); } else { System.out.println("Warning: unexpected parameter!"+pd); } checkSizes(); return i; } /** Rotate the primitive. Here we just rotate 90° by 90° @param bc specify if the rotation should be done counterclockwise. @param ix the x coordinate of the rotation center @param iy the y coordinate of the rotation center */ public void rotatePrimitive(boolean bc, int ix, int iy) { boolean bCounterClockWise=bc; super.rotatePrimitive(bCounterClockWise, ix, iy); int po=o/90; if((sty & TEXT_MIRRORED)!=0) { bCounterClockWise=!bCounterClockWise; } if (bCounterClockWise) { po=++po%4; } else { po=(po+3)%4; } o=90*po; } /** Mirror the primitive. For the text, it is different than for the other primitives, since we just need to toggle the mirror flag. @param xPos is the symmetry axis */ public void mirrorPrimitive(int xPos) { super.mirrorPrimitive(xPos); sty ^= TEXT_MIRRORED; changed=true; recalcSize = true; } /** Obtain a string command descripion of the primitive. @param extensions true if the FidoCadJ extensions to the old FidoCAD formad should be taken into account. @return the FidoCad code corresponding to the primitive. */ public String toString(boolean extensions) { String subsFont; // The standard font is indicated with an asterisk if (fontName.equals(Globals.defaultTextFont)) { subsFont = "*"; } else { StringBuffer s=new StringBuffer(""); // All spaces are substituted with "++" in order to avoid problems // while parsing. for (int i=0; i<fontName.length(); ++i) { if(fontName.charAt(i)==' ') { s.append("++"); } else { s.append(fontName.charAt(i)); } } subsFont=s.toString(); } return "TY "+virtualPoint[0].x+" "+virtualPoint[0].y+" "+siy+" " +six+" "+o+" "+sty+" "+getLayer()+" "+subsFont+" "+txt+"\n"; } /** Export the text primitive on a vector graphic format. @param exp the export interface to employ. @param cs the coordinate mapping to employ. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { int resultingO=o-cs.getOrientation()*90; exp.exportAdvText (cs.mapX(virtualPoint[0].x,virtualPoint[0].y), cs.mapY(virtualPoint[0].x,virtualPoint[0].y), (int)Math.abs(cs.mapXr(six,six)-cs.mapXr(0,0)), (int)Math.abs(cs.mapYr(siy,siy)-cs.mapYr(0,0)), fontName, (sty & TEXT_BOLD)!=0, (sty & TEXT_MIRRORED)!=0, (sty & TEXT_ITALIC)!=0, resultingO, getLayer(), txt); } /** Get the number of the virtual point associated to the Name property. @return the number of the virtual point associated to the Name property. */ public int getNameVirtualPointNumber() { return -1; } /** Get the number of the virtual point associated to the Value property. @return the number of the virtual point associated to the Value property. */ public int getValueVirtualPointNumber() { return -1; } }
24,085
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitiveMacro.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitiveMacro.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.circuit.controllers.SelectionActions; import net.sourceforge.fidocadj.circuit.controllers.EditorActions; import net.sourceforge.fidocadj.circuit.controllers.ParserActions; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.circuit.views.Drawing; import net.sourceforge.fidocadj.circuit.views.Export; import net.sourceforge.fidocadj.layers.LayerDesc; /** Class to handle the macro primitive. Code is somewhat articulated since I use recursion (a macro is another drawing seen as an unbreakable symbol). <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 PrimitiveMacro extends GraphicPrimitive { static final int N_POINTS=3; private final Map<String, MacroDesc> library; private final List<LayerDesc> layers; private int o; // Macro orientation private boolean m; // Macro mirroring private boolean drawOnlyPads; private int drawOnlyLayer; private boolean alreadyExported; private DrawingModel macro; private final MapCoordinates macroCoord; private boolean selected; private String macroName; private String macroDesc; private boolean exportInvisible; private Drawing drawingAgent; // Stored data for caching private int x1; // NOPMD private int y1; // NOPMD /** Some layers may be shown or hidden by the user. Therefore, in some cases they may be exported or not. Set if invisible layers should be exported. @param s the value export invisible. True means that invisible layers will be exported. */ public void setExportInvisible(boolean s) { exportInvisible = s; } /** Gets the number of control points used. @return the number of points used by the primitive */ public int getControlPointNumber() { return N_POINTS; } /** Constructor. @param lib the library to be inherited. @param l the list of layers. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveMacro(Map<String, MacroDesc>lib, List<LayerDesc> l, String f, int size) { super(); library=lib; layers=l; drawOnlyPads=false; drawOnlyLayer=-1; macro=new DrawingModel(); macroCoord=new MapCoordinates(); changed=true; initPrimitive(-1, f, size); macroStore(layers); } /** Constructor. @param lib the library to be inherited. @param l the list of layers. @param x the x coordinate of the control point of the macro. @param y the y coordinate of the control point of the macro. @param keyT the key to be used to uniquely identify the macro (it will be converted to lowercase). @param na the name to be shown. @param xa the x coordinate of the name of the macro. @param ya the y coordinate of the name of the macro. @param va the value to be shown. @param xv the x coordinate of the value of the macro. @param yv the y coordinate of the value of the macro. @param macroF the font to be used for the name and the value of the macro. @param macroS the size of the font. @param oo the macro orientation. @param mm the macro mirroring. @throws IOException if an unrecognized macro is found. */ public PrimitiveMacro(Map<String, MacroDesc> lib, List<LayerDesc> l, int x, int y, String keyT, String na, int xa, int ya, String va, int xv, int yv, String macroF, int macroS, int oo, boolean mm) throws IOException { super(); initPrimitive(-1, macroF, macroS); library=lib; layers=l; String key=keyT.toLowerCase(new Locale("en")); macro=new DrawingModel(); macroCoord=new MapCoordinates(); changed=true; setMacroFontSize(macroS); o=oo; m=mm; // Store the points of the macro and the text describing it. virtualPoint[0].x=x; virtualPoint[0].y=y; virtualPoint[1].x=xa; virtualPoint[1].y=ya; virtualPoint[2].x=xv; virtualPoint[2].y=yv; name=na; value=va; MacroDesc macro=(MacroDesc)library.get(key); // Check if the macro description is contained in the database // containing all the libraries. if (macro==null){ throw new IOException("Unrecognized macro " + key); } macroDesc = macro.description; macroName = key; macroFont = macroF; macroStore(layers); } /** Returns true if the macro contains the specified layer. This is a calculation done at the DrawingModel level. @param l the layer to be checked. @return true if the layer is contained in the drawing and therefore should be drawn. */ public boolean containsLayer(int l) { return macro.containsLayer(l); } /** Draw the macro contents. @param g the graphic context. @param coordSys the coordinate system. @param layerV the vector containing all layers. */ private void drawMacroContents(GraphicsInterface g, MapCoordinates coordSys) { /* in the macro primitive, the the virtual point represents the position of the reference point of the macro to be drawn. */ if(changed) { changed = false; x1=virtualPoint[0].x; y1=virtualPoint[0].y; macroCoord.setXMagnitude(coordSys.getXMagnitude()); macroCoord.setYMagnitude(coordSys.getYMagnitude()); macroCoord.setXCenter(coordSys.mapXr(x1,y1)); macroCoord.setYCenter(coordSys.mapYr(x1,y1)); macroCoord.setOrientation((o+coordSys.getOrientation())%4); macroCoord.mirror=m ^ coordSys.mirror; macroCoord.isMacro=true; macroCoord.resetMinMax(); macro.setChanged(true); } if(getSelected()) { new SelectionActions(macro).setSelectionAll(true); selected = true; } else if (selected) { new SelectionActions(macro).setSelectionAll(false); selected = false; } macro.setDrawOnlyLayer(drawOnlyLayer); macro.setDrawOnlyPads(drawOnlyPads); drawingAgent = new Drawing(macro); drawingAgent.draw(g,macroCoord); if (macroCoord.getXMax()>macroCoord.getXMin() && macroCoord.getYMax()>macroCoord.getYMin()) { coordSys.trackPoint(macroCoord.getXMax(),macroCoord.getYMax()); coordSys.trackPoint(macroCoord.getXMin(),macroCoord.getYMin()); } } /** Specifies that the current primitive has been modified or not. If it is true, during the redraw all parameters should be calulated from scratch. @param c the value of the parameter. */ public void setChanged(boolean c) { super.setChanged(c); macro.setChanged(c); } /** Parse and store the tokenized version of the macro. @layerV the array containing the layer description to be inherited. */ private void macroStore(List<LayerDesc> layerV) { macro.setLibrary(library); // Inherit the library macro.setLayers(layerV); // Inherit the layers changed=true; if (macroDesc!=null) { ParserActions pa = new ParserActions(macro); pa.parseString(new StringBuffer(macroDesc)); // Recursive call } } /** Set the layer vector. @param layerV the layer vector. */ public void setLayers(List<LayerDesc> layerV) { macro.setLayers(layerV); } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { // Macros are *always* on layer 0 (they can contain elements to be // drawn, of course, on other layers). setLayer(0); if(selectLayer(g,layerV)) { drawText(g, coordSys, layerV, drawOnlyLayer); } drawMacroContents(g, coordSys); } /** Set the Draw Only Pads mode. @param pd the wanted value */ public void setDrawOnlyPads(boolean pd) { drawOnlyPads=pd; } /** Set the Draw Only Layer mode. @param la the layer that should be drawn. */ public void setDrawOnlyLayer(int la) { drawOnlyLayer=la; } /** Get the maximum index of the layers contained in the macro. @return the maximum index of layers contained in the macro. */ public int getMaxLayer() { return macro.getMaxLayer(); } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array @throws IOException if the arguments are incorrect or the primitive is invalid. */ public void parseTokens(String[] tokens, int nn) throws IOException { // assert it is the correct primitive changed=true; if ("MC".equals(tokens[0])) { // Line if (nn<6) { throw new IOException("Bad arguments on MC"); } // Load the points in the virtual points associated to the // current primitive. virtualPoint[0].x=Integer.parseInt(tokens[1]); virtualPoint[0].y=Integer.parseInt(tokens[2]); virtualPoint[1].x=virtualPoint[0].x+10; virtualPoint[1].y=virtualPoint[0].y+10; virtualPoint[2].x=virtualPoint[0].x+10; virtualPoint[2].y=virtualPoint[0].y+5; o=Integer.parseInt(tokens[3]); // orientation m=Integer.parseInt(tokens[4])==1; // mirror macroName=tokens[5]; // This is useful when a filename contains spaces. However, it does // not work when there are two or more consecutive spaces. for (int i=6; i<nn; ++i) { macroName+=" "+tokens[i]; } // The macro key recognition is made case insensitive by converting // internally all keys to lower case. macroName=macroName.toLowerCase(new Locale("en")); // Let's see if the macro is recognized and store it. MacroDesc macro=(MacroDesc)library.get(macroName); if (macro==null){ throw new IOException("Unrecognized macro '" + macroName+"'"); } macroDesc = macro.description; macroStore(layers); } else { throw new IOException("MC: Invalid primitive:"+tokens[0]+ " programming error?"); } } /** Check if the macro contains elements which need to draw holes. @return true if the macro contains elements requiring holes, false otherwise. */ public boolean needsHoles() { return drawingAgent.getNeedHoles(); } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { /* in the macro primitive, the the first virtual point represents the position of the reference point of the macro to be drawn. */ int x1=virtualPoint[0].x; int y1=virtualPoint[0].y; int dt=Integer.MAX_VALUE; // Here we check if the given point lies inside the text areas if(checkText(px, py)) { return 0; } // If not, we need to see more throughly about the inners of the macro int vx=px-x1+100; int vy= py-y1+100; // This is a sort of inelegant code: we need to translate the position // given in the macro's coordinate system. if(m) { switch(o){ case 1: vx=py-y1+100; vy=px-x1+100; break; case 2: vx=px-x1+100; vy=-(py-y1)+100; break; case 3: vx=-(py-y1)+100; vy=-(px-x1)+100; break; case 0: vx=-(px-x1)+100; vy=py-y1+100; break; default: vx=0; vy=0; break; } } else { switch(o){ case 1: vx=py-y1+100; vy=-(px-x1)+100; break; case 2: vx=-(px-x1)+100; vy=-(py-y1)+100; break; case 3: vx=-(py-y1)+100; vy=px-x1+100; break; case 0: vx=px-x1+100; vy=py-y1+100; break; default: vx= 0; vy= 0; break; } } if (macroDesc==null) { System.out.println("1-Unrecognized macro "+ "WARNING this can be a programming problem..."); } else { SelectionActions sa = new SelectionActions(macro); EditorActions edt=new EditorActions(macro, sa, null); return Math.min(edt.distancePrimitive(vx, vy), dt); } return Integer.MAX_VALUE; } /** Select the primitive if one of its virtual point is in the specified 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) { // Here is a trick: if there is at least one active layer, // distancePrimitive will return a value less than the maximum. SelectionActions sa = new SelectionActions(macro); EditorActions edt=new EditorActions(macro, sa, null); if (edt.distancePrimitive(0, 0)<Integer.MAX_VALUE) { return super.selectRect(px, py, w, h); } else { return false; } } /** Get the macro orientation @return the orientation. */ public int getOrientation() { return o; } /** Determine wether the macro is mirrored or not @return true if the macro is mirrored */ public boolean isMirrored() { return m; } /** Rotate the primitive. For a macro, it is different than for the other primitive, since we need to rotate its coordinate system. @param bCounterClockWise specify if the rotation should be done counterclockwise. @param ix the x coordinate of the center of rotation @param iy the y coordinate of the center of rotation */ public void rotatePrimitive(boolean bCounterClockWise,int ix, int iy) { super.rotatePrimitive(bCounterClockWise, ix, iy); if (bCounterClockWise) { o=(o+3)%4; } else { o=++o%4; } changed=true; } /** Mirror the primitive. For a macro, it is different than for the other primitive, since we just need to toggle the mirror flag. @param xpos the x value of the pivot axis. */ public void mirrorPrimitive(int xpos) { super.mirrorPrimitive(xpos); m ^= true; changed=true; } /** Obtain a string command descripion of the primitive. @param extensions true if FidoCadJ extensions to the old FidoCAD format should be active. @return the FIDOCAD command line. */ public String toString(boolean extensions) { String mirror="0"; if(m) { mirror="1"; } String s="MC "+virtualPoint[0].x+" "+virtualPoint[0].y+" "+o+" " +mirror+" "+macroName+"\n"; s+=saveText(extensions); return s; } /** Get the control parameters of the given primitive. @return a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v=new Vector<ParameterDescription>(10); ParameterDescription pd = new ParameterDescription(); pd.parameter=name; pd.description=Globals.messages.getString("ctrl_name"); pd.isExtension = true; v.add(pd); pd = new ParameterDescription(); pd.parameter=value; pd.description=Globals.messages.getString("ctrl_value"); pd.isExtension = true; v.add(pd); return v; } /** Set the control parameters of the given primitive. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. @return the next index in v to be scanned (if needed) after the execution of this function. */ public int setControls(List<ParameterDescription> v) { int i=0; ParameterDescription pd; changed=true; pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof String) { name=((String)pd.parameter); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof String) { value=((String)pd.parameter); } else { System.out.println("Warning: unexpected parameter!"+pd); } return i; } /** Ensure that the next time the macro is exported, it will be done. Macro that are not expanded during exportation does not need to be replicated thru the layers. For this reason, there is an inibition system which is activated. Calling this method resets the inibition flag. */ public void resetExport() { alreadyExported=false; } /** Each graphic primitive should call the appropriate exporting method of the export interface specified. @param exp the export interface that should be used. @param cs the actual coordinate mapping. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { if(alreadyExported) { return; } // Call the macro interface, to see if the macro should be expanded if (exp.exportMacro(cs.mapX(virtualPoint[0].x, virtualPoint[0].y), cs.mapY(virtualPoint[0].x, virtualPoint[0].y), m, o*90, macroName, macroDesc, name, cs.mapX(virtualPoint[1].x, virtualPoint[1].y), cs.mapY(virtualPoint[1].x, virtualPoint[1].y), value, cs.mapX(virtualPoint[2].x, virtualPoint[2].y), cs.mapY(virtualPoint[2].x, virtualPoint[2].y), macroFont, (int)(cs.mapYr(getMacroFontSize(),getMacroFontSize())- cs.mapYr(0,0)), library)) { alreadyExported = true; return; } /* in the macro primitive, the virtual point represents the position of the reference point of the macro to be drawn. */ int x1=virtualPoint[0].x; int y1=virtualPoint[0].y; MapCoordinates macroCoord=new MapCoordinates(); macroCoord.setXMagnitude(cs.getXMagnitude()); macroCoord.setYMagnitude(cs.getYMagnitude()); macroCoord.setXCenter(cs.mapXr(x1,y1)); macroCoord.setYCenter(cs.mapYr(x1,y1)); macroCoord.setOrientation((o+cs.getOrientation())%4); macroCoord.mirror=m ^ cs.mirror; macroCoord.isMacro=true; macro.setDrawOnlyLayer(drawOnlyLayer); if(getSelected()) { new SelectionActions(macro).setSelectionAll(true); } macro.setDrawOnlyPads(drawOnlyPads); new Export(macro).exportDrawing(exp, exportInvisible, macroCoord); exportText(exp, cs, drawOnlyLayer); } /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public int getNameVirtualPointNumber() { return 1; } /** Get the number of the virtual point associated to the Value property @return the number of the virtual point associated to the Value property */ public int getValueVirtualPointNumber() { return 2; } /** Get the current macro description string. @return the macro description string. */ public String getMacroDesc() { return macroDesc; } /** Set the current macro description string. @param macroDesc the macro description string. */ public void setMacroDesc(String macroDesc) { this.macroDesc = macroDesc; } }
23,951
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitiveBezier.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitiveBezier.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.dialogs.DashInfo; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.ShapeInterface; import net.sourceforge.fidocadj.graphic.RectangleG; /** Class to handle the Bézier 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 aa 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 PrimitiveBezier extends GraphicPrimitive { // aa Bézier is defined by four points. static final int N_POINTS=6; private int dashStyle; private final Arrow arrowData; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. private ShapeInterface shape1; private float w; private int xmin; private int ymin; private int width; private int height; /** Gets the number of control points used. @return the number of points used by the primitive */ public int getControlPointNumber() { return N_POINTS; } /** Standard constructor. It creates an empty shape. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveBezier(String f, int size) { super(); arrowData=new Arrow(); initPrimitive(-1, f, size); } /** Create a Bézier curve specified by four control points @param x1 the x coordinate (logical unit) of P1. @param y1 the y coordinate (logical unit) of P1. @param x2 the x coordinate (logical unit) of P2. @param y2 the y coordinate (logical unit) of P2. @param x3 the x coordinate (logical unit) of p3. @param y3 the y coordinate (logical unit) of p3. @param x4 the x coordinate (logical unit) of P4. @param y4 the y coordinate (logical unit) of P4. @param layer the layer to be used. @param arrowS arrow to be drawn at the beginning of the curve. @param arrowE arrow to be drawn at the beginning of the curve. @param arrowSt arrow style. @param arrowLe the arrow length. @param arrowWi the arrow half width. @param dashSt dash style. @param font the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int layer, boolean arrowS, boolean arrowE, int arrowSt, int arrowLe, int arrowWi, int dashSt, String font, int size) { super(); arrowData=new Arrow(); arrowData.setArrowStart(arrowS); arrowData.setArrowEnd(arrowE); arrowData.setArrowHalfWidth(arrowWi); arrowData.setArrowLength(arrowLe); arrowData.setArrowStyle(arrowSt); dashStyle=dashSt; initPrimitive(-1, font, size); // Store the coordinates of the points virtualPoint[0].x=x1; virtualPoint[0].y=y1; virtualPoint[1].x=x2; virtualPoint[1].y=y2; virtualPoint[2].x=x3; virtualPoint[2].y=y3; virtualPoint[3].x=x4; virtualPoint[3].y=y4; virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; setLayer(layer); } /** Get the control parameters of the given primitive. @return a vector of ParameterDescription containing each control parameter. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v=super.getControls(); arrowData.getControlsForArrow(v); ParameterDescription pd = new ParameterDescription(); pd.parameter=new DashInfo(dashStyle); pd.description=Globals.messages.getString("ctrl_dash_style"); pd.isExtension = true; v.add(pd); return v; } /** Set the control parameters of the given primitive. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. @return the next index in v to be scanned (if needed) after the execution of this function. */ public int setControls(List<ParameterDescription> v) { int i=super.setControls(v); i=arrowData.setParametersForArrow(v, i); ParameterDescription pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof DashInfo) { dashStyle=((DashInfo)pd.parameter).style; } else { System.out.println("Warning: 6-unexpected parameter!"+pd); } // Parameters validation and correction if(dashStyle>=Globals.dashNumber) { dashStyle=Globals.dashNumber-1; } if(dashStyle<0) { dashStyle=0; } return i; } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { if(!selectLayer(g,layerV)) { return; } int h=0; PointG p0=new PointG(coordSys.mapX(virtualPoint[0].x,virtualPoint[0].y), coordSys.mapY(virtualPoint[0].x,virtualPoint[0].y)); PointG p3=new PointG(coordSys.mapX(virtualPoint[3].x,virtualPoint[3].y), coordSys.mapY(virtualPoint[3].x,virtualPoint[3].y)); drawText(g, coordSys, layerV, -1); if(changed) { // Calculating stroke width w = (float)(Globals.lineWidth*coordSys.getXMagnitude()); if (w<D_MIN) { w=D_MIN; } } // Apply the stroke style g.applyStroke(w, dashStyle); // Check if there are arrows to be drawn and, if needed, draw them. if (arrowData.atLeastOneArrow()) { h=arrowData.prepareCoordinateMapping(coordSys); // If the arrow length is negative, the arrow extends // outside the line, so the limits must not be changed. if (arrowData.isArrowStart()) { if(arrowData.getArrowLength()>0) { p0=drawArrow(g, coordSys, 0,1,2,3); } else { drawArrow(g, coordSys, 0,1,2,3); } } if (arrowData.isArrowEnd()) { if(arrowData.getArrowLength()>0) { p3=drawArrow(g, coordSys, 3,2,1,0); } else { drawArrow(g, coordSys, 3,2,1,0); } } } // in the Bézier primitive, the four virtual points represent // the control points of the shape. if (changed) { changed=false; shape1=g.createShape(); // Create the Bézier curve shape1.createCubicCurve( p0.x, p0.y, coordSys.mapX(virtualPoint[1].x,virtualPoint[1].y), coordSys.mapY(virtualPoint[1].x,virtualPoint[1].y), coordSys.mapX(virtualPoint[2].x,virtualPoint[2].y), coordSys.mapY(virtualPoint[2].x,virtualPoint[2].y), p3.x, p3.y); // Calculating the bounds of this curve is useful since we can // check if it is visible and thus choose wether draw it or not. RectangleG r = shape1.getBounds(); xmin = r.x-h; ymin = r.y-h; width = r.width+2*h; height = r.height+2*h; } // If the curve is not visible, exit immediately if(!g.hitClip(xmin,ymin, width+1, height+1)) { return; } if(width==0 ||height==0) { // Degenerate case: horizontal or vertical segment. g.drawLine(coordSys.mapX(virtualPoint[0].x,virtualPoint[0].y), coordSys.mapY(virtualPoint[0].x,virtualPoint[0].y), coordSys.mapX(virtualPoint[3].x,virtualPoint[3].y), coordSys.mapY(virtualPoint[3].x,virtualPoint[3].y)); } else { // Draw the curve. g.draw(shape1); } } /** Draw an arrow checking that the coordinates given are not degenerate. @param g the graphical context on which to write. @param coordSyst the coordinate system. @param aa the index of the first point (the head of the arrow) @param bb the index of the second arrow (indicates the direction, if the coordinates are diffrent from point aa. If it is not true, the coordinates of point cc are used. @param cc if the test of point bb fails, employs this point to indicate the direction, unless equal to point aa. @param dd employs this point as a last resort! */ private PointG drawArrow(GraphicsInterface g, MapCoordinates coordSys, int aa, int bb, int cc, int dd) { int psx; int psy; // starting coordinates. int pex; int pey; // ending coordinates. // We must check if the cubic curve is degenerate. In this case, // the correct arrow orientation will be determined by successive // points in the curve. psx = virtualPoint[aa].x; psy = virtualPoint[aa].y; if(virtualPoint[aa].x!=virtualPoint[bb].x || virtualPoint[aa].y!=virtualPoint[bb].y) { pex = virtualPoint[bb].x; pey = virtualPoint[bb].y; } else if(virtualPoint[aa].x!=virtualPoint[cc].x || virtualPoint[aa].y!=virtualPoint[cc].y) { pex = virtualPoint[cc].x; pey = virtualPoint[cc].y; } else { pex = virtualPoint[dd].x; pey = virtualPoint[dd].y; } return arrowData.drawArrow(g, coordSys.mapX(psx,psy), coordSys.mapY(psx,psy), coordSys.mapX(pex,pey), coordSys.mapY(pex,pey)); } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array. @throws IOException if the arguments are incorrect or the primitive is invalid. */ public void parseTokens(String[] tokens, int nn) throws IOException { changed=true; // assert it is the correct primitive if ("BE".equals(tokens[0])) { // Bézier if (nn<9) { throw new IOException("Bad arguments on BE"); } // Parse the coordinates of all points of the Bézier curve int x1 = virtualPoint[0].x=Integer.parseInt(tokens[1]); int y1 = virtualPoint[0].y=Integer.parseInt(tokens[2]); virtualPoint[1].x=Integer.parseInt(tokens[3]); virtualPoint[1].y=Integer.parseInt(tokens[4]); virtualPoint[2].x=Integer.parseInt(tokens[5]); virtualPoint[2].y=Integer.parseInt(tokens[6]); virtualPoint[3].x=Integer.parseInt(tokens[7]); virtualPoint[3].y=Integer.parseInt(tokens[8]); virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; if(nn>9) { parseLayer(tokens[9]); } if(nn>10 && "FCJ".equals(tokens[10])) { int i=arrowData.parseTokens(tokens, 11); dashStyle = checkDashStyle(Integer.parseInt(tokens[i])); } } else { throw new IOException("Invalid primitive: "+ " programming error?"); } } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { // We first check if the given point lies inside the text areas. if(checkText(px, py)) { return 0; } PointG p0 = new PointG(virtualPoint[0].x, virtualPoint[0].y); PointG p3 = new PointG(virtualPoint[3].x, virtualPoint[3].y); // Check if the point is in the arrows. Correct the starting and ending // points if needed. if (arrowData.atLeastOneArrow()) { boolean r=false; boolean t=false; // We work with logic coordinates (default for MapCoordinates). MapCoordinates m=new MapCoordinates(); arrowData.prepareCoordinateMapping(m); if (arrowData.isArrowStart()) { if(arrowData.getArrowLength()>0) { t=arrowData.isInArrow(px, py, virtualPoint[0].x, virtualPoint[0].y, virtualPoint[1].x, virtualPoint[1].y, p0); } else { t=arrowData.isInArrow(px, py, virtualPoint[0].x, virtualPoint[0].y, virtualPoint[1].x, virtualPoint[1].y, null); } } if (arrowData.isArrowEnd()) { if(arrowData.getArrowLength()>0) { r=arrowData.isInArrow(px, py, virtualPoint[3].x, virtualPoint[3].y, virtualPoint[2].x, virtualPoint[2].y, p3); } else { r=arrowData.isInArrow(px, py, virtualPoint[3].x, virtualPoint[3].y, virtualPoint[2].x, virtualPoint[2].y, null); } } // Click on one of the arrows? if(r||t) { return 1; } } // If not, we check for the distance to the Bézier curve. return GeometricDistances.pointToBezier( p0.x, p0.y, virtualPoint[1].x, virtualPoint[1].y, virtualPoint[2].x, virtualPoint[2].y, p3.x, p3.y, px, py); } /** Obtain a string command descripion of the primitive. @param extensions true if FidoCadJ extensions to the old FidoCAD format should be active. @return the FIDOCAD command line. */ public String toString(boolean extensions) { String s = "BE "+virtualPoint[0].x+" "+virtualPoint[0].y+" "+ +virtualPoint[1].x+" "+virtualPoint[1].y+" "+ +virtualPoint[2].x+" "+virtualPoint[2].y+" "+ +virtualPoint[3].x+" "+virtualPoint[3].y+" "+ getLayer()+"\n"; if(extensions && (arrowData.atLeastOneArrow()|| dashStyle>0 || hasName() || hasValue())) { String text = "0"; // We take into account that there may be some text associated // to that primitive. if (name.length()!=0 || value.length()!=0) { text = "1"; } s+="FCJ "+arrowData.createArrowTokens()+" "+dashStyle+ " "+text+"\n"; } // The false is needed since saveText should not write the FCJ tag. s+=saveText(false); return s; } /** Export the primitive on a vector graphic format. @param exp the export interface to employ. @param cs the coordinate mapping to employ. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { exportText(exp, cs, -1); exp.exportBezier(cs.mapX(virtualPoint[0].x,virtualPoint[0].y), cs.mapY(virtualPoint[0].x,virtualPoint[0].y), cs.mapX(virtualPoint[1].x,virtualPoint[1].y), cs.mapY(virtualPoint[1].x,virtualPoint[1].y), cs.mapX(virtualPoint[2].x,virtualPoint[2].y), cs.mapY(virtualPoint[2].x,virtualPoint[2].y), cs.mapX(virtualPoint[3].x,virtualPoint[3].y), cs.mapY(virtualPoint[3].x,virtualPoint[3].y), getLayer(), arrowData.isArrowStart(), arrowData.isArrowEnd(), arrowData.getArrowStyle(), (int)(arrowData.getArrowLength()*cs.getXMagnitude()), (int)(arrowData.getArrowHalfWidth()*cs.getXMagnitude()), dashStyle,Globals.lineWidth*cs.getXMagnitude()); } /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public int getNameVirtualPointNumber() { return 4; } /** Get the number of the virtual point associated to the Value property @return the number of the virtual point associated to the Value property */ public int getValueVirtualPointNumber() { return 5; } }
19,297
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitiveRectangle.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitiveRectangle.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.dialogs.DashInfo; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; /** Class to handle the rectangle 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 2007-2023 by Davide Bucci </pre> @author Davide Bucci */ public final class PrimitiveRectangle extends GraphicPrimitive { // A rectangle is defined by two points. static final int N_POINTS=4; // The state: filled or not. private boolean isFilled; // The dashing style. private int dashStyle; // This is the value which is given for the distance calculation when the // user clicks inside the rectangle: static final int DISTANCE_IN = 1; // This is the value given instead when the clicks is done outside: static final int DISTANCE_OUT = 1000; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. // For this reason, they are NOT local variables. private int xa; // NOPMD private int ya; // NOPMD private int xb; // NOPMD private int yb; // NOPMD private int x1; // NOPMD private int y1; // NOPMD private int x2; // NOPMD private int y2; // NOPMD private int width; // NOPMD private int height; // NOPMD private float w; // NOPMD /** Gets the number of control points used. @return the number of points used by the primitive */ public int getControlPointNumber() { return N_POINTS; } /** Standard constructor. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveRectangle(String f, int size) { super(); isFilled=false; initPrimitive(-1, f, size); changed=true; } /** Create a rectangle defined by two points @param x1 the start x coordinate (logical unit). @param y1 the start y coordinate (logical unit). @param x2 the end x coordinate (logical unit). @param y2 the end y coordinate (logical unit). @param f specifies if the rectangle should be filled. @param layer the layer to be used. @param dashSt the dashing style. @param font the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveRectangle(int x1, int y1, int x2, int y2, boolean f, int layer, int dashSt, String font, int size) { super(); initPrimitive(-1, font, size); virtualPoint[0].x=x1; virtualPoint[0].y=y1; virtualPoint[1].x=x2; virtualPoint[1].y=y2; virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; isFilled=f; dashStyle=dashSt; changed = true; setLayer(layer); } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { if(!selectLayer(g,layerV)) { return; } drawText(g, coordSys, layerV, -1); // in the rectangle primitive, the first two virtual points represent // the two corners of the segment if(changed) { changed=false; x1=coordSys.mapX(virtualPoint[0].x,virtualPoint[0].y); y1=coordSys.mapY(virtualPoint[0].x,virtualPoint[0].y); x2=coordSys.mapX(virtualPoint[1].x,virtualPoint[1].y); y2=coordSys.mapY(virtualPoint[1].x,virtualPoint[1].y); // Sort the coordinates. if (x1>x2) { xa=x2; xb=x1; } else { xa=x1; xb=x2; } if (y1>y2) { ya=y2; yb=y1; } else { ya=y1; yb=y2; } // Calculate the stroke width w = (float)(Globals.lineWidth*coordSys.getXMagnitude()); if (w<D_MIN) { w=D_MIN; } width = xb-xa; height = yb-ya; } // If we do not need to perform the drawing, exit immediately if(!g.hitClip(xa,ya, width+1,height+1)) { return; } g.applyStroke(w, dashStyle); if(isFilled){ // We need to add 1 to the rectangle, since the behaviour of // Java api is to skip the rightmost and bottom pixels g.fillRect(xa,ya,width+1,height+1); } else { if(xb!=xa || yb!=ya) { // It seems that under MacOSX, drawing a rectangle by cycling // with the lines is much more efficient than the drawRect // method. Probably, a further investigation is needed to // determine if this situation is the same with more recent // Java runtimes (mine was 1.5.something on an iMac G5 at // 2 GHz when I did the tests). g.drawLine(xa, ya, xb,ya); g.drawLine(xb, ya, xb,yb); g.drawLine(xb, yb, xa,yb); g.drawLine(xa, yb, xa,ya); } } } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array @throws IOException if the arguments are incorrect or the primitive is invalid. */ public void parseTokens(String[] tokens, int nn) throws IOException { changed=true; // assert it is the correct primitive if ("RV".equals(tokens[0])||"RP".equals(tokens[0])) { // Oval if (nn<5) { throw new IOException("Bad arguments on RV/RP"); } int x1 = virtualPoint[0].x=Integer.parseInt(tokens[1]); int y1 = virtualPoint[0].y=Integer.parseInt(tokens[2]); virtualPoint[1].x=Integer.parseInt(tokens[3]); virtualPoint[1].y=Integer.parseInt(tokens[4]); virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; if(nn>5) { parseLayer(tokens[5]); } if("RP".equals(tokens[0])) { isFilled=true; } else { isFilled=false; } if(nn>6 && "FCJ".equals(tokens[6])) { dashStyle = checkDashStyle(Integer.parseInt(tokens[7])); } } else { throw new IOException("RV/RP: Invalid primitive: " +tokens[0]+" programming error?"); } } /** Get the control parameters of the given primitive. @return a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v=super.getControls(); ParameterDescription pd = new ParameterDescription(); pd.parameter=Boolean.valueOf(isFilled); pd.description=Globals.messages.getString("ctrl_filled"); v.add(pd); pd = new ParameterDescription(); pd.parameter=new DashInfo(dashStyle); pd.description=Globals.messages.getString("ctrl_dash_style"); pd.isExtension = true; v.add(pd); return v; } /** Set the control parameters of the given primitive. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. @return the next index in v to be scanned (if needed) after the execution of this function. */ public int setControls(List<ParameterDescription> v) { int i=super.setControls(v); ParameterDescription pd; pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof Boolean) { isFilled=((Boolean)pd.parameter).booleanValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof DashInfo) { dashStyle=((DashInfo)pd.parameter).style; } else { System.out.println("Warning: unexpected parameter!"+pd); } // Parameters validation and correction if(dashStyle>=Globals.dashNumber) { dashStyle=Globals.dashNumber-1; } if(dashStyle<0) { dashStyle=0; } return i; } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (polygons, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { // Here we check if the given point lies inside the text areas if(checkText(px, py)) { return 0; } int xa=Math.min(virtualPoint[0].x,virtualPoint[1].x); int ya=Math.min(virtualPoint[0].y,virtualPoint[1].y); int xb=Math.max(virtualPoint[0].x,virtualPoint[1].x); int yb=Math.max(virtualPoint[0].y,virtualPoint[1].y); if(isFilled) { if(GeometricDistances.pointInRectangle(xa,ya, xb-xa, yb-ya,px,py)) { return DISTANCE_IN; } else { return DISTANCE_OUT; } } return GeometricDistances.pointToRectangle(xa,ya, xb-xa, yb-ya,px,py); } /** Obtain a string command descripion of the primitive. @param extensions true if FidoCadJ extensions to the old FidoCAD format should be active. @return the FIDOCAD command line. */ public String toString(boolean extensions) { String cmd; if (isFilled) { cmd="RP "; } else { cmd="RV "; } cmd+=virtualPoint[0].x+" "+virtualPoint[0].y+" "+ +virtualPoint[1].x+" "+virtualPoint[1].y+" "+ getLayer()+"\n"; if(extensions && (dashStyle>0 || hasName() || hasValue())) { String text = "0"; if (name.length()!=0 || value.length()!=0) { text = "1"; } cmd+="FCJ "+dashStyle+" "+text+"\n"; } // The false is needed since saveText should not write the FCJ tag. cmd+=saveText(false); return cmd; } /** Export the primitive on a vector graphic format. @param exp the export interface to employ. @param cs the coordinate mapping to employ. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { exportText(exp, cs, -1); exp.exportRectangle(cs.mapX(virtualPoint[0].x,virtualPoint[0].y), cs.mapY(virtualPoint[0].x,virtualPoint[0].y), cs.mapX(virtualPoint[1].x,virtualPoint[1].y), cs.mapY(virtualPoint[1].x,virtualPoint[1].y), isFilled, getLayer(), dashStyle, Globals.lineWidth*cs.getXMagnitude()); } /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public int getNameVirtualPointNumber() { return 2; } /** Get the number of the virtual point associated to the Value property @return the number of the virtual point associated to the Value property */ public int getValueVirtualPointNumber() { return 3; } }
14,205
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
Arrow.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/Arrow.java
package net.sourceforge.fidocadj.primitives; import java.util.*; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.graphic.PolygonInterface; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.dialogs.ArrowInfo; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.export.PointPr; /** Arrow class: draws an arrow of the given size, style and direction. @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 final class Arrow { /** A few constants in order to define the arrow style. */ public static final int flagLimiter = 0x01; public static final int flagEmpty = 0x02; // From version 0.24.8, those become floating point values. private float arrowLength; private float arrowHalfWidth; // If the length and the width differ from an integer less than the given // tolerance, the result will be rounded private static final float roundTolerance=1e-5f; // The coordinate mapping must be kept so that the drawn points can be // tracked for the calculation of the size of the drawing. MapCoordinates m; // Style of the arrow. private int arrowStyle; private boolean arrowStart; // Draw arrow at the start point. private boolean arrowEnd; // Draw arrow at the end point. // Arrow sizes in pixels. private int h; private int l; /** Constructor is private since this is an utility class. */ public Arrow() { arrowLength = 3; arrowHalfWidth = 1; } /** Determine if at least one arrow has to be drawn. @return true if at least one arrow has to be drawn. */ public boolean atLeastOneArrow() { return arrowStart || arrowEnd; } /** Create the string describing the arrow. If the arrowLength and arrowHalfWidth differs from an integer less than a given tolerance (constant roundTolerance in the class definition), the sizes are rounded and issued as integer values. This allows to have a better compatibility with former versions of FidoCadJ (<0.24.7) that can not parse a non-integer value in those places. The code issued is a little bit more compact, too. @return a string containing the codes */ public String createArrowTokens() { int arrows = (arrowStart?0x01:0x00)|(arrowEnd?0x02:0x00); String result=""; result+=arrows+" "; result+=arrowStyle+" "; if (Math.abs(arrowLength-Math.round(arrowLength))<roundTolerance) { result+= (int)Math.round(arrowLength); } else { result+=arrowLength; } result+=" "; if (Math.abs(arrowHalfWidth-Math.round(arrowHalfWidth))<roundTolerance){ result+= (int)Math.round(arrowHalfWidth); } else { result+=arrowHalfWidth; } return result; } /** Determine if the arrow on the start point should be drawn. @return true if the arrow on the start point should be drawn. */ public boolean isArrowStart() { return arrowStart; } /** Set if an arrow has to be drawn at the start (beginning) of the element. @param as true if it is the case. */ public void setArrowStart(boolean as) { arrowStart=as; } /** Determine if the arrow on the start point should be drawn. @return true if the arrow on the start point should be drawn. */ public boolean isArrowEnd() { return arrowEnd; } /** Set if an arrow has to be drawn at the end of the element. @param ae true if it is the case. */ public void setArrowEnd(boolean ae) { arrowEnd=ae; } /** Get the code of the current arrow style @return the code. */ public int getArrowStyle() { return arrowStyle; } /** Set the current style. @param as the code style. */ public void setArrowStyle(int as) { arrowStyle=as; } /** Get the current arrow length. @return the arrow length. */ public float getArrowLength() { return arrowLength; } /** Set the current arrow length. @param al the arrow length. */ public void setArrowLength(float al) { arrowLength=al; } /** Get the current arrow half width. @return the arrow half width. */ public float getArrowHalfWidth() { return arrowHalfWidth; } /** Set the current arrow half width. @param ahw the arrow half width */ public void setArrowHalfWidth(float ahw) { arrowHalfWidth=ahw; } /** Parse the tokens for the description of an arrow. They always come (in a FCJ line) in the same order, but the starting index may differ. The order is as follows: 1. the presence of which arrow (start/end points), 2. the style code, 3. the length, 4. the half width, 5. the style. @param tokens the tokens to be interpreted. @param startIndex the index where to start having a look around. @return the index of the token following the one which has been just read. */ public int parseTokens(String[] tokens, int startIndex) { int i=startIndex; int arrows = Integer.parseInt(tokens[i++]); arrowStart = (arrows & 0x01) !=0; arrowEnd = (arrows & 0x02) !=0; arrowStyle = Integer.parseInt(tokens[i++]); // These rounding operations should be removed in version // 0.24.8 (see Issue #111). arrowLength = Float.parseFloat(tokens[i++]); arrowHalfWidth= Float.parseFloat(tokens[i++]); return i; } /** The drawing operation is done in two step. The first one is performed here and consists in calculating all the relevant size parameters in pixels, given the current coordinate mapping. The results are stored and used during the drawing operations. This function does not need to be employed each time a drawing operation is needed, but only when something changes, such as the coordinate mapping or the sizes of the arrows. @param coordSys the current coordinate mapping system. @return the half width in pixels. */ public int prepareCoordinateMapping(MapCoordinates coordSys) { m=coordSys; // Heigth and width of the arrows in pixels h=Math.abs(coordSys.mapXi(arrowHalfWidth,arrowHalfWidth,false)- coordSys.mapXi(0,0, false)); l=Math.abs(coordSys.mapXi(arrowLength,arrowLength, false)- coordSys.mapXi(0,0,false)); // h and l must conserve the sign of arrowHalfWidth and // arrowLength, regardless of the coordinate system // orientation. if(arrowHalfWidth<0) { h=-h; } if(arrowLength<0) { l=-l; } return h; } /** Add elements for the Arrow description inside a parameter description array used to create a parameters dialog. @param v the List to which the elements have to be added (of course, this means that that List will be modified! @return the vector itself. */ public List<ParameterDescription> getControlsForArrow( List<ParameterDescription> v) { ParameterDescription pd = new ParameterDescription(); pd.parameter=Boolean.valueOf(isArrowStart()); pd.description=Globals.messages.getString("ctrl_arrow_start"); pd.isExtension = true; v.add(pd); pd = new ParameterDescription(); pd.parameter=Boolean.valueOf(isArrowEnd()); pd.description=Globals.messages.getString("ctrl_arrow_end"); pd.isExtension = true; v.add(pd); pd = new ParameterDescription(); pd.parameter=Float.valueOf(getArrowLength()); pd.description=Globals.messages.getString("ctrl_arrow_length"); pd.isExtension = true; v.add(pd); pd = new ParameterDescription(); pd.parameter=Float.valueOf(getArrowHalfWidth()); pd.description=Globals.messages.getString("ctrl_arrow_half_width"); pd.isExtension = true; v.add(pd); pd = new ParameterDescription(); pd.parameter=new ArrowInfo(getArrowStyle()); pd.description=Globals.messages.getString("ctrl_arrow_style"); pd.isExtension = true; v.add(pd); return v; } /** Read the elements for the Arrow description inside a parameter description List, coming from a parameters dialog. @param v the List to which the elements have been added @param start the starting index to which the parameters should be interpreted as describing an Arrow. @return the index+1 of the last element employed for the Arrow. */ public int setParametersForArrow(List<ParameterDescription> v, int start) { int i=start; ParameterDescription pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof Boolean) { setArrowStart(((Boolean)pd.parameter).booleanValue()); } else { System.out.println("Warning: 1-unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof Boolean) { setArrowEnd(((Boolean)pd.parameter).booleanValue()); } else { System.out.println("Warning: 2-unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof Float) { setArrowLength(((Float)pd.parameter).floatValue()); } else { System.out.println("Warning: 3-unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof Float) { setArrowHalfWidth(((Float)pd.parameter).floatValue()); } else { System.out.println("Warning: 4-unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof ArrowInfo) { setArrowStyle(((ArrowInfo)pd.parameter).style); } else { System.out.println("Warning: 5-unexpected parameter!"+pd); } return i; } /** Draw an arrow at the given position. Version useful in those cases where the sizes have to be set directly in pixels and no data deserve to be stored for very long. @param g the graphic context to be used. @param x the x coordinate of the arrow point. @param y the y coordinate of the arrow point. @param xc the x coordinate of the direction point. @param yc the y coordinate of the direction point. @return the coordinate of the base point of the arrow head. @param tl the length of the arrow in pixels. @param th the half width of the arrow in pixels. @param as the style of the arrow. */ public PointG drawArrowPixels(GraphicsInterface g, int x, int y, int xc, int yc, int tl, int th, int as) { h=th; l=tl; arrowStyle=as; return drawArrow(g, x,y, xc,yc); } /** Check if the logic coordinates (xs,ys) are inside an arrow. @param xs the x coordinate of the point to check. @param ys the y coordinate of the point to check. @param x the x coordinate of the arrow tip. @param y the y coordinate of the arrow tip. @param xc the x coordinate of the direction point. @param yc the y coordinate of the direction point. @param pBase return the coordinate of the base point of the arrow head. If pBase is specified, it modifies its values. If it is null, nothing will be stored. @return true if the coordinates are inside the arrow. */ public boolean isInArrow(int xs, int ys, int x, int y, int xc, int yc, PointG pBase) { // Consider the arrow as a polygon. int[] xp=new int[3]; int[] yp=new int[3]; PointPr[] p=calculateArrowPoints(x,y,xc,yc); xp[0]=x; xp[1]=(int)Math.round(p[1].x); xp[2]=(int)Math.round(p[2].x); yp[0]=y; yp[1]=(int)Math.round(p[1].y); yp[2]=(int)Math.round(p[2].y); if(pBase!=null) { pBase.x=(int)Math.round(p[0].x); pBase.y=(int)Math.round(p[0].y); } return GeometricDistances.pointInPolygon(xp,yp,3,xs,ys); } private PointPr[] calculateArrowPoints(int x, int y, int xc, int yc) { PointPr[] p; // At first we need the angle giving the direction of the arrow double alpha=getArrowAngle(x,y,xc,yc); // Then, we calculate the points for the polygon double cosalpha=Math.cos(alpha); double sinalpha=Math.sin(alpha); p = new PointPr[5]; p[0] = new PointPr(x - l*cosalpha, y - l*sinalpha); p[1] = new PointPr(p[0].x - h*sinalpha, p[0].y + h*cosalpha); p[2] = new PointPr(p[0].x + h*sinalpha, p[0].y - h*cosalpha); if ((arrowStyle & flagLimiter) != 0) { p[3] = new PointPr(x - h*sinalpha, y + h*cosalpha); p[4] = new PointPr(x + h*sinalpha, y - h*cosalpha); } return p; } private double getArrowAngle(int x, int y, int xc, int yc) { double alpha; // a little bit of trigonometry :-) // The idea is that the arrow head should be oriented in the direction // specified by the second point. 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 is the angle of the arrow, against an horizontal line with // the trigonometric convention (anti clockwise is positive). alpha += x-xc>0.0?0.0:Math.PI; return alpha; } /** Draw an arrow at the given position. @param g the graphic context to be used. @param x the x coordinate of the arrow point. @param y the y coordinate of the arrow point. @param xc the x coordinate of the direction point. @param yc the y coordinate of the direction point. @return the coordinate of the base point of the arrow head. */ public PointG drawArrow(GraphicsInterface g, int x, int y, int xc, int yc) { PointPr[] p = calculateArrowPoints(x,y,xc,yc); // The arrow head is traced using a polygon. Here we create the // object and populate it with the calculated coordinates. PolygonInterface pp = g.createPolygon(); pp.addPoint(x,y); pp.addPoint((int)Math.round(p[1].x),(int)Math.round(p[1].y)); pp.addPoint((int)Math.round(p[2].x),(int)Math.round(p[2].y)); if(m!=null) { m.trackPoint(x,y); m.trackPoint(p[1].x,p[1].y); m.trackPoint(p[2].x,p[2].y); } if ((arrowStyle & flagEmpty) == 0) { g.fillPolygon(pp); } else { g.drawPolygon(pp); } // Check if we need to draw the limiter or not // This is a small line useful for quotes. if ((arrowStyle & flagLimiter) != 0) { g.drawLine((int)Math.round(p[3].x),(int)Math.round(p[3].y), (int)Math.round(p[4].x),(int)Math.round(p[4].y)); if(m!=null) { m.trackPoint(p[3].x,p[3].y); m.trackPoint(p[4].x,p[4].y); } } return new PointG((int)p[0].x,(int)p[0].y); } }
16,678
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PrimitiveComplexCurve.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/primitives/PrimitiveComplexCurve.java
package net.sourceforge.fidocadj.primitives; import java.io.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.dialogs.DashInfo; import net.sourceforge.fidocadj.export.ExportInterface; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.GeometricDistances; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.graphic.GraphicsInterface; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.PolygonInterface; import net.sourceforge.fidocadj.graphic.ShapeInterface; import net.sourceforge.fidocadj.graphic.PointDouble; /** Class to handle the ComplexCurve 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 2011-2023 by Davide Bucci Spline calculations by Tim Lambert http://www.cse.unsw.edu.au/~lambert/splines/ </pre> @author Davide Bucci */ public final class PrimitiveComplexCurve extends GraphicPrimitive { private int nPoints; private boolean isFilled; private boolean isClosed; private final Arrow arrowData; private int dashStyle; // The natural spline is drawn as a polygon. Even if this is a rather // crude technique, it fits well with the existing architecture (in // particular for the export facilities), since everything that it is // needed for a polygon is available and can be reused here. // In some cases (for example for drawing), a ShapeInterface is created, // since it gives better results than a polygon. // A first polygon stored in screen coordinates. private PolygonInterface p; // A second polygon stored in logical coordinates. private PolygonInterface q; // 5 points is the initial storage size, which is increased if needed. // In other words, we initially create space for storing 5 points and // we increase that if needed. int storageSize=5; static final int STEPS=24; // Some stored data private int xmin; private int ymin; private int width; private int height; // Those are data which are kept for the fast redraw of this primitive. // Basically, they are calculated once and then used as much as possible // without having to calculate everything from scratch. private float w; private ShapeInterface gp; /** Gets the number of control points used. @return the number of points used by the primitive. */ public int getControlPointNumber() { return nPoints+2; } /** Constructor. Create a ComplexCurve. Add points with the addPoint method. @param f the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveComplexCurve(String f, int size) { super(); arrowData=new Arrow(); isFilled=false; nPoints=0; p = null; initPrimitive(storageSize, f, size); } /** Create a ComplexCurve. Add points with the addPoint method. @param f specifies if the ComplexCurve should be filled. @param c specifies if the ComplexCurve should be closed. @param layer the layer to be used. @param arrowS arrow to be drawn at the beginning of the curve. @param arrowE arrow to be drawn at the beginning of the curve. @param arrowSt arrow style. @param arrowLe the arrow length. @param arrowWi the arrow half width. @param dashSt dash style. @param font the name of the font for attached text. @param size the size of the font for attached text. */ public PrimitiveComplexCurve(boolean f, boolean c, int layer, boolean arrowS, boolean arrowE, int arrowSt, int arrowLe, int arrowWi, int dashSt, String font, int size) { super(); arrowData=new Arrow(); arrowData.setArrowStart(arrowS); arrowData.setArrowEnd(arrowE); arrowData.setArrowHalfWidth(arrowWi); arrowData.setArrowLength(arrowLe); arrowData.setArrowStyle(arrowSt); dashStyle=dashSt; p = null; initPrimitive(storageSize, font, size); nPoints=0; isFilled=f; isClosed=c; dashStyle=dashSt; setLayer(layer); } /** Add the given point to the closest part of the curve. @param px the x coordinate of the point to add @param py the y coordinate of the point to add */ public void addPointClosest(int px, int py) { int[] xp=new int[storageSize]; int[] yp=new int[storageSize]; int k; for(k=0;k<nPoints;++k){ xp[k]=virtualPoint[k].x; yp[k]=virtualPoint[k].y; } // Calculate the distance between the // given point and all the segments composing the polygon and we // take the smallest one. int distance=(int)Math.sqrt((px-xp[0])*(px-xp[0])+ (py-yp[0])*(py-yp[0])); int d; int minv=0; for(int i=0; i<q.getNpoints()-1; ++i) { d=GeometricDistances.pointToSegment(q.getXpoints()[i], q.getYpoints()[i], q.getXpoints()[i+1], q.getYpoints()[i+1], px,py); if(d<distance) { distance = d; minv=i-1; } } minv /= STEPS; ++minv; if(minv<0) { minv=nPoints-1; } // Now minv contains the index of the vertex before the one which // should be entered. We begin to enter the new vertex at the end... addPoint(px, py); // ...then we do the swap for(int i=nPoints-1; i>minv; --i) { virtualPoint[i].x=virtualPoint[i-1].x; virtualPoint[i].y=virtualPoint[i-1].y; } virtualPoint[minv].x=px; virtualPoint[minv].y=py; changed = true; } /** Add a point at the current ComplexCurve. The point is always added at the end of the already existing path. @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+2>=storageSize) { int oN=storageSize; int i; storageSize += 10; PointG[] nv = new PointG[storageSize]; for(i=0;i<oN;++i) { nv[i]=virtualPoint[i]; } for(;i<storageSize;++i) { nv[i]=new PointG(); } virtualPoint=nv; } // And now we enter the position of the point we are interested with virtualPoint[nPoints].x=x; virtualPoint[nPoints++].y=y; // We do need to shift the two points describing the position // of the text lines virtualPoint[getNameVirtualPointNumber()].x=x+5; virtualPoint[getNameVirtualPointNumber()].y=y+5; virtualPoint[getValueVirtualPointNumber()].x=x+5; virtualPoint[getValueVirtualPointNumber()].y=y+10; changed = true; } /** Create the CurveStorage associated to the complex curve. This is a crude technique, but it is very easy to implement. @param coordSys the coordinate mapping to be employed. @return the CurveStorage approximating the complex curve. */ public CurveStorage createComplexCurve(MapCoordinates coordSys) { double [] xPoints = new double[nPoints]; double [] yPoints = new double[nPoints]; // The first and the last points may be the base of the arrows, if // the latter are present and the points have been updated. for (int i=0; i<nPoints; ++i) { xPoints[i] = coordSys.mapXr(virtualPoint[i].x,virtualPoint[i].y); yPoints[i] = coordSys.mapYr(virtualPoint[i].x,virtualPoint[i].y); } Cubic[] xx; Cubic[] yy; if(isClosed) { xx = calcNaturalCubicClosed(nPoints-1, xPoints); yy = calcNaturalCubicClosed(nPoints-1, yPoints); } else { xx = calcNaturalCubic(nPoints-1, xPoints); yy = calcNaturalCubic(nPoints-1, yPoints); // Here we don't check if a point is in the arrow, but we exploit // the code for calculating the base of the head of the arrows. if (arrowData.atLeastOneArrow()) { arrowData.prepareCoordinateMapping(coordSys); if (arrowData.isArrowStart()) { PointG pp = new PointG(); arrowData.isInArrow(0, 0, (int)Math.round(xx[0].eval(0)), (int)Math.round(yy[0].eval(0)), (int)Math.round(xx[0].eval(0.05)), (int)Math.round(yy[0].eval(0.05)), pp); if(arrowData.getArrowLength()>0) { xPoints[0]=pp.x; yPoints[0]=pp.y; } } if (arrowData.isArrowEnd()) { int l=xx.length-1; PointG pp = new PointG(); arrowData.isInArrow(0, 0, (int)Math.round(xx[l].eval(1)), (int)Math.round(yy[l].eval(1)), (int)Math.round(xx[l].eval(0.95)), (int)Math.round(yy[l].eval(0.95)), pp); if(arrowData.getArrowLength()>0) { xPoints[nPoints-1]=pp.x; yPoints[nPoints-1]=pp.y; } } // Since the arrow will occupy a certain size, the curve has // to be recalculated. This means that the previous evaluation // are just approximations, but the practice shows that they // are enough for all purposes that can be foreseen. // This is not needed if the length is negative, as in this // case the arrow extends outside the curve. if(arrowData.getArrowLength()>0) { xx = calcNaturalCubic(nPoints-1, xPoints); yy = calcNaturalCubic(nPoints-1, yPoints); } } } if(xx==null || yy==null) { return null; } // very crude technique: just break each segment up into steps lines CurveStorage c = new CurveStorage(); c.pp.add(new PointDouble(xx[0].eval(0), yy[0].eval(0))); for (int i = 0; i < xx.length; ++i) { c.dd.add(new PointDouble(xx[i].d1, yy[i].d1)); for (int j = 1; j <= STEPS; ++j) { double u = j / (double) STEPS; c.pp.add(new PointDouble(xx[i].eval(u), yy[i].eval(u))); } } c.dd.add(new PointDouble(xx[xx.length-1].d2, yy[xx.length-1].d2)); return c; } /** Create the polygon associated to the complex curve. This is a crude technique, but it is very easy to implement. @param coordSys the coordinate mapping to be employed. @param poly the polygon to which the points will be added. @return the polygon approximating the complex curve. */ public PolygonInterface createComplexCurvePoly(MapCoordinates coordSys, PolygonInterface poly) { xmin = Integer.MAX_VALUE; ymin = Integer.MAX_VALUE; int xmax = -Integer.MAX_VALUE; int ymax = -Integer.MAX_VALUE; CurveStorage c=createComplexCurve(coordSys); if (c==null) { return null; } List<PointDouble> pp = c.pp; if (pp==null) { return null; } int x; int y; for (PointDouble ppp : pp) { x=(int)Math.round(ppp.x); y=(int)Math.round(ppp.y); poly.addPoint(x, y); coordSys.trackPoint(x,y); if (x<xmin) { xmin=x; } if (x>xmax) { xmax=x; } if(y<ymin) { ymin=y; } if(y>ymax) { ymax=y; } } width = xmax-xmin; height = ymax-ymin; return poly; } /** Code adapted from Tim Lambert's snippets: http://www.cse.unsw.edu.au/~lambert/splines/ Used here with permissions (hey, thanks a lot, Tim!). @param n the number of points. @param x the vector containing x coordinates of nodes. @return the cubic curve spline'ing the nodes. */ Cubic[] calcNaturalCubic(int n, double... x) { if(n<1) { return new Cubic[0]; } double[] gamma = new double[n+1]; double[] delta = new double[n+1]; double[] dd = new double[n+1]; int i; /* We solve the equation [2 1 ] [dd[0]] [3(x[1] - x[0]) ] |1 4 1 | |dd[1]| |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | | ..... | | . | | . | | 1 4 1| | . | |3(x[n] - x[n-2])| [ 1 2] [dd[n]] [3(x[n] - x[n-1])] by using row operations to convert the matrix to upper triangular and then back substitution. The dd[i] are the derivatives at the knots. */ gamma[0] = 1.0/2.0; for (i = 1; i<n; ++i) { gamma[i] = 1.0/(4.0-gamma[i-1]); } gamma[n] = 1.0/(2.0-gamma[n-1]); delta[0] = 3*(x[1]-x[0])*gamma[0]; for (i = 1; i < n; ++i) { delta[i] = (3.0*(x[i+1]-x[i-1])-delta[i-1])*gamma[i]; } delta[n] = (3.0*(x[n]-x[n-1])-delta[n-1])*gamma[n]; dd[n] = delta[n]; for (i = n-1; i>=0; --i) { dd[i] = delta[i] - gamma[i]*dd[i+1]; } /* now compute the coefficients of the cubics */ Cubic[] cc = new Cubic[n]; for (i = 0; i<n; ++i) { cc[i] = new Cubic(x[i], dd[i], 3.0*(x[i+1]-x[i])-2.0*dd[i]-dd[i+1], 2.0*(x[i] - x[i+1]) + dd[i] + dd[i+1]); cc[i].d1=dd[i]; cc[i].d2=dd[i+1]; } return cc; } /** Code mainly taken from Tim Lambert's snippets: http://www.cse.unsw.edu.au/~lambert/splines/ Used here with permissions (hey, thanks a lot, Tim!) calculates the closed natural cubic spline that interpolates x[0], x[1], ... x[n] The first segment is returned as cc[0].a + cc[0].b*u + cc[0].c*u^2 + cc[0].d*u^3 0<=u <1 the other segments are in cc[1], cc[2], ... cc[n] */ Cubic[] calcNaturalCubicClosed(int n, double... x) { if(n<1) { return new Cubic[0]; } double[] w = new double[n+1]; double[] v = new double[n+1]; double[] y = new double[n+1]; double[] dd = new double[n+1]; double z; double ff; double gg; double hh; int k; /* We solve the equation [4 1 1] [dd[0]] [3(x[1] - x[n]) ] |1 4 1 | |dd[1]| |3(x[2] - x[0]) | | 1 4 1 | | . | = | . | | ..... | | . | | . | | 1 4 1| | . | |3(x[n] - x[n-2])| [1 1 4] [dd[n]] [3(x[0] - x[n-1])] by decomposing the matrix into upper triangular and lower matrices and then back substitution. See Spath "Spline Algorithms for Curves and Surfaces" pp 19--21. The dd[i] are the derivatives at the knots. */ w[1] = v[1] = z = 1.0f/4.0f; y[0] = z * 3 * (x[1] - x[n]); hh = 4; ff = 3 * (x[0] - x[n-1]); gg = 1; for (k = 1; k < n; ++k) { v[k+1] = z = 1/(4 - v[k]); w[k+1] = -z * w[k]; y[k] = z * (3*(x[k+1]-x[k-1]) - y[k-1]); hh = hh - gg * w[k]; ff = ff - gg * y[k-1]; gg = -v[k] * gg; } hh = hh - (gg+1)*(v[n]+w[n]); y[n] = ff - (gg+1)*y[n-1]; dd[n] = y[n]/hh; dd[n-1] = y[n-1] - (v[n]+w[n])*dd[n]; /* This equation is WRONG! in my copy of Spath */ for (k = n-2; k >= 0; --k) { dd[k] = y[k] - v[k+1]*dd[k+1] - w[k+1]*dd[n]; } /* now compute the coefficients of the cubics */ Cubic[] cc = new Cubic[n+1]; for (k = 0; k < n; ++k) { cc[k] = new Cubic((float)x[k], dd[k], 3*(x[k+1] - x[k]) - 2*dd[k] - dd[k+1], 2*(x[k] - x[k+1]) + dd[k] + dd[k+1]); cc[k].d1=dd[k]; cc[k].d2=dd[k+1]; } cc[n] = new Cubic((float)x[n], dd[n], 3*(x[0] - x[n]) - 2*dd[n] - dd[0], 2*(x[n] - x[0]) + dd[n] + dd[0]); cc[n].d1=dd[n]; cc[n].d2=dd[0]; return cc; } /** Remove the control point of the spline closest to the given coordinates, if the distance is less than a certain tolerance @param x the x coordinate of the target @param y the y coordinate of the target @param tolerance the tolerance */ public void removePoint(int x, int y, double tolerance) { // We can not have a spline with less than three vertices if (nPoints<=3) { return; } int i; double distance; double minDistance= GeometricDistances.pointToPoint(virtualPoint[0].x, virtualPoint[0].y,x,y); int selI=-1; for(i=1;i<nPoints;++i) { distance = GeometricDistances.pointToPoint(virtualPoint[i].x, virtualPoint[i].y,x,y); if (distance<minDistance) { minDistance=distance; selI=i; } } // Check if the control node losest to the given coordinates // is closer than the given tolerance if(minDistance<=tolerance){ --nPoints; for(i=0;i<nPoints;++i) { // Shift all the points subsequent to the one which needs // to be erased. if(i>=selI) { virtualPoint[i].x=virtualPoint[i+1].x; virtualPoint[i].y=virtualPoint[i+1].y; } changed=true; } } } /** Draw the graphic primitive on the given graphic context. @param g the graphic context in which the primitive should be drawn. @param coordSys the graphic coordinates system to be applied. @param layerV the layer description. */ public void draw(GraphicsInterface g, MapCoordinates coordSys, List layerV) { if(!selectLayer(g,layerV)) { return; } drawText(g, coordSys, layerV, -1); if(changed) { changed=false; // Important: notice that createComplexCurve has some important // side effects as the update of the xmin, ymin, width and height // variables. This means that the order of the two following // commands is important! q=createComplexCurvePoly(new MapCoordinates(), g.createPolygon()); p=createComplexCurvePoly(coordSys, g.createPolygon()); CurveStorage c = createComplexCurve(coordSys); // Prevent a null pointer exception when the user does three clicks // on the same point. TODO: an incomplete toString output is // created. if (c==null) { return; } List<PointDouble> dd = c.dd; List<PointDouble> pp = c.pp; if(q==null) { return; } gp = g.createShape(); gp.createGeneralPath(q.getNpoints()); gp.moveTo((float)pp.get(0).x, (float)pp.get(0).y); int increment=STEPS; double derX1=0.0; double derX2=0.0; double derY1=0.0; double derY2=0.0; double w1=0.666667; double w2=0.666667; int j=0; // TODO: check if using i instead of j is sufficient. for(int i=0; i<pp.size()-increment; i+=increment) { derX1=dd.get(j).x/2.0*w1; derY1=dd.get(j).y/2.0*w1; derX2=dd.get(j+1).x/2.0*w2; derY2=dd.get(j+1).y/2.0*w2; ++j; gp.curveTo((float)(pp.get(i).x+derX1), (float)(pp.get(i).y+derY1), (float)(pp.get(i+increment).x-derX2), (float)(pp.get(i+increment).y-derY2), (float)pp.get(i+increment).x, (float)pp.get(i+increment).y); } if (isClosed) { gp.closePath(); } w = (float)(Globals.lineWidth*coordSys.getXMagnitude()); if (w<D_MIN) { w=D_MIN; } } if (p==null || gp==null) { return; } g.applyStroke(w, dashStyle); // Draw the arrows if they are needed // Ensure that there are enough points to calculate a derivative. if (arrowData.atLeastOneArrow() && p.getNpoints()>2) { arrowData.prepareCoordinateMapping(coordSys); if (arrowData.isArrowStart()&&!isClosed) { arrowData.drawArrow(g, coordSys.mapX(virtualPoint[0].x,virtualPoint[0].y), coordSys.mapY(virtualPoint[0].x,virtualPoint[0].y), p.getXpoints()[1], p.getYpoints()[1]); } if (arrowData.isArrowEnd()&&!isClosed) { int l=nPoints-1; arrowData.drawArrow(g, coordSys.mapX(virtualPoint[l].x,virtualPoint[l].y), coordSys.mapY(virtualPoint[l].x,virtualPoint[l].y), p.getXpoints()[p.getNpoints()-2], p.getYpoints()[p.getNpoints()-2]); } } // If the curve is outside of the shown portion of the drawing, // exit immediately. if(!g.hitClip(xmin,ymin, width+1, height+1)) { return; } // If needed, fill the interior of the shape if (isFilled) { g.fill(gp); } if(width==0 || height==0) { // Degenerate case: draw a segment. int d=nPoints-1; g.drawLine(coordSys.mapX(virtualPoint[0].x,virtualPoint[0].y), coordSys.mapY(virtualPoint[0].x,virtualPoint[0].y), coordSys.mapX(virtualPoint[d].x,virtualPoint[d].y), coordSys.mapY(virtualPoint[d].x,virtualPoint[d].y)); } else { // Draw the curve. g.draw(gp); } } /** Parse a token array and store the graphic data for a given primitive Obviously, that routine should be called *after* having recognized that the called primitive is correct. That routine also sets the current layer. @param tokens the tokens to be processed. tokens[0] should be the command of the actual primitive. @param nn the number of tokens present in the array. @throws IOException it parsing goes wrong, parameters can not be read or primitive is incorrect. */ public void parseTokens(String[] tokens, int nn) throws IOException { changed=true; // assert it is the correct primitive if ("CP".equals(tokens[0])||"CV".equals(tokens[0])) { if (nn<6) { throw new IOException("Bad arguments on CP/CV"); } // Load the points in the virtual points associated to the // current primitive. int j=1; int i=0; int x1 = 0; int y1 = 0; // The first token says if the spline is opened or closed if("1".equals(tokens[j])) { isClosed = true; } else { isClosed = false; } ++j; // Then we have the points defining the curve while(j<nn-1) { if (j+1<nn-1 && "FCJ".equals(tokens[j+1])) { break; } x1 =Integer.parseInt(tokens[j++]); // Check if the following point is available if(j>=nn-1) { throw new IOException("bad arguments on CP/CV"); } y1 =Integer.parseInt(tokens[j++]); ++i; addPoint(x1,y1); } nPoints=i; // We specify now the standard position of the name and value virtualPoint[getNameVirtualPointNumber()].x=x1+5; virtualPoint[getNameVirtualPointNumber()].y=y1+5; virtualPoint[getValueVirtualPointNumber()].x=x1+5; virtualPoint[getValueVirtualPointNumber()].y=y1+10; // And we check finally for extensions (FCJ) if(nn>j) { parseLayer(tokens[j++]); if(nn>j) { if ("FCJ".equals(tokens[j])) { ++j; j=arrowData.parseTokens(tokens, j); dashStyle = checkDashStyle(Integer.parseInt(tokens[j++])); } else { ++j; } } } // See if the curve should be filled (command CP) or empty (CV) if ("CP".equals(tokens[0])) { isFilled=true; } else { isFilled=false; } } else { throw new IOException("CP/CV: Invalid primitive:"+tokens[0]+ " programming error?"); } } /** Get the control parameters of the given primitive. @return a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. */ public List<ParameterDescription> getControls() { List<ParameterDescription> v=super.getControls(); ParameterDescription pd = new ParameterDescription(); pd.parameter=Boolean.valueOf(isFilled); pd.description=Globals.messages.getString("ctrl_filled"); v.add(pd); pd = new ParameterDescription(); pd.parameter=Boolean.valueOf(isClosed); pd.description=Globals.messages.getString("ctrl_closed_curve"); pd.isExtension = true; v.add(pd); arrowData.getControlsForArrow(v); pd = new ParameterDescription(); pd.parameter=new DashInfo(dashStyle); pd.description=Globals.messages.getString("ctrl_dash_style"); pd.isExtension = true; v.add(pd); return v; } /** Set the control parameters of the given primitive. This method is specular to getControls(). @param v a vector of ParameterDescription containing each control parameter. The first parameters should always be the virtual points. @return the next index in v to be scanned (if needed) after the execution of this function. */ public int setControls(List<ParameterDescription> v) { int i=super.setControls(v); ParameterDescription pd; pd=(ParameterDescription)v.get(i); ++i; // Check, just for sure... if (pd.parameter instanceof Boolean) { isFilled=((Boolean)pd.parameter).booleanValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } pd=(ParameterDescription)v.get(i++); // Check, just for sure... if (pd.parameter instanceof Boolean) { isClosed=((Boolean)pd.parameter).booleanValue(); } else { System.out.println("Warning: unexpected parameter!"+pd); } i=arrowData.setParametersForArrow(v, i); pd=(ParameterDescription)v.get(i++); if (pd.parameter instanceof DashInfo) { dashStyle=((DashInfo)pd.parameter).style; } else { System.out.println("Warning: unexpected parameter 6!"+pd); } // Parameters validation and correction if(dashStyle>=Globals.dashNumber) { dashStyle=Globals.dashNumber-1; } if(dashStyle<0) { dashStyle=0; } return i; } /** Gets the distance (in primitive's coordinates space) between a given point and the primitive. When it is reasonable, the behaviour can be binary (ComplexCurves, ovals...). In other cases (lines, points), it can be proportional. @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 getDistanceToPoint(int px, int py) { // Here we check if the given point lies inside the text areas if(checkText(px, py)) { return 0; } int distance = 100; // In this case, the user has not introduced a complete curve, // but just one point. if(p==null) { return GeometricDistances.pointToPoint(virtualPoint[0].x, virtualPoint[0].y, px,py); } // If the curve is filled, we check if the given point lies inside // the polygon. if(isFilled && q.contains(px, py)) { return 1; } // If the curve is not filled, we calculate the distance between the // given point and all the segments composing the curve and we // take the smallest one. int [] xpoints=q.getXpoints(); int [] ypoints=q.getYpoints(); // Check if the point is in the arrows. Correct the starting and ending // points if needed. if (arrowData.atLeastOneArrow()&& !isClosed) { boolean r=false; boolean t=false; // We work with logic coordinates (default for MapCoordinates). MapCoordinates m=new MapCoordinates(); arrowData.prepareCoordinateMapping(m); if (arrowData.isArrowStart()) { t=arrowData.isInArrow(px, py, virtualPoint[0].x, virtualPoint[0].y, xpoints[0], ypoints[0], null); } if (arrowData.isArrowEnd()) { r=arrowData.isInArrow(px, py, xpoints[q.getNpoints()-1], ypoints[q.getNpoints()-1], virtualPoint[nPoints-1].x, virtualPoint[nPoints-1].y, null); } // Click on one of the arrows. if(r||t) { return 1; } } for(int i=0; i<q.getNpoints()-1; ++i) { int d=GeometricDistances.pointToSegment(xpoints[i], ypoints[i], xpoints[i+1], ypoints[i+1], px,py); if(d<distance) { distance = d; } } return distance; } /** Obtain a string command descripion of the primitive. @param extensions true if FidoCadJ extensions to the old FidoCAD format should be active. @return the FidoCadJ command line. */ public String toString(boolean extensions) { // A single point curve without anything is not worth converting. if (name.length()==0 && value.length()==0 && nPoints==1) { return ""; } StringBuffer temp=new StringBuffer(25); if(isFilled) { temp.append("CP "); } else { temp.append("CV "); } if(isClosed) { temp.append("1 "); } else { temp.append("0 "); } for(int i=0; i<nPoints;++i) { temp.append(virtualPoint[i].x); temp.append(" "); temp.append(virtualPoint[i].y); temp.append(" "); } temp.append(getLayer()); temp.append("\n"); String cmd=temp.toString(); if(extensions && (arrowData.atLeastOneArrow() || dashStyle>0 || hasName() || hasValue())) { String text = "0"; // We take into account that there may be some text associated // to that primitive. if (name.length()!=0 || value.length()!=0) { text = "1"; } cmd+="FCJ "+arrowData.createArrowTokens()+" "+dashStyle+" " +text+"\n"; } // The false is needed since saveText should not write the FCJ tag. cmd+=saveText(false); return cmd; } /** Export the primitive on a vector graphic format. @param exp the export interface to employ. @param cs the coordinate mapping to employ. @throws IOException if a problem occurs, such as it is impossible to write on the output file. */ public void export(ExportInterface exp, MapCoordinates cs) throws IOException { double [] xPoints = new double[nPoints]; double [] yPoints = new double[nPoints]; PointDouble[] vertices = new PointDouble[nPoints*STEPS+1]; for (int i=0; i<nPoints; ++i) { xPoints[i] = cs.mapXr(virtualPoint[i].x,virtualPoint[i].y); yPoints[i] = cs.mapYr(virtualPoint[i].x,virtualPoint[i].y); // This is a trick: we do not use another array, but we pre-charge // the control points in vertices (surely we have some place, at // least if STEPS>-1). If the export is done via a polygon, those // points will be discarded and the array reused. vertices[i] = new PointDouble(); vertices[i].x = xPoints[i]; vertices[i].y = yPoints[i]; } // Check if the export is handled via a dedicated curve primitive. // If not, we continue using a polygon with an high number of // vertex if (!exp.exportCurve(vertices, nPoints, isFilled, isClosed, getLayer(), arrowData.isArrowStart(), arrowData.isArrowEnd(), arrowData.getArrowStyle(), (int)(arrowData.getArrowLength()*cs.getXMagnitude()), (int)(arrowData.getArrowHalfWidth()*cs.getXMagnitude()), dashStyle, Globals.lineWidth*cs.getXMagnitude())) { exportAsPolygonInterface(xPoints, yPoints, vertices, exp, cs); int totalnP=q.getNpoints(); // Draw the arrows if they are needed if(q.getNpoints()>2) { if (arrowData.isArrowStart()&&!isClosed) { exp.exportArrow( cs.mapX(virtualPoint[0].x,virtualPoint[0].y), cs.mapY(virtualPoint[0].x,virtualPoint[0].y), vertices[1].x, vertices[1].y, arrowData.getArrowLength()*cs.getXMagnitude(), arrowData.getArrowHalfWidth()*cs.getXMagnitude(), arrowData.getArrowStyle()); } if (arrowData.isArrowEnd()&&!isClosed) { int l=nPoints-1; exp.exportArrow( cs.mapX(virtualPoint[l].x,virtualPoint[l].y), cs.mapY(virtualPoint[l].x,virtualPoint[l].y), vertices[totalnP-2].x, vertices[totalnP-2].y, arrowData.getArrowLength()*cs.getXMagnitude(), arrowData.getArrowHalfWidth()*cs.getXMagnitude(), arrowData.getArrowStyle()); } } } exportText(exp, cs, -1); } /** Expansion of the curve in a polygon with a big number of corners. This is useful when some sort of spline command is not available on the export format chosen. */ private void exportAsPolygonInterface(double [] xPoints, double [] yPoints, PointDouble[] vertices, ExportInterface exp, MapCoordinates cs) throws IOException { Cubic[] xx; Cubic[] yy; int i; if(isClosed) { xx = calcNaturalCubicClosed(nPoints-1, xPoints); yy = calcNaturalCubicClosed(nPoints-1, yPoints); } else { xx = calcNaturalCubic(nPoints-1, xPoints); yy = calcNaturalCubic(nPoints-1, yPoints); // Here we don't check if a point is in the arrow, but we exploit // the code for calculating the base of the head of the arrows. if (arrowData.atLeastOneArrow()) { arrowData.prepareCoordinateMapping(cs); if (arrowData.isArrowStart()) { PointG pp = new PointG(); arrowData.isInArrow(0, 0, (int)Math.round(xx[0].eval(0)), (int)Math.round(yy[0].eval(0)), (int)Math.round(xx[0].eval(0.05)), (int)Math.round(yy[0].eval(0.05)), pp); if(arrowData.getArrowLength()>0) { xPoints[0]=pp.x; yPoints[0]=pp.y; } } if (arrowData.isArrowEnd()) { int l=xx.length-1; PointG pp = new PointG(); arrowData.isInArrow(0, 0, (int)Math.round(xx[l].eval(1)), (int)Math.round(yy[l].eval(1)), (int)Math.round(xx[l].eval(0.95)), (int)Math.round(yy[l].eval(0.95)), pp); if(arrowData.getArrowLength()>0) { xPoints[nPoints-1]=pp.x; yPoints[nPoints-1]=pp.y; } } // Since the arrow will occupy a certain size, the curve has // to be recalculated. This means that the previous evaluation // are just approximations, but the practice shows that they // are enough for all purposes that can be foreseen. // This is not needed if the length is negative, as in this // case the arrow extends outside the curve. if(arrowData.getArrowLength()>0) { xx = calcNaturalCubic(nPoints-1, xPoints); yy = calcNaturalCubic(nPoints-1, yPoints); } } } if(xx==null || yy==null) { return; } /* very crude technique - just break each segment up into steps lines */ vertices[0]=new PointDouble(); vertices[0].x=xx[0].eval(0); vertices[0].y=yy[0].eval(0); for (i = 0; i < xx.length; ++i) { for (int j = 1; j <= STEPS; ++j) { double u = j / (double) STEPS; vertices[i*STEPS+j]=new PointDouble(); vertices[i*STEPS+j].x=xx[i].eval(u); vertices[i*STEPS+j].y=yy[i].eval(u); } } vertices[xx.length*STEPS]=new PointDouble(); vertices[xx.length*STEPS].x=xx[xx.length-1].eval(1.0); vertices[xx.length*STEPS].y=yy[xx.length-1].eval(1.0); if (isClosed) { exp.exportPolygon(vertices, xx.length*STEPS+1, isFilled, getLayer(), dashStyle, Globals.lineWidth*cs.getXMagnitude()); } else { float phase=0; for(i=1; i<xx.length*STEPS+1;++i){ exp.setDashPhase(phase); exp.exportLine(vertices[i-1].x, vertices[i-1].y, vertices[i].x, vertices[i].y, getLayer(), false, false, 0, 0, 0, dashStyle, Globals.lineWidth*cs.getXMagnitude()); phase+=Math.sqrt(Math.pow(vertices[i-1].x-vertices[i].x,2)+ Math.pow(vertices[i-1].y-vertices[i].y,2)); } } } /** Get the number of the virtual point associated to the Name property @return the number of the virtual point associated to the Name property */ public int getNameVirtualPointNumber() { return nPoints; } /** Get the number of the virtual point associated to the Value property @return the number of the virtual point associated to the Value property */ public int getValueVirtualPointNumber() { return nPoints+1; } } /** this class represents a cubic polynomial, by Tim Lambert */ class Cubic { double a; /* a + b*u + c*u^2 +d*u^3 */ double b; double c; double d; public double d1; // Derivatives public double d2; public Cubic(double a, double b, double c, double d) { this.a = a; this.b = b; this.c = c; this.d = d; } /** evaluate cubic */ public double eval(double u) { return ((d*u + c)*u + b)*u + a; } } /** The curve is stored in two vectors. The first contains a curve representation as a polygon with a lot of vertices. The second has as much as elements as the number of control vertices and stores only the derivatives. */ class CurveStorage { List<PointDouble> pp; // Curve as a polygon (relatively big) List<PointDouble> dd; // Derivatives public CurveStorage() { pp = new Vector<PointDouble>(); dd = new Vector<PointDouble>(); } }
42,457
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MouseWheelHandler.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/circuit/MouseWheelHandler.java
package net.sourceforge.fidocadj.circuit; import java.awt.event.*; import net.sourceforge.fidocadj.globals.Globals; /** MouseWheelHandler: handle wheel events for the zoom in/out. <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 miklos80, Davide Bucci </pre> @author Davide Bucci */ public class MouseWheelHandler implements KeyListener, MouseWheelListener { CircuitPanel cc; /** Constructor. @param c the CircuitPanel associated to the wheel events. */ public MouseWheelHandler(CircuitPanel c) { cc=c; } /** Windows and Linux users can use Ctrl+Wheel to zoom in and out. With MacOSX, however Ctrl+Wheel is associated to the full screen zooming. Therefore, we use Command ("meta" with the Java terminology). */ private int getKeyForWheel() { int keyCode=KeyEvent.VK_CONTROL; if(Globals.weAreOnAMac) { keyCode=KeyEvent.VK_META; } return keyCode; } /** Intercepts the moment when the Ctrl or Command key is pressed (see the note for getKeyForWheel(), so that the wheel listener is added. */ @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == getKeyForWheel() && !hasMouseWheelListener()) { cc.addMouseWheelListener(this); } } /** Intercepts the moment when the Ctrl or Command key is released (see the note for getKeyForWheel(), so that the wheel listener is removed. */ @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == getKeyForWheel() && hasMouseWheelListener()) { cc.removeMouseWheelListener(this); } } /** Required by the KeyListener interface. */ @Override public void keyTyped(KeyEvent e) { // do nothing } /** Determines wether in the wheel listener there is this class. */ private boolean hasMouseWheelListener() { MouseWheelListener[] listeners = cc.getMouseWheelListeners(); for (MouseWheelListener mouseWheelListener : listeners) { if (mouseWheelListener.equals(this)) { return true; } } return false; } /** Handle zoom event via the wheel. */ @Override public void mouseWheelMoved(MouseWheelEvent e) { cc.changeZoomByStep(e.getWheelRotation() < 0, e.getX(), e.getY(), 1.1); } }
3,192
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
PopUpMenu.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/circuit/PopUpMenu.java
package net.sourceforge.fidocadj.circuit; import java.awt.event.*; import java.io.*; import javax.swing.*; import net.sourceforge.fidocadj.dialogs.DialogSymbolize; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.globals.LibUtils; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; import net.sourceforge.fidocadj.primitives.PrimitiveComplexCurve; import net.sourceforge.fidocadj.primitives.PrimitivePolygon; 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.UndoActions; import net.sourceforge.fidocadj.circuit.controllers.ContinuosMoveActions; import net.sourceforge.fidocadj.circuit.controllers.EditorActions; import net.sourceforge.fidocadj.circuit.controllers.SelectionActions; import net.sourceforge.fidocadj.clipboard.TextTransfer; /** Pop up menu for the main editing panel. <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 PopUpMenu implements ActionListener { // Elements to be included in the popup menu. private JMenuItem editProperties; private JMenuItem editCut; private JMenuItem editCopy; private JMenuItem editPaste; private JMenuItem editDuplicate; private JMenuItem editSelectAll; private JMenuItem editRotate; private JMenuItem editMirror; private JMenuItem editSymbolize; // phylum private JMenuItem editUSymbolize; // phylum private JMenuItem editAddNode; private JMenuItem editRemoveNode; private final CircuitPanel cp; private final SelectionActions sa; private final EditorActions edt; private final ContinuosMoveActions eea; private final UndoActions ua; private final ParserActions pa; private final CopyPasteActions cpa; private final JPopupMenu pp; // We need to save the position where the popup menu appears. private int menux; private int menuy; /** Constructor. Create a PopUpMenu and associates it to the provided handler. @param p the CircuitPanel. */ public PopUpMenu(CircuitPanel p) { cp=p; sa=cp.getSelectionActions(); edt=cp.getEditorActions(); eea=cp.getContinuosMoveActions(); ua=cp.getUndoActions(); pa=cp.getParserActions(); cpa=cp.getCopyPasteActions(); pp = new JPopupMenu(); definePopupMenu(); } /** Get the x coordinate of the place where the user clicked for the popup menu. @return the x coordinate. */ public int getMenuX() { return menux; } /** Get the y coordinate of the place where the user clicked for the popup menu. @return the y coordinate. */ public int getMenuY() { return menuy; } /** Create the popup menu. */ private void definePopupMenu() { editProperties = new JMenuItem(Globals.messages.getString("Param_opt")); editCut = new JMenuItem(Globals.messages.getString("Cut")); editCopy = new JMenuItem(Globals.messages.getString("Copy")); editSelectAll = new JMenuItem(Globals.messages.getString("SelectAll")); editPaste = new JMenuItem(Globals.messages.getString("Paste")); editDuplicate = new JMenuItem(Globals.messages.getString("Duplicate")); editRotate = new JMenuItem(Globals.messages.getString("Rotate")); editMirror = new JMenuItem(Globals.messages.getString("Mirror_E")); editSymbolize = new JMenuItem(Globals.messages.getString("Symbolize")); editUSymbolize = new JMenuItem(Globals.messages.getString("Unsymbolize")); editAddNode = new JMenuItem(Globals.messages.getString("Add_node")); editRemoveNode = new JMenuItem(Globals.messages.getString("Remove_node")); pp.add(editProperties); pp.addSeparator(); pp.add(editCut); pp.add(editCopy); pp.add(editPaste); pp.add(editDuplicate); pp.addSeparator(); pp.add(editSelectAll); pp.addSeparator(); pp.add(editRotate); pp.add(editMirror); pp.add(editAddNode); pp.add(editRemoveNode); pp.addSeparator(); pp.add(editSymbolize); // by phylum pp.add(editUSymbolize); // phylum // Adding the action listener editProperties.addActionListener(this); editCut.addActionListener(this); editCopy.addActionListener(this); editSelectAll.addActionListener(this); editPaste.addActionListener(this); editDuplicate.addActionListener(this); editRotate.addActionListener(this); editMirror.addActionListener(this); editAddNode.addActionListener(this); editRemoveNode.addActionListener(this); editSymbolize.addActionListener(this); // phylum editUSymbolize.addActionListener(this); // phylum } /** Show a popup menu representing the actions that can be done on the selected context. @param j the panel to which this menu should be associated. @param x the x coordinate where the popup menu should be put. @param y the y coordinate where the popup menu should be put. */ public void showPopUpMenu(JPanel j, int x, int y) { menux=x; menuy=y; boolean s=false; GraphicPrimitive g=sa.getFirstSelectedPrimitive(); boolean somethingSelected=g!=null; // A certain number of menu options are applied to selected // primitives. We therefore check wether are there some // of them available and in cp case we activate what should // be activated in the pop up menu. s=somethingSelected; editProperties.setEnabled(s); editCut.setEnabled(s); editCopy.setEnabled(s); editRotate.setEnabled(s); editMirror.setEnabled(s); editDuplicate.setEnabled(s); editSelectAll.setEnabled(true); if(g instanceof PrimitiveComplexCurve || g instanceof PrimitivePolygon) { s=true; } else { s=false; } if (!sa.isUniquePrimitiveSelected()) { s=false; } editAddNode.setEnabled(s); editRemoveNode.setEnabled(s); editAddNode.setVisible(s); editRemoveNode.setVisible(s); // We just check if the clipboard is empty. It would be better // to see if there is some FidoCadJ code wich might be pasted TextTransfer textTransfer = new TextTransfer(); if("".equals(textTransfer.getClipboardContents())) { editPaste.setEnabled(false); } else { editPaste.setEnabled(true); } editSymbolize.setEnabled(somethingSelected); editUSymbolize.setEnabled(sa.selectionCanBeSplitted()); // phylum pp.show(j, x, y); } /** Register an action involving the editing @param actionString the action name to be associated to this action @param key the key to be used. It will be associated either in lower case as well as in upper case. @param state the wanted state to be used (see definitions INTERFACE). */ private void registerAction(String actionString, char key, final int state) { // We need to make this indipendent to the case. So we start by // registering the action for the upper case cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(Character.toUpperCase(key)), actionString); // And then we repeat the operation for the lower case cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(Character.toLowerCase(key)), actionString); cp.getActionMap().put(actionString, new AbstractAction() { @Override public void actionPerformed(ActionEvent ignored) { // We now set the new editing state cp.setSelectionState(state,""); // If we are entering or modifying a primitive or a macro, // we should be sure it disappears when the state changes eea.primEdit = null; cp.repaint(); } }); } /** Register a certain number of keyboard actions with an associated meaning: <pre> [A], [space] or [ESC] Selection [L] Line [T] Text [B] Bézier [P] Polygon [O] Complex curve [E] Ellipse [G] Rectangle [C] Connection [I] PCB track [Z] PCB pad [DEL] or [BACKSPC] Delete the selected objects </pre> */ public final void registerActiveKeys() { registerAction("selection", 'a', ElementsEdtActions.SELECTION); cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,0,false), "selection"); cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0,false), "selection"); registerAction("line", 'l', ElementsEdtActions.LINE); registerAction("text", 't', ElementsEdtActions.TEXT); registerAction("bezier", 'b', ElementsEdtActions.BEZIER); registerAction("polygon", 'p', ElementsEdtActions.POLYGON); registerAction("complexcurve", 'o', ElementsEdtActions.COMPLEXCURVE); registerAction("ellipse", 'e', ElementsEdtActions.ELLIPSE); registerAction("rectangle", 'g', ElementsEdtActions.RECTANGLE); registerAction("connection", 'c', ElementsEdtActions.CONNECTION); registerAction("pcbline", 'i', ElementsEdtActions.PCB_LINE); registerAction("pcbpad", 'z', ElementsEdtActions.PCB_PAD); final String delete = "delete"; // Delete key cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("DELETE"), delete); cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("BACK_SPACE"), delete); cp.getActionMap().put(delete, new AbstractAction() { @Override public void actionPerformed(ActionEvent ignored) { edt.deleteAllSelected(true); cp.repaint(); } }); final String escape = "escape"; // Escape: clear everything /*cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke("ESCAPE"), escape);*/ cp.getActionMap().put(escape, new AbstractAction() { @Override public void actionPerformed(ActionEvent ignored) { if(eea.clickNumber>0){ // Here we need to clear the variables which are used // during the primitive introduction and editing. // see mouseMoved method for details. eea.successiveMove = false; eea.clickNumber = 0; eea.primEdit = null; cp.repaint(); } } }); final String left = "lleft"; // left key cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.ALT_MASK,false), left); cp.getActionMap().put(left, new AbstractAction() { @Override public void actionPerformed(ActionEvent ignored) { edt.moveAllSelected(-1,0); cp.repaint(); } }); final String right = "lright"; // right key cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.ALT_MASK,false), right); cp.getActionMap().put(right, new AbstractAction() { @Override public void actionPerformed(ActionEvent ignored) { edt.moveAllSelected(1,0); cp.repaint(); } }); final String up = "lup"; // up key cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.ALT_MASK,false), up); cp.getActionMap().put(up, new AbstractAction() { @Override public void actionPerformed(ActionEvent ignored) { edt.moveAllSelected(0,-1); cp.repaint(); } }); final String down = "ldown"; // down key cp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) .put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.ALT_MASK,false), down); cp.getActionMap().put(down, new AbstractAction() { @Override public void actionPerformed(ActionEvent ignored) { edt.moveAllSelected(0,1); cp.repaint(); } }); } /** The action listener. Recognize menu events and behaves consequently. @param evt the MouseEvent to handle */ @Override public void actionPerformed(ActionEvent evt) { // TODO: Avoid some copy/paste of code // Recognize and handle popup menu events if(evt.getSource() instanceof JMenuItem) { String arg=evt.getActionCommand(); if (arg.equals(Globals.messages.getString("Param_opt"))) { cp.setPropertiesForPrimitive(); } else if (arg.equals(Globals.messages.getString("Copy"))) { // Copy all selected elements in the clipboard cpa.copySelected(!cp.getStrictCompatibility(), false); } else if (arg.equals(Globals.messages.getString("Cut"))) { // Cut elements cpa.copySelected(!cp.getStrictCompatibility(), false); edt.deleteAllSelected(true); cp.repaint(); } else if (arg.equals(Globals.messages.getString("Paste"))) { // Paste elements from the clipboard cpa.paste(cp.getMapCoordinates().getXGridStep(), cp.getMapCoordinates().getYGridStep()); cp.repaint(); } else if (arg.equals(Globals.messages.getString("Duplicate"))) { // Copy all selected elements in the clipboard cpa.copySelected(!cp.getStrictCompatibility(), false); // Paste elements from the clipboard cpa.paste(cp.getMapCoordinates().getXGridStep(), cp.getMapCoordinates().getYGridStep()); cp.repaint(); } else if (arg.equals(Globals.messages.getString("SelectAll"))) { // Select all in the drawing. sa.setSelectionAll(true); // Even if the drawing is not changed, a repaint operation is // needed since all selected elements are rendered in green. cp.repaint(); } else if (arg.equals(Globals.messages.getString("Rotate"))) { // Rotate the selected element if(eea.isEnteringMacro()) { eea.rotateMacro(); } else { edt.rotateAllSelected(); } cp.repaint(); } else if(arg.equals(Globals.messages.getString("Mirror_E"))) { // Mirror the selected element if(eea.isEnteringMacro()) { eea.mirrorMacro(); } else { edt.mirrorAllSelected(); } cp.repaint(); } else if (arg.equals(Globals.messages.getString("Symbolize"))) { if (sa.getFirstSelectedPrimitive() == null) { return; } DialogSymbolize s = new DialogSymbolize(cp, cp.getDrawingModel()); s.setModal(true); s.setVisible(true); try { LibUtils.saveLibraryState(ua); } catch (IOException e) { System.out.println("Exception: "+e); } cp.repaint(); } else if (arg.equals(Globals.messages.getString("Unsymbolize"))) { StringBuffer s=sa.getSelectedString(true, pa); edt.deleteAllSelected(false); pa.addString(pa.splitMacros(s, true),true); ua.saveUndoState(); cp.repaint(); } else if(arg.equals(Globals.messages.getString("Remove_node"))) { if(sa.getFirstSelectedPrimitive() instanceof PrimitivePolygon) { PrimitivePolygon poly= (PrimitivePolygon)sa.getFirstSelectedPrimitive(); poly.removePoint( cp.getMapCoordinates().unmapXnosnap(getMenuX()), cp.getMapCoordinates().unmapYnosnap(getMenuY()), 1); ua.saveUndoState(); cp.repaint(); } else if(sa.getFirstSelectedPrimitive() instanceof PrimitiveComplexCurve) { PrimitiveComplexCurve curve= (PrimitiveComplexCurve)sa.getFirstSelectedPrimitive(); curve.removePoint( cp.getMapCoordinates().unmapXnosnap(getMenuX()), cp.getMapCoordinates().unmapYnosnap(getMenuY()), 1); ua.saveUndoState(); cp.repaint(); } } else if(arg.equals(Globals.messages.getString("Add_node"))) { if(sa.getFirstSelectedPrimitive() instanceof PrimitivePolygon) { PrimitivePolygon poly= (PrimitivePolygon)sa.getFirstSelectedPrimitive(); poly.addPointClosest( cp.getMapCoordinates().unmapXsnap(getMenuX()), cp.getMapCoordinates().unmapYsnap(getMenuY())); ua.saveUndoState(); cp.repaint(); } else if(sa.getFirstSelectedPrimitive() instanceof PrimitiveComplexCurve) { PrimitiveComplexCurve poly= (PrimitiveComplexCurve)sa.getFirstSelectedPrimitive(); poly.addPointClosest( cp.getMapCoordinates().unmapXsnap(getMenuX()), cp.getMapCoordinates().unmapYsnap(getMenuY())); ua.saveUndoState(); cp.repaint(); } } } } }
20,053
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/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
CircuitPanel.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/circuit/CircuitPanel.java
package net.sourceforge.fidocadj.circuit; import java.awt.*; import java.io.*; import java.awt.event.*; import javax.swing.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.LayerInfo; import net.sourceforge.fidocadj.dialogs.ParameterDescription; import net.sourceforge.fidocadj.dialogs.DialogParameters; import net.sourceforge.fidocadj.primitives.GraphicPrimitive; import net.sourceforge.fidocadj.timer.MyTimer; import net.sourceforge.fidocadj.toolbars.ChangeSelectionListener; import net.sourceforge.fidocadj.toolbars.ChangeZoomListener; import net.sourceforge.fidocadj.toolbars.ChangeGridState; import net.sourceforge.fidocadj.toolbars.ChangeSelectedLayer; import net.sourceforge.fidocadj.circuit.controllers.EditorActions; import net.sourceforge.fidocadj.circuit.controllers.CopyPasteActions; import net.sourceforge.fidocadj.circuit.controllers.ParserActions; import net.sourceforge.fidocadj.circuit.controllers.UndoActions; import net.sourceforge.fidocadj.circuit.controllers.ContinuosMoveActions; import net.sourceforge.fidocadj.circuit.controllers.SelectionActions; import net.sourceforge.fidocadj.circuit.controllers.PrimitivesParInterface; import net.sourceforge.fidocadj.circuit.controllers.ElementsEdtActions; import net.sourceforge.fidocadj.circuit.model.DrawingModel; import net.sourceforge.fidocadj.circuit.views.Drawing; import net.sourceforge.fidocadj.clipboard.TextTransfer; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.DimensionG; import net.sourceforge.fidocadj.graphic.swing.Graphics2DSwing; import net.sourceforge.fidocadj.graphic.swing.ColorSwing; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.geom.DrawingSize; import net.sourceforge.fidocadj.globals.Globals; /** Circuit panel: draw the circuit inside this panel. This is one of the most important components, as it is responsible of all editing actions. In many ways, this class contains the most important component of FidoCadJ. This class is able to perform its profiling, which is in particular the measurement of the time needed to draw the circuit. <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 CircuitPanel extends JPanel implements ChangeSelectedLayer, ChangeGridState, ChangeZoomListener, ChangeSelectionListener, PrimitivesParInterface { // *********** DRAWING *********** Graphics2DSwing graphicSwing; // Coordinate system to be used. private transient MapCoordinates cs; // Use anti alias in drawings public boolean antiAlias; // Draw the grid private boolean isGridVisible; // Default background color private Color backgroundColor; // Position of the rectangle used for the selection private Rectangle evidenceRect; // Margin size in pixels when calculating component sizes. public static final int MARGIN=20; // Color of elements during editing static final ColorSwing editingColor=new ColorSwing(Color.green); // Model: // TODO: This should be kept private! public transient DrawingModel dmp; // Scrolling pane data public JScrollPane father; private static final int MINSIZEX=1000; private static final int MINSIZEY=1000; // Views: public Drawing drawingAgent; // Controllers: private EditorActions edt; private CopyPasteActions cpa; private ParserActions pa; private UndoActions ua; private ContinuosMoveActions eea; private SelectionActions sa; // ********** PROFILING ********** // Specify that the profiling mode should be activated. public boolean profileTime; private double average; // Record time for the redrawing. private double record; // Number of times the redraw has occourred. private double runs; // ********** INTERFACE ********** // If this variable is different from null, the component will ensure that // the corresponding rectangle will be shown in a scroll panel during the // next redraw. private Rectangle scrollRectangle; // Strict FidoCAD compatibility public boolean extStrict; // ********** RULER ********** private final Ruler ruler; // Is it to be drawn? // ********** INTERFACE ELEMENTS ********** PopUpMenu popup; // Popup menu MouseWheelHandler mwHandler; // Wheel handler MouseMoveClickHandler mmcHandler; // Mouse click handler // ********** LISTENERS ********** private ChangeZoomListener zoomListener; private ChangeSelectionListener selectionListener; private ChangeSelectionListener scrollGestureSelectionListener; /** Standard constructor @param isEditable indicates whether the panel should be responsible to keyboard and mouse inputs. */ public CircuitPanel (boolean isEditable) { backgroundColor=Color.white; setDrawingModel(new DrawingModel()); mwHandler=new MouseWheelHandler(this); mmcHandler= new MouseMoveClickHandler(this); graphicSwing = new Graphics2DSwing(); ruler = new Ruler(editingColor.getColorSwing(), editingColor.getColorSwing().darker().darker()); isGridVisible=true; zoomListener=null; antiAlias = true; record = 1e100; evidenceRect = new Rectangle(0,0,-1,-1); // Set up the standard view settings: // top left corner, 400% zoom. cs = new MapCoordinates(); cs.setXCenter(0.0); cs.setYCenter(0.0); cs.setXMagnitude(4.0); cs.setYMagnitude(4.0); cs.setOrientation(0); setOpaque(true); runs = 0; average = 0; // This is not useful when preparing the applet: the circuit panel will // not be editable in this case. if (isEditable) { addMouseListener(mmcHandler); addMouseMotionListener(mmcHandler); addKeyListener(mwHandler); setFocusable(true); //Create the popup menu. popup=new PopUpMenu(this); popup.registerActiveKeys(); // Patchwork for bug#54. // When mouse pointer enters into CircuitPanel with macro, // grab focus from macropicker. // NOTE: MouseListener.mouseEntered doesn't works stable. addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { if(eea.isEnteringMacro() && !isFocusOwner()){ requestFocus(); } } }); } } /** 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(); } /** 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 */ public void showPopUpMenu(int x, int y) { popup.showPopUpMenu(this, x, y); } /** Makes sure the object gets focus. */ public void getFocus() { requestFocusInWindow(); } /** ChangeSelectionListener interface implementation @param s the selection state @param macro the macro key (if applies) */ public void setSelectionState(int s, String macro) { if (selectionListener!=null && s!=eea.actionSelected) { selectionListener.setSelectionState(s, macro); selectionListener.setStrictCompatibility(extStrict); } if (scrollGestureSelectionListener!=null) { scrollGestureSelectionListener.setSelectionState(s, macro); } eea.setState(s, macro); mmcHandler.selectCursor(); } /** Set the rectangle which will be shown during the next redraw. @param r the rectangle to show. */ public void setScrollRectangle(Rectangle r) { scrollRectangle = r; repaint(); } /** Define the listener to be called when the zoom is changed @param c the new zoom listener. */ public void addChangeZoomListener(ChangeZoomListener c) { zoomListener=c; } /** Define the listener to be called when the selected action is changed @param c the new selection listener. */ public void addChangeSelectionListener(ChangeSelectionListener c) { selectionListener=c; eea.setChangeSelectionListener(c); } /** Define the listener to be called when the selected action is changed (this is explicitly done for the ScrollGestureSelection). @param c the new selection listener. */ public void addScrollGestureSelectionListener(ChangeSelectionListener c) { scrollGestureSelectionListener=c; } /** Return the current editing layer. @return the index of the layer. */ public int getCurrentLayer() { return eea.currentLayer; } /** Set the current editing layer. @param cl the wanted layer. */ public void setCurrentLayer(int cl) { int l=cl; /* two little checks... */ if (l<0) { l=0; } if (l>=dmp.getLayers().size()) { l=dmp.getLayers().size()-1; } eea.currentLayer=l; } /** Change the current layer state. Change the layer of all selected primitives. @param s the layer to be selected. */ public void changeSelectedLayer(int s) { // Change the current layer eea.currentLayer=s; // Change also the layer of all selected primitives if(edt.setLayerForSelectedPrimitives(s)) { repaint(); } } /** The method which is called when the current grid visibility has to be changed. @param v is the wanted grid visibility state. */ public void setGridVisibility(boolean v) { isGridVisible=v; repaint(); } /** Determines if the grid is visible or not. @return the grid visibility. */ public boolean getGridVisibility() { return isGridVisible; } /** The method to be called when the current snap visibility has changed. @param v is the wanted snap state. */ public void setSnapState(boolean v) { cs.setSnap(v); } /** Determines if the grid is visible or not. @return the grid visibility. */ public boolean getSnapState() { return cs.getSnap(); } /** Increase or decrease 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 the amount the zoom is multiplied (or divided). Should be greater than 1. */ public void changeZoomByStep(boolean increase, int x, int y, double rate) { int xpos = cs.unmapXnosnap(x); int ypos = cs.unmapYnosnap(y); double z=cs.getXMagnitude(); // Click+Meta reduces the zoom // Click raises the zoom double oldz=z; if(increase) { z=z*rate; } else { z=z/rate; } // Checking that reasonable limits are not exceeded. if(z>Globals.maxZoomFactor/100) {z=Globals.maxZoomFactor/100;} if(z<Globals.minZoomFactor/100) {z=Globals.minZoomFactor/100;} z=Math.round(z*100.0)/100.0; if (Math.abs(oldz-z)<1e-5) { return; } cs.setMagnitudes(z,z); // A little strong... int width = father.getViewport().getExtentSize().width; int height = father.getViewport().getExtentSize().height; Point rr=father.getViewport().getViewPosition(); int corrx=x-rr.x; int corry=y-rr.y; Rectangle r=new Rectangle(cs.mapXi(xpos,ypos,false)-corrx, cs.mapYi(xpos,ypos,false)-corry, width, height); updateSizeOfScrollBars(r); } /** Calculate the size of the image and update the size of the scroll bars, with the current zoom. @param r the Rectangle which will contain the new image size at the end of this method. */ public void updateSizeOfScrollBars(Rectangle r) { PointG origin=new PointG(); DimensionG d=DrawingSize.getImageSize(dmp, cs.getXMagnitude(), false, origin); int minx=cs.mapXi(MINSIZEX,MINSIZEY,false); int miny=cs.mapYi(MINSIZEX,MINSIZEY,false); Dimension dd=new Dimension(Math.max(d.width +MARGIN, minx),Math.max(d.height+MARGIN, miny)); setPreferredSize(dd); if(r!=null) { scrollRectangle = r; } revalidate(); repaint(); } /** Get the current editing action (see the constants defined in this class). @return the current editing action. */ public int getSelectionState() { return eea.getSelectionState(); } /** The zoom listener. @param tz the zoom factor to be used. */ public void changeZoom(double tz) { double z=Math.round(tz*100.0)/100.0; cs.setMagnitudes(z,z); eea.successiveMove=false; requestFocusInWindow(); // # repaint(); } /** Sets the background color. @param sfondo the background color to be used. */ @Override public void setBackground(Color sfondo) { backgroundColor=sfondo; } /** 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. */ public void setEvidenceRect(int lx, int ly, int w, int h) { evidenceRect = new Rectangle(); evidenceRect.x=lx; evidenceRect.y=ly; evidenceRect.height=h; evidenceRect.width=w; } /** Repaint the panel. This method performs the following operations:<br> 1. set the anti aliasing on (or off, depending on antiAlias).<br> 2. paint in white the background, draw the bk. image and the grid.<br> 3. call drawingAgent draw.<br> 4. draw all active handles.<br> 5. if needed, draw the primitive being edited.<br> 6. draw the ruler, if needed.<br> 7. if requested, print information about redraw speed.<br> @param g the graphic context on which perform the drawing operations. */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); MyTimer mt; mt = new MyTimer(); Graphics2D g2 = (Graphics2D)g; graphicSwing.setGraphicContext(g2); activateDrawingSettings(g2); // Draw the background. g.setColor(backgroundColor); g.fillRect(0, 0, getWidth(), getHeight()); dmp.imgCanvas.drawCanvasImage(g2, cs); // Draw the grid if necessary. if(isGridVisible) { graphicSwing.drawGrid(cs,0,0,getWidth(), getHeight()); } // The standard color is black. g.setColor(Color.black); // This is important for taking into account the dashing size graphicSwing.setZoom(cs.getXMagnitude()); // Draw all the elements of the drawing. drawingAgent.draw(graphicSwing, cs); dmp.imgCanvas.trackExtremePoints(cs); if (zoomListener!=null) { zoomListener.changeZoom(cs.getXMagnitude()); } // Draw the handles of all selected primitives. drawingAgent.drawSelectedHandles(graphicSwing, cs); // If an evidence rectangle is active, draw it. g.setColor(editingColor.getColorSwing()); g2.setStroke(new BasicStroke(1)); if(evidenceRect!=null && eea.actionSelected == ElementsEdtActions.SELECTION) { g.drawRect(evidenceRect.x,evidenceRect.y, evidenceRect.width, evidenceRect.height); } else { evidenceRect = null; } // If there is a primitive or a macro being edited, draws it. eea.drawPrimEdit(graphicSwing, cs); // If a ruler.isActive() is active, draw it. ruler.drawRuler(g, cs); setSizeIfNeeded(); if(scrollRectangle!=null) { Rectangle r=scrollRectangle; scrollRectangle = null; scrollRectToVisible(r); } // Since the redraw speed is a capital parameter which determines the // perceived speed, we monitor it very carefully if the program // profiling is active. if(profileTime) { double elapsed=mt.getElapsed(); g2.drawString("Version: "+ Globals.version, 0,100); g.drawString("Time elapsed: " + elapsed+" ms" ,0,50); ++runs; average += elapsed; if(elapsed<record) { record=elapsed; } System.out.println("R: Time elapsed: "+ elapsed+ " averaging "+ average/runs+ "ms in "+runs+ " redraws; record: "+record+" ms"); } } /** Activate or deactivate anti-aliasing if necessary. */ private void activateDrawingSettings(Graphics2D g2) { if (antiAlias) { g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); } else { // Faster graphic (??? true??? I do not think so on modern systems) g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED); g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF); g2.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); } } /** Set the new size of the drawing, if needed. */ private void setSizeIfNeeded() { Dimension d=new Dimension(cs.getXMax(), cs.getYMax()); if (d.width>0 && d.height>0) { int minx=cs.mapXi(MINSIZEX,MINSIZEY,false); int miny=cs.mapYi(MINSIZEX,MINSIZEY,false); Dimension dd=new Dimension(Math.max(d.width +MARGIN, minx),Math.max(d.height+MARGIN, miny)); Dimension nn=getPreferredSize(); if(dd.width!=nn.width || dd.height!=nn.height) { setPreferredSize(dd); revalidate(); } } } /** Update the current size of the object, given the current size of the drawing. */ @Override public void validate() { int minx=cs.mapXi(MINSIZEX,MINSIZEY,false); int miny=cs.mapYi(MINSIZEX,MINSIZEY,false); Dimension dd=new Dimension(Math.max(cs.getXMax() +MARGIN, minx),Math.max(cs.getYMax()+MARGIN, miny)); Dimension nn=getPreferredSize(); if(dd.width!=nn.width || dd.height!=nn.height) { setPreferredSize(dd); } super.validate(); } /** Get the current drawing model. @return the drawing model. */ public final DrawingModel getDrawingModel() { return dmp; } /** Set the current drawing model. Changing it mean that all the controllers and views associated to the panel will be updated. @param dm the drawing model. */ public final void setDrawingModel(DrawingModel dm) { dmp=dm; sa = new SelectionActions(dmp); pa =new ParserActions(dmp); ua = new UndoActions(pa); edt = new EditorActions(dmp, sa, ua); eea = new ContinuosMoveActions(dmp, sa, ua, edt); drawingAgent=new Drawing(dmp); eea.setPrimitivesParListener(this); cpa=new CopyPasteActions(dmp, edt, sa, pa, ua, new TextTransfer()); } /** Get the current instance of SelectionActions controller class @return the class */ public SelectionActions getSelectionActions() { return sa; } /** Get the current instance of EditorActions controller class @return the class */ public EditorActions getEditorActions() { return edt; } /** Get the current instance of CopyPasteActions controller class @return the class */ public CopyPasteActions getCopyPasteActions() { return cpa; } /** Get the current instance of ParserActions controller class @return the class */ public ParserActions getParserActions() { return pa; } /** Get the current instance of UndoActions controller class @return the class */ public UndoActions getUndoActions() { return ua; } /** Get the current instance of ElementsEdtActions controller class @return the class */ public ContinuosMoveActions getContinuosMoveActions() { return eea; } /** 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. */ public void setPropertiesForPrimitive() { GraphicPrimitive gp=sa.getFirstSelectedPrimitive(); if (gp==null) { return; } java.util.List<ParameterDescription> v; if (sa.isUniquePrimitiveSelected()) { v=gp.getControls(); } else { // If more than a primitive is selected, v=new Vector<ParameterDescription>(1); ParameterDescription pd = new ParameterDescription(); pd.parameter=new LayerInfo(gp.getLayer()); pd.description=Globals.messages.getString("ctrl_layer"); v.add(pd); } DialogParameters dp = new DialogParameters( (JFrame)Globals.activeWindow, v, extStrict, dmp.getLayers()); dp.setVisible(true); if(dp.active) { if (sa.isUniquePrimitiveSelected()) { gp.setControls(dp.getCharacteristics()); } else { ParameterDescription pd=(ParameterDescription)v.get(0); dp.getCharacteristics(); if (pd.parameter instanceof LayerInfo) { int l=((LayerInfo)pd.parameter).getLayer(); edt.setLayerForSelectedPrimitives(l); } else { System.out.println( "Warning: unexpected parameter! (layer)"); } } dmp.setChanged(true); // We need to check and sort the layers, since the user can // change the layer associated to a given primitive thanks to // the dialog window which has been shown. dmp.sortPrimitiveLayers(); ua.saveUndoState(); repaint(); } } /** 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. */ public void selectAndSetProperties(int x, int y) { sa.setSelectionAll(false); edt.handleSelection(cs, x, y, false); repaint(); setPropertiesForPrimitive(); } /** Checks if FidoCadJ should strictly comply with the FidoCAD format (and limitations). @return the compliance mode. */ public boolean getStrictCompatibility() { return extStrict; } /** 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) { extStrict=strict; } /** Change the current coordinate mapping. @param m the new coordinate mapping to be adopted. */ public void setMapCoordinates(MapCoordinates m) { cs=m; // Force an in-depth redraw. dmp.setChanged(true); } /** Get the current coordinate mapping. @return the current coordinate mapping. */ public MapCoordinates getMapCoordinates() { return cs; } /** Force a repaint. */ public void forcesRepaint() { repaint(); } /** Force 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. */ public void forcesRepaint(int x, int y, int width, int height) { repaint(x, y, width, height); } /** Get the Ruler object. @return the Ruler object. */ public Ruler getRuler() { return ruler; } /** Check if the profiling is active. @return true if the profiling is active. */ public boolean isProfiling() { return profileTime; } /** Get the attached image as background. @return the attached image object. */ public ImageAsCanvas getAttachedImage() { return dmp.imgCanvas; } }
28,012
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ImageAsCanvas.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/circuit/ImageAsCanvas.java
package net.sourceforge.fidocadj.circuit; import java.awt.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; import net.sourceforge.fidocadj.geom.MapCoordinates; /** Employs a bitmap image as a canvas to trace on 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 2017-2023 by Davide Bucci </pre> */ public class ImageAsCanvas { private BufferedImage img; private String filename; private BufferedImage resizedImg; private double resolution=200; private double xcorner=0; private double ycorner=0; // Some temporary data used during the calculations. private int oldw=0; private int oldh=0; private int shiftx=0; private int shifty=0; private final int maxResizedWidth; private final int maxResizedHeight; /** Constructor. */ public ImageAsCanvas() { img=null; Dimension screensize; try { screensize=Toolkit.getDefaultToolkit().getScreenSize(); } catch (HeadlessException eE) { screensize=new Dimension(1000,1000); } maxResizedWidth=screensize.width*3; maxResizedHeight=screensize.height*3; } /** 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 { img=ImageIO.read(new File(f)); filename=f; } /** Specify an image to attach to the current drawing. @param f the path and the filename of the image file to load and display. @param i the image to be loaded. */ public void loadImage(String f, BufferedImage i) { img=i; filename=f; } /** 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) { resolution=res; } /** Get the current resolution in dpi. @return the current resolution in dots per inch. */ public double getResolution() { return resolution; } /** Remove the attached image. */ public void removeImage() { img=null; } /** Get the current file name. @return the current file name */ public String getFilename() { return filename; } /** 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) { xcorner=x; ycorner=y; } /** Get the x coordinate of the left topmost point of the image (use FidoCadJ coordinates). @return the x coordinate. */ public double getCornerX() { return xcorner; } /** Track the extreme points of the image in the given coordinate systems. @param mc the coordinate systems. */ public void trackExtremePoints(MapCoordinates mc) { if(img==null) { return; } int ox=mc.mapXi(xcorner, ycorner,false); int oy=mc.mapYi(xcorner, ycorner,false); // The FidoCadJ resolution is 200dpi. int w=(int)(200.0*img.getWidth()/resolution*mc.getXMagnitude()+0.5); int h=(int)(200.0*img.getHeight()/resolution*mc.getYMagnitude()+0.5); mc.trackPoint(ox, oy); mc.trackPoint(ox+w, oy+h); } /** Get the y coordinate of the left topmost point of the image (use FidoCadJ coordinates). @return the y coordinate. */ public double getCornerY() { return ycorner; } /** 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(Graphics2D g, MapCoordinates mc) { if(img==null) { return; } // The image is drawn only in the "dirty" region of the drawing area // so to greatly improve redrawing speed. Rectangle clip=g.getClipBounds(); int regionx=clip.x; int regiony=clip.y; int regionwidth=clip.width; int regionheight=clip.height; // The FidoCadJ resolution is 200dpi. int w=(int)(200.0*img.getWidth()/resolution*mc.getXMagnitude()+0.5); int h=(int)(200.0*img.getHeight()/resolution*mc.getYMagnitude()+0.5); int ox=mc.mapXi(xcorner, ycorner,false); int oy=mc.mapYi(xcorner, ycorner,false); // This code is needed to avoid exceeding the boundaries of the // images (this produces a tiled effect). regionwidth=Math.max(0,Math.min(regionwidth,w-regionx+ox)); regionheight=Math.max(0,Math.min(regionheight,h-regiony+ox)); regionx=Math.max(ox,regionx); regiony=Math.max(oy,regiony); // Resizing an image is pretty time-consuming. Therefore, this is done // only when it is absolutely needed. This happens when the zoom is // changed, or when the chunk of the image which has been resized // should be changed. if(oldw!=w || oldh!=h || regionx<shiftx || regiony<shifty|| regionx+regionwidth>shiftx+maxResizedWidth || regiony+regionheight>shifty+maxResizedHeight) { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = env.getDefaultScreenDevice(); GraphicsConfiguration config = device.getDefaultConfiguration(); oldw=w; oldh=h; if(w<maxResizedWidth && h<maxResizedHeight) { // Here the image can be resized all together. shiftx=ox; shifty=oy; resizedImg = config.createCompatibleImage( w, h, Transparency.TRANSLUCENT); // If the resulting image is very small, implement a multi-step // resize to improve the rendering quality. if(img.getWidth()/w>5) { System.out.print("Multistep reduction"); BufferedImage rs=img; BufferedImage rs1=img; BufferedImage rs2; int nw=img.getWidth(); int nh=img.getHeight(); while (nw>w*2) { System.out.print("."); rs= config.createCompatibleImage( nw/2, nh/2, Transparency.TRANSLUCENT); Graphics2D graphics2D = rs.createGraphics(); graphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); graphics2D.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.drawImage(rs1,0,0,nw/2,nh/2,null); nw=nw/2; nh=nh/2; rs2=rs; rs=rs1; rs1=rs2; } System.out.print("\n"); resizedImg.getGraphics().drawImage(rs,0,0,w,h,null); } else { resizedImg.getGraphics().drawImage(img,0,0,w,h,null); } } else { // Here, resizing the image would produce an image too big. // Therefore, the image is resized by chunks. resizedImg = config.createCompatibleImage( maxResizedWidth, maxResizedHeight, Transparency.TRANSLUCENT); shiftx=Math.max(regionx-maxResizedWidth/3,0)+ox; shifty=Math.max(regiony-maxResizedHeight/3,0)+oy; /*System.out.println("---------------------------"); System.out.println("New shiftx = "+shiftx+ " shifty = "+shifty); */ resizedImg.getGraphics().drawImage(img, 0, 0, maxResizedWidth, maxResizedHeight, (int)(shiftx/mc.getXMagnitude()*resolution/200.0+0.5), (int)(shifty/mc.getXMagnitude()*resolution/200.0+0.5), (int)((shiftx+maxResizedWidth) /mc.getXMagnitude()*resolution/200.0 +0.5), (int)((shifty+maxResizedHeight)/ mc.getYMagnitude()*resolution/200.0+0.5), null); } } // Draw the resized image at the right place. g.drawImage(resizedImg, regionx, regiony, regionx+regionwidth, regiony+regionheight, regionx-shiftx, regiony-shifty, regionx+regionwidth-shiftx, regiony+regionheight-shifty, null); } }
10,223
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
Ruler.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/circuit/Ruler.java
package net.sourceforge.fidocadj.circuit; import java.awt.*; import net.sourceforge.fidocadj.geom.MapCoordinates; import net.sourceforge.fidocadj.globals.Globals; /** Draw a ruler. <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 Ruler { // Font to be used to draw the ruler. private static final String rulerFont = "Lucida Sans Regular"; // Color of elements during editing. private final Color rulerColor; private final Color textColor; // Begin and end coordinates. private int rulerStartX; private int rulerStartY; private int rulerEndX; private int rulerEndY; // Is the ruler active? private boolean isActiveRuler; /** Constructor, specify the colors to be employed. @param rc the color of ruler elements. @param tc the color of text elements. */ public Ruler(Color rc, Color tc) { rulerColor=rc; textColor=tc; isActiveRuler=false; } /** Set wether the ruler should be drawn or not. @param s true if the ruler should be drawn. */ public void setActive(boolean s) { isActiveRuler=s; } /** Gets the current status of the ruler. @return true if the ruler should be drawn, false if not. */ public boolean isActive() { return isActiveRuler; } /** Draws a ruler to ease measuring distances. @param g the graphic context. @param cs the coordinate mapping. */ public void drawRuler(Graphics g, MapCoordinates cs) { if (!isActiveRuler) { return; } int sx=rulerStartX; int sy=rulerStartY; int ex=rulerEndX; int ey=rulerEndY; double length; //MapCoordinates cs=dmp.getMapCoordinates(); int xa = cs.unmapXnosnap(sx); int ya = cs.unmapYnosnap(sy); int xb = cs.unmapXnosnap(ex); int yb = cs.unmapYnosnap(ey); int x1; int y1; int x2; int y2; double x; double y; // Calculates the ruler length. length = Math.sqrt((double)(xa-xb)*(xa-xb)+(ya-yb)*(ya-yb)); g.drawLine(sx, sy, ex, ey); // A little bit of trigonometry :-) double alpha; if (sx==ex) { alpha = Math.PI/2.0+(ey-sy<0?0:Math.PI); } else { alpha = Math.atan((double)(ey-sy)/(double)(ex-sx)); } alpha += ex-sx>0?0:Math.PI; // Those magic numers are the lenghts of the tics (major and minor) double l = 5.0; if (cs.getXMagnitude()<1.0) { l=10; } else if(cs.getXMagnitude() > 5.0) { l=1; } else { l=5; } double ll = 0.0; double ld = 5.0; int m = 5; int j = 0; double dex = sx + length*Math.cos(alpha)*cs.getXMagnitude(); double dey = sy + length*Math.sin(alpha)*cs.getYMagnitude(); alpha += Math.PI/2.0; boolean debut=true; // Draw the ticks. for(double i=0; i<=length; i+=l) { if (j==m || debut) { j=0; ll=2*ld; debut=false; } else { ll=ld; } ++j; x = dex*i/length+(double)sx*(length-i)/length; y = dey*i/length+(double)sy*(length-i)/length; x1 = (int)(x - ll*Math.cos(alpha)); x2 = (int)(x + ll*Math.cos(alpha)); y1 = (int)(y - ll*Math.sin(alpha)); y2 = (int)(y + ll*Math.sin(alpha)); g.drawLine(x1, y1, x2, y2); } Font f=new Font(rulerFont,Font.PLAIN,10); g.setFont(f); String t1 = Globals.roundTo(length,2); // Remember that one FidoCadJ logical unit is 127 microns. String t2 = Globals.roundTo(length*.127,2)+" mm"; FontMetrics fm = g.getFontMetrics(f); // Draw the box at the end, with the measurement results. g.setColor(Color.white); g.fillRect(ex+10, ey, Math.max(fm.stringWidth(t1), fm.stringWidth(t2))+1, 24); g.setColor(rulerColor); g.drawRect(ex+9, ey-1, Math.max(fm.stringWidth(t1), fm.stringWidth(t2))+2, 25); g.setColor(textColor); g.drawString(t1, ex+10, ey+10); g.drawString(t2, ex+10, ey+20); } /** Define the coordinates of the starting point of the ruler. @param sx the x coordinate. @param sy the y coordinate. */ public void setRulerStart(int sx, int sy) { rulerStartX=sx; rulerStartY=sy; } /** Define the coordinates of the ending point of the ruler. @param sx the x coordinate. @param sy the y coordinate. */ public void setRulerEnd(int sx, int sy) { rulerEndX=sx; rulerEndY=sy; } /** Get the x coordinate of the starting point of the ruler. @return the x coordinate. */ public int getRulerStartX() { return rulerStartX; } /** Get the y coordinate of the starting point of the ruler. @return the y coordinate. */ public int getRulerStartY() { return rulerStartY; } }
5,998
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
MouseMoveClickHandler.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/circuit/MouseMoveClickHandler.java
package net.sourceforge.fidocadj.circuit; import java.awt.*; import java.awt.event.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.circuit.controllers.ElementsEdtActions; import net.sourceforge.fidocadj.circuit.controllers.ContinuosMoveActions; import net.sourceforge.fidocadj.circuit.controllers.EditorActions; import net.sourceforge.fidocadj.circuit.controllers.HandleActions; import net.sourceforge.fidocadj.timer.MyTimer; import net.sourceforge.fidocadj.geom.MapCoordinates; /** Handle the mouse click operations, as well as some dragging actions. <pre> cp 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 MouseMoveClickHandler implements MouseMotionListener, MouseListener { private final CircuitPanel cp; private final EditorActions edt; private final ContinuosMoveActions eea; private final HandleActions haa; // Record time for mouse down handle event in selection. private double record_c; // Record time for click up event in selection. private double record_d; /** Constructor. Create a MouseMoveClickHandler and associates it to the provided handler. @param p the CircuitPanel. */ public MouseMoveClickHandler(CircuitPanel p) { cp=p; edt=cp.getEditorActions(); eea=cp.getContinuosMoveActions(); haa=new HandleActions(cp.getDrawingModel(), edt, cp.getSelectionActions(), cp.getUndoActions()); record_c=record_d=1e100; } /** Called when the mouse is clicked inside the control 0.23.2: the Java click event is a bit too much restrictive. The mouse need to be hold still during the click. This is apparently a problem for a number of user. I have thus decided to use the mouse release event instead of the complete click. @param evt the MouseEvent to handle. */ @Override public void mouseClicked(MouseEvent evt) { cp.requestFocusInWindow(); } /** Handle the mouse movements when editing a graphic primitive. This procedure is important since it is used to show interactively to the user which element is being modified. @param evt the MouseEvent to handle. */ @Override public void mouseMoved(MouseEvent evt) { int xa=evt.getX(); int ya=evt.getY(); boolean toggle = getToggle(evt); if (eea.continuosMove(cp.getMapCoordinates(), xa, ya, toggle)) { cp.repaint(); } } /** Check if the "toggle" keyboard button is pressed during the mouse operation. Toggle may be Control or Meta, depending on the operating system. @param evt the MouseEvent. @return true if the toggle should be active. */ private boolean getToggle(MouseEvent evt) { if(Globals.useMetaForMultipleSelection) { return evt.isMetaDown(); } else { return evt.isControlDown(); } } /** Mouse interface: start of the dragging operations. @param evt the MouseEvent to handle */ @Override public void mousePressed(MouseEvent evt) { MyTimer mt = new MyTimer(); int px=evt.getX(); int py=evt.getY(); cp.getRuler().setActive(false); cp.getRuler().setRulerStart(px, py); cp.getRuler().setRulerEnd(px, py); boolean toggle = getToggle(evt); if(eea.actionSelected == ElementsEdtActions.SELECTION && (evt.getModifiers() & InputEvent.BUTTON3_MASK)==0 && !evt.isShiftDown()) { haa.dragHandleStart(px, py, edt.getSelectionTolerance(), toggle, cp.getMapCoordinates()); } else if(eea.actionSelected == ElementsEdtActions.SELECTION){ // Right click during selection cp.getRuler().setActive(true); } if(cp.isProfiling()) { double elapsed=mt.getElapsed(); if(elapsed<record_c) { record_c=elapsed; } System.out.println("MP: Time elapsed: "+elapsed+ "; record: "+record_c+" ms"); } } /** Dragging event with the mouse. @param evt the MouseEvent to handle */ @Override public void mouseDragged(MouseEvent evt) { MyTimer mt = new MyTimer(); int px=evt.getX(); int py=evt.getY(); // Handle the ruler. Basically, we just save the coordinates and // we launch a repaint which will be done as soon as possible. // No graphical elements are drawn outside a repaint. if((evt.getModifiers() & InputEvent.BUTTON3_MASK)!=0 || evt.isShiftDown()) { cp.getRuler().setRulerEnd(px, py); cp.repaint(); return; } haa.dragHandleDrag(cp, px, py, cp.getMapCoordinates(), (evt.getModifiers() & ActionEvent.CTRL_MASK)== ActionEvent.CTRL_MASK); // A little profiling if necessary. I noticed that time needed for // handling clicks is not negligible in large drawings, hence the // need of controlling it. if(cp.isProfiling()) { double elapsed=mt.getElapsed(); if(elapsed<record_d) { record_d=elapsed; } System.out.println("MD: Time elapsed: "+elapsed+ "; record: "+record_d+" ms"); } } /** Mouse release event. @param evt the MouseEvent to handle */ @Override public void mouseReleased(MouseEvent evt) { MyTimer mt = new MyTimer(); int px=evt.getX(); int py=evt.getY(); MapCoordinates cs=cp.getMapCoordinates(); boolean button3 = false; boolean toggle = getToggle(evt); // Key bindings are a little different with macOS. if(Globals.weAreOnAMac) { if(evt.getButton()==MouseEvent.BUTTON3) { button3=true; } else if(evt.getButton()==MouseEvent.BUTTON1 && evt.isControlDown()) { button3=true; } } else { button3 = (evt.getModifiers() & InputEvent.BUTTON3_MASK)== InputEvent.BUTTON3_MASK; } // If we are in the selection state, either we are ending the editing // of an element (and thus the dragging of a handle) or we are // making a click. if(eea.actionSelected==ElementsEdtActions.SELECTION) { if(cp.getRuler().getRulerStartX()!=px || cp.getRuler().getRulerStartY()!=py) // NOPMD { haa.dragHandleEnd(cp, px, py, toggle, cs); } else { cp.getRuler().setActive(false); cp.requestFocusInWindow(); eea.handleClick(cs,evt.getX(), evt.getY(), button3, toggle, evt.getClickCount() >= 2); } cp.repaint(); } else { cp.requestFocusInWindow(); if(eea.handleClick(cs,evt.getX(), evt.getY(), button3, toggle, evt.getClickCount() >= 2)) { cp.repaint(); } } // Having an idea of the release time is useful for the optimization // of the click event handling. The most time-consuming operation // which is done in this phase is finding the closest component to // the mouse pointer and eventually selecting it. if(cp.isProfiling()) { double elapsed=mt.getElapsed(); if(elapsed<record_d) { record_d=elapsed; } System.out.println("MR: Time elapsed: "+elapsed+ "; record: "+record_d+" ms"); } } /** The mouse pointer enters into the control. This method changes the cursor associated to it. @param evt the MouseEvent to handle */ @Override public void mouseEntered(MouseEvent evt) { selectCursor(); } /** Define the icon used for the mouse cursor, depending on the current editing action. */ public void selectCursor() { switch(eea.actionSelected) { case ElementsEdtActions.NONE: case ElementsEdtActions.ZOOM: case ElementsEdtActions.HAND: cp.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); break; case ElementsEdtActions.LINE: case ElementsEdtActions.TEXT: case ElementsEdtActions.BEZIER: case ElementsEdtActions.POLYGON: case ElementsEdtActions.COMPLEXCURVE: case ElementsEdtActions.ELLIPSE: case ElementsEdtActions.RECTANGLE: case ElementsEdtActions.CONNECTION: case ElementsEdtActions.PCB_LINE: case ElementsEdtActions.PCB_PAD: cp.setCursor(Cursor.getPredefinedCursor( Cursor.CROSSHAIR_CURSOR)); break; case ElementsEdtActions.SELECTION: default: cp.setCursor(Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR)); break; } } /** The mouse pointer has exited the control. This method changes the cursor associated and restores the default one. @param evt the MouseEvent to handle */ @Override public void mouseExited(MouseEvent evt) { cp.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); if(eea.successiveMove) { eea.successiveMove = false; cp.repaint(); } } }
10,479
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
HasChangedListener.java
/FileExtraction/Java_unseen/DarwinNE_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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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
DashCellRenderer.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/dialogs/DashCellRenderer.java
package net.sourceforge.fidocadj.dialogs; import java.awt.*; import javax.swing.*; /** The class ArrowCellRenderer is used in the arrow list. @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 DashCellRenderer implements ListCellRenderer { /** Method required for the ListCellRenderer interface; it draws a dash element in the cell and adds its event listeners. @param list the {@link JList} associated to the rendered. @param value the value used by the rendered. @param index the index in the list. @param isSelected true if the cell has been selected. @param cellHasFocus true if the cell has focus. @return the created {@link Component}. */ @Override public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { final DashInfo arrow=(DashInfo) value; return new CellDash(arrow, list, isSelected); } }
1,785
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
LibraryPanel.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/dialogs/LibraryPanel.java
package net.sourceforge.fidocadj.dialogs; import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*; import javax.swing.plaf.metal.*; import net.sourceforge.fidocadj.globals.Globals; import java.awt.*; import java.io.*; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; import java.util.*; /** * JFileChooser accessory panel for listing libraries 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 <a href=http://www.gnu.org/licenses/>http://www.gnu.org/licenses/</a>. Copyright 2014-2023 by Kohta Ozaki, Davide Bucci </pre> @author Kohta Ozaki, Davide Bucci */ public final class LibraryPanel extends JPanel implements PropertyChangeListener { final private static int PREFERRED_PANEL_WIDTH = 250; final private JFileChooser fc; final private LibraryListModel listModel; /** * Creates UI. * This LibraryPanel register as accessory panel to JFileChooser. * And adds as listener for receiving selection change event. * @param fc JFileChooser instance. */ public LibraryPanel(JFileChooser fc) { this.fc = fc; fc.addPropertyChangeListener(this); fc.setAccessory(this); listModel = new LibraryListModel(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { initGUI(); } } ); listModel.setDirectory(fc.getCurrentDirectory()); } /** 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(); } /** * Creates UI. */ private void initGUI() { JList<LibraryDesc> fileList; JScrollPane sp; setLayout(new BorderLayout()); setPreferredSize(new Dimension(PREFERRED_PANEL_WIDTH,1)); // If this class is run as a standalone program, the Globals.messages // resource handler might not be initizalized. In this case, // an english tag will do the job. if(Globals.messages==null) { add(BorderLayout.NORTH, new JLabel("Libraries in directory:")); } else { add(BorderLayout.NORTH,new JLabel( Globals.messages.getString("lib_in_dir"))); } fileList = new JList<LibraryDesc>(listModel); fileList.setCellRenderer(new ListCellRenderer<LibraryDesc>() { @Override public Component getListCellRendererComponent(JList<? extends LibraryPanel.LibraryDesc> list, LibraryPanel.LibraryDesc value, int index, boolean isSelected, boolean cellHasFocus) { LibraryDesc desc = (LibraryDesc) value; String libraryName; JPanel p; Icon icon = MetalIconFactory.getTreeFloppyDriveIcon(); Icon spaceIcon = new SpaceIcon(icon.getIconWidth(), icon.getIconHeight()); if (desc.libraryName == null) { libraryName = "---"; } else { libraryName = "(" + desc.libraryName + ")"; } p = new JPanel(); p.setBorder(new EmptyBorder(2,0,3,0)); p.setOpaque(false); p.setLayout(new BorderLayout()); p.add(BorderLayout.NORTH, new JLabel(desc.filename, icon, SwingConstants.LEFT)); p.add(BorderLayout.SOUTH, new JLabel(libraryName, spaceIcon, SwingConstants.LEFT)); return p; } }); sp = new JScrollPane(fileList); sp.setVerticalScrollBarPolicy( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); add(BorderLayout.CENTER, sp); // Disable focus. // The list is never selected. fileList.setFocusable(false); } @Override public void propertyChange(PropertyChangeEvent evt) { if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals( evt.getPropertyName())) { listModel.setDirectory(fc.getSelectedFile()); } if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals( evt.getPropertyName())) { listModel.setDirectory(fc.getCurrentDirectory()); } } /** For test method. Shows only JFileChooser with this LibraryPanel. @param args the input parameters on the command line. */ public static void main(String... args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFileChooser fc; fc = new JFileChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setPreferredSize(new Dimension(800,400)); new LibraryPanel(fc); fc.showOpenDialog(null); } }); } /** * ListModel to provide libraries list. * This model searches libraries in selected directory. * And provide library name and filename to JList component. */ public static class LibraryListModel implements ListModel<LibraryDesc> { final private java.util.List<ListDataListener> listeners; final private java.util.List<LibraryDesc> libraryList; private File currentDir=null; /** Constructs model. */ LibraryListModel() { listeners = new ArrayList<ListDataListener>(); libraryList = new ArrayList<LibraryDesc>(); } /** * Sets directory. * And updates libraries list in directory. * @param dir selected directory as File */ public void setDirectory(File dir) { currentDir = dir; clearList(); if (currentDir != null && currentDir.canRead() && currentDir.isDirectory()) { // Permission check refreshList(); } // DB -> KO check if it is correct. I removed a "}" fireChanged(); } private void refreshList() { File[] files=null; LibraryDesc desc=null; files = currentDir.listFiles(new FileFilter() { @Override public boolean accept(File f) { return f.isFile() && f.getName().toLowerCase(Locale.US). matches("^.*\\.fcl$"); } }); if(files==null) { return; } for (File f : files) { desc = new LibraryDesc(); desc.filename = f.getName(); desc.libraryName = getLibraryName(f); libraryList.add(desc); } // Sort list by filename. Collections.sort(libraryList, new Comparator<LibraryDesc>() { @Override public int compare(LibraryDesc ld1, LibraryDesc ld2) { // Sort with case sensitive. // This is usually made in UNIX file systems. // If case sensitive is not needed, use // String.compareToIgnoreCase return ld1.filename.compareTo(ld2.filename); } /*@Override public boolean equals(Object obj) { // DB. FindBugs complains that this methods always // returns "false". It considers it a quite high priority // issue to be solved. Is there any particular reason why // this must return false? // return false; return this == obj; }*/ }); } private void clearList() { libraryList.clear(); } private void fireChanged() { for (ListDataListener l : listeners) { l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, 0)); } } private String getLibraryName(File f) { // if there is a public api for reading library name direct, // rewrite this section. // maxReadLine = -1 : reads to EOF. // = num : reads to num line. int maxReadline = -1; int pt = 0; FileReader fr = null; BufferedReader br = null; String buf; String libraryName = null; try { fr = new FileReader(f); br = new BufferedReader(fr); while (true) { buf = br.readLine(); // check EOF if (buf == null) { break; } if (buf.matches("^\\[FIDOLIB .*\\]\\s*")) { buf = buf.trim(); libraryName = buf.substring(9, buf.length() - 1); break; } if (maxReadline != -1 && maxReadline <= pt) { break; } pt++; } // DB: it seems to me that catching an Exception is a // little bit too general. Which kind of reasonable // problems have we got to handle here? } catch (Exception e) { // return null for libraryName libraryName=null; } finally { try { if (br != null) { br.close(); } if (fr != null) { fr.close(); } // DB: it seems to me that catching an Exception is a // little bit too general. Which kind of reasonable // problems have we got to handle here? } catch (Exception e) { System.out.println("Problems while closing streams."); } } return libraryName; } @Override public void addListDataListener(ListDataListener l) { listeners.add(l); } @Override public void removeListDataListener(ListDataListener l) { listeners.remove(l); } @Override public int getSize() { return libraryList.size(); } @Override public LibraryDesc getElementAt(int index) { return libraryList.get(index); } } /** * Library description class. */ private static final class LibraryDesc { public String filename; public String libraryName; @Override public String toString() { return String.format("%s (%s)", filename, libraryName); } } /** * Dummy icon class for spacing. */ private static class SpaceIcon implements Icon { final private int width; final private int height; /** Constructor. Creates a dummy icon with the given size. */ SpaceIcon(int width, int height) { this.width = width; this.height = height; } @Override public int getIconHeight() { return height; } @Override public int getIconWidth() { return width; } @Override public void paintIcon(Component c, Graphics g, int x, int y) { // NOP } } }
12,879
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
DialogEditLayer.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/dialogs/DialogEditLayer.java
package net.sourceforge.fidocadj.dialogs; import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.graphic.swing.ColorSwing; import net.sourceforge.fidocadj.dialogs.mindimdialog.MinimumSizeDialog; /** The class DialogEditLayer allows to choose the style, visibility and description of the current layer. <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 DialogEditLayer extends MinimumSizeDialog { static final int ALPHA_MIN = 0; static final int ALPHA_MAX = 100; private final JColorChooser tcc; private final JCheckBox visibility; private final JTextField description; private final JSlider opacity; private boolean active; // true if the user selected ok private final LayerDesc ll; /** Standard constructor. @param parent the dialog parent @param l a LayerDesc containing the layer's attributes */ public DialogEditLayer (JFrame parent, LayerDesc l) { super(500, 450, parent, Globals.messages.getString("Layer_options")+ l.getDescription(), true); ll = l; addComponentListener(this); active=false; Container contentPane=getContentPane(); GridBagLayout bgl=new GridBagLayout(); contentPane.setLayout(bgl); GridBagConstraints constraints = DialogUtil.createConst(0,0,3,1,100,100, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(20,20,6,20)); ColorSwing c = (ColorSwing) l.getColor(); tcc = new JColorChooser(c.getColorSwing()); contentPane.add(tcc, constraints); JLabel descrLabel=new JLabel(Globals.messages.getString("Description")); constraints = DialogUtil.createConst(1,1,1,1,100,100, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0,20,0,0)); contentPane.add(descrLabel, constraints); description=new JTextField(); description.setText(l.getDescription()); constraints = DialogUtil.createConst(2,1,1,1,100,0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,120)); contentPane.add(description, constraints); JLabel opacityLbl=new JLabel(Globals.messages.getString("Opacity")); constraints = DialogUtil.createConst(1,3,1,1,100,0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(0,0,0,20)); contentPane.add(opacityLbl, constraints); opacity = new JSlider(JSlider.HORIZONTAL, ALPHA_MIN, ALPHA_MAX, Math.round(l.getAlpha()*100.0f)); //Turn on labels at major tick marks. opacity.setMajorTickSpacing(20); opacity.setMinorTickSpacing(1); opacity.setPaintTicks(true); opacity.setPaintLabels(true); constraints = DialogUtil.createConst(2,3,1,1,100,0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,0,0,120)); contentPane.add(opacity, constraints); visibility=new JCheckBox(Globals.messages.getString("IsVisible")); visibility.setSelected(l.getVisible()); constraints = DialogUtil.createConst(2,4,1,1,100,0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,0,20,120)); contentPane.add(visibility, constraints); JButton ok = new JButton(Globals.messages.getString("Ok_btn")); JButton cancel = new JButton(Globals.messages.getString("Cancel_btn")); // Put the OK and Cancel buttons and make them active. Box b=Box.createHorizontalBox(); b.add(Box.createHorizontalGlue()); ok.setPreferredSize(cancel.getPreferredSize()); if (Globals.okCancelWinOrder) { b.add(ok); b.add(Box.createHorizontalStrut(12)); b.add(cancel); } else { b.add(cancel); b.add(Box.createHorizontalStrut(12)); b.add(ok); } constraints = DialogUtil.createConst(0,5,3,1,100,0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,20,20,20)); contentPane.add(b, constraints); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { active=true; setVisible(false); } }); getRootPane().setDefaultButton(ok); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { setVisible(false); } }); // Here is an action in which the dialog is closed AbstractAction cancelAction = new AbstractAction () { @Override public void actionPerformed (ActionEvent e) { setVisible(false); } }; DialogUtil.addCancelEscape (this, cancelAction); pack(); DialogUtil.center(this); } /** 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(); } /** Get the layer description as specified in the layer edit dialog */ public void acceptLayer() { // It is important that here we use exactly the same layer which has // been specified at the beginning. In this way, every reference to // that layer will be modified. ll.setVisible(visibility.isSelected()); ll.setDescription(description.getText()); ll.setColor(new ColorSwing(tcc.getColor())); ll.setAlpha(opacity.getValue()/100.0f); ll.setModified(true); } /** Determine if the user selected the Ok button. @return true if the user has quit the dialog box with the Ok button. */ public boolean getActive() { return active; } }
7,303
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
EnterCircuitFrame.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/dialogs/EnterCircuitFrame.java
package net.sourceforge.fidocadj.dialogs; import java.awt.*; import javax.swing.*; import java.awt.event.*; import net.sourceforge.fidocadj.globals.Globals; /** EnterCircuitFrame.java 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 2007-2023 by Davide Bucci </pre> A dialog useful to past the FidoCadJ code. @author Davide Bucci */ public final class EnterCircuitFrame extends JDialog implements ComponentListener { private static final int MIN_WIDTH=400; private static final int MIN_HEIGHT=350; private final JTextArea textArea; /* The stringCircuit property gives the modified string if the user selected the Ok button. */ private String stringCircuit; /** Defines the string containing the FidoCadJ code. @param s the string */ public void setStringCircuit(String s) { stringCircuit = s; } /** Gets the string containing the FidoCadJ code. @return the string. */ public String getStringCircuit() { return stringCircuit; } /** Impose a minimum size for this dialog. @param e the component event received. */ @Override public void componentResized(ComponentEvent e) { int width = getWidth(); int height = getHeight(); boolean resize = false; if (width < MIN_WIDTH) { resize = true; width = MIN_WIDTH; } if (height < MIN_HEIGHT) { resize = true; height = MIN_HEIGHT; } if (resize) { setSize(width, height); } } /** Required for the implementation of the ComponentListener interface. @param e the component event which happened. */ @Override public void componentMoved(ComponentEvent e) { // Nothing to do } /** Required for the implementation of the ComponentListener interface. @param e the component event which happened. */ @Override public void componentShown(ComponentEvent e) { // Nothing to do } /** Required for the implementation of the ComponentListener interface. @param e the component event which happened. */ @Override public void componentHidden(ComponentEvent e) { // Nothing to do } /** The constructor. @param parent the parent frame @param circuit the circuit Fidocad code */ public EnterCircuitFrame (JFrame parent, String circuit) { super(parent, Globals.messages.getString("Enter_code"), true); addComponentListener(this); // Ensure that under MacOSX >= 10.5 Leopard, this dialog will appear // as a document modal sheet getRootPane().putClientProperty("apple.awt.documentModalSheet", Boolean.TRUE); GridBagConstraints constraints; Container contentPane=getContentPane(); contentPane.setLayout(new GridBagLayout()); DialogUtil.center(this,.5,.5); stringCircuit="[FIDOCAD]\n"+circuit; textArea=new JTextArea(stringCircuit,2,10); JScrollPane scrollPane=new JScrollPane(textArea); constraints = DialogUtil.createConst(0,0,1,1,100,100, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(20,20,12,20)); contentPane.add(scrollPane, constraints); JButton ok=new JButton(Globals.messages.getString("Ok_btn")); JButton cancel=new JButton(Globals.messages.getString("Cancel_btn")); // Put the OK and Cancel buttons and make them active. Box b=Box.createHorizontalBox(); b.add(Box.createHorizontalGlue()); ok.setPreferredSize(cancel.getPreferredSize()); if (Globals.okCancelWinOrder) { b.add(ok); b.add(Box.createHorizontalStrut(12)); b.add(cancel); } else { b.add(cancel); b.add(Box.createHorizontalStrut(12)); b.add(ok); } b.add(Box.createHorizontalStrut(20)); constraints = DialogUtil.createConst(0,1,1,1,100,0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0,0,20,0)); contentPane.add(b, constraints); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { setVisible(false); stringCircuit=textArea.getText(); } }); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { setVisible(false); } }); // Here is an action in which the dialog is closed AbstractAction cancelAction = new AbstractAction () { @Override public void actionPerformed (ActionEvent e) { setVisible(false); } }; DialogUtil.addCancelEscape (this, cancelAction); } }
5,736
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
ArrowCellRenderer.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/dialogs/ArrowCellRenderer.java
package net.sourceforge.fidocadj.dialogs; import java.awt.*; import javax.swing.*; /** The class ArrowCellRenderer is used in the arrow list. @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>. </pre> Copyright 2009-2023 by Davide Bucci */ public class ArrowCellRenderer implements ListCellRenderer { /** Method required for the ListCellRenderer interface; it draws a layer element in the cell and adds its event listeners. @param list the {@link JList} associated to the rendered. @param value the value used by the rendered. @param index the index in the list. @param isSelected true if the cell has been selected. @param cellHasFocus true if the cell has focus. @return the created {@link Component}. */ @Override public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { final ArrowInfo arrow=(ArrowInfo) value; return new CellArrow(arrow, list, isSelected); } }
1,789
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/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/src/net/sourceforge/fidocadj/dialogs/DialogParameters.java
package net.sourceforge.fidocadj.dialogs; import java.io.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; import net.sourceforge.fidocadj.dialogs.OSKeybPanel.KEYBMODES; import net.sourceforge.fidocadj.globals.Globals; import net.sourceforge.fidocadj.layers.LayerDesc; import net.sourceforge.fidocadj.graphic.PointG; import net.sourceforge.fidocadj.graphic.FontG; /** 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 automagically. <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 final class DialogParameters extends JDialog { //private int minWidth = 450; //private int minHeight = 350; private static final int MAX = 20; // Maximum number of user interface elements of the same type present // in the dialog window. private static final int MAX_ELEMENTS = 20; public boolean active; // true if the user selected Ok // Text box array and counter private final JTextField jtf[]; private int tc; // NOPMD this field can NOT be final! It is a counter. // Check box array and counter private final JCheckBox jcb[]; private int cc; // NOPMD this field can NOT be final! It is a counter. private final JComboBox jco[]; private int co; // NOPMD this field can NOT be final! It is a counter. private final java.util.List<ParameterDescription> v; OSKeybPanel keyb1; OSKeybPanel keyb2; JTabbedPane keyb = new JTabbedPane(); /** Programmatically build a dialog frame containing the appropriate elements, in order to let the user modify the characteristics of a graphic primitive. @param parent the parent frame useful for creating the dialog. @param vec a ParameterDescription array containing the value and the description of each parameter that should be edited by the user. @param strict true if a strict compatibility with FidoCAD is required @param layers a vector containing the layers */ // Here some legacy code makes use of generics. They are tested, so // there is no risk of an actual error, but Java issues a warning. @SuppressWarnings("unchecked") public DialogParameters(final JFrame parent, java.util.List<ParameterDescription> vec, boolean strict, java.util.List<LayerDesc> layers) { super(parent, Globals.messages.getString("Param_opt"), true); keyb1 = new OSKeybPanel(KEYBMODES.GREEK); keyb2 = new OSKeybPanel(KEYBMODES.MISC); JPanel hints = new JPanel(); JTextArea hintsL = new JTextArea( Globals.messages.getString("text_hints"),6,40); hintsL.setLineWrap(true); hintsL.setWrapStyleWord(true); hintsL.setEditable(false); hintsL.setOpaque(false); hints.add(hintsL); keyb1.setField(this); keyb2.setField(this); keyb.addTab(Globals.messages.getString("param_greek"), keyb1); keyb.addTab(Globals.messages.getString("param_misc"), keyb2); keyb.addTab(Globals.messages.getString("param_hints"), hints); keyb.setVisible(false); v = vec; // We create dynamically all the needed elements. // For this reason, we work on arrays of the potentially useful Swing // objects. jtf = new JTextField[MAX_ELEMENTS]; jcb = new JCheckBox[MAX_ELEMENTS]; jco = new JComboBox[MAX_ELEMENTS]; active = false; GridBagLayout bgl = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); Container contentPane = getContentPane(); contentPane.setLayout(bgl); boolean extStrict = strict; int top = 0; JLabel lab; tc = 0; cc = 0; co = 0; // We process all parameter passed. Depending on its type, a // corresponding interface element will be created. // A symmetrical operation is done when validating parameters. int ycount = 0; for (ParameterDescription pd : v) { // We do not need to store label objects, since we do not need // to retrieve data from them. lab = new JLabel(pd.description); constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 1; constraints.gridy = ycount; constraints.gridwidth = 1; constraints.gridheight = 1; // The first element needs a little bit more space at the top. if (ycount == 0) { top = 10; } else { top = 0; } // Here, we configure the grid layout. constraints.insets = new Insets(top, 20, 0, 6); constraints.fill = GridBagConstraints.VERTICAL; constraints.anchor = GridBagConstraints.EAST; lab.setEnabled(!(pd.isExtension && extStrict)); if (!(pd.parameter instanceof Boolean)) { contentPane.add(lab, constraints); } constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(top, 0, 0, 0); constraints.fill = GridBagConstraints.HORIZONTAL; // Now, depending on the type of parameter we create interface // elements and we populate the dialog. if (pd.parameter instanceof PointG) { jtf[tc] = new JTextField(10); jtf[tc].setText("" + ((PointG) pd.parameter).x); constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 2; constraints.gridy = ycount; constraints.gridwidth = 1; constraints.gridheight = 1; // Disable FidoCadJ extensions in the strict compatibility mode jtf[tc].setEnabled(!(pd.isExtension && extStrict)); contentPane.add(jtf[tc++], constraints); jtf[tc] = new JTextField(10); jtf[tc].setText("" + ((PointG) pd.parameter).y); constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 3; constraints.gridy = ycount; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets = new Insets(top, 6, 0, 20); constraints.fill = GridBagConstraints.HORIZONTAL; jtf[tc].setEnabled(!(pd.isExtension && extStrict)); contentPane.add(jtf[tc++], constraints); } else if (pd.parameter instanceof String) { jtf[tc] = new JTextField(24); jtf[tc].setText((String) pd.parameter); // 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) { jtf[tc].selectAll(); } constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 2; constraints.gridy = ycount; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets = new Insets(top, 0, 0, 20); constraints.fill = GridBagConstraints.HORIZONTAL; jtf[tc].setEnabled(!(pd.isExtension && extStrict)); contentPane.add(jtf[tc++], constraints); } else if (pd.parameter instanceof Boolean) { jcb[cc] = new JCheckBox(pd.description); jcb[cc].setSelected(((Boolean) pd.parameter).booleanValue()); constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 2; constraints.gridy = ycount; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets = new Insets(top, 0, 0, 20); constraints.fill = GridBagConstraints.HORIZONTAL; jcb[cc].setEnabled(!(pd.isExtension && extStrict)); contentPane.add(jcb[cc++], constraints); } else if (pd.parameter instanceof Integer) { jtf[tc] = new JTextField(24); jtf[tc].setText(((Integer) pd.parameter).toString()); constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 2; constraints.gridy = ycount; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets = new Insets(top, 0, 0, 20); constraints.fill = GridBagConstraints.HORIZONTAL; jtf[tc].setEnabled(!(pd.isExtension && extStrict)); contentPane.add(jtf[tc++], constraints); } else if (pd.parameter instanceof Float) { jtf[tc] = new JTextField(24); jtf[tc].setText(""+pd.parameter); constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 2; constraints.gridy = ycount; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets = new Insets(top, 0, 0, 20); constraints.fill = GridBagConstraints.HORIZONTAL; jtf[tc].setEnabled(!(pd.isExtension && extStrict)); contentPane.add(jtf[tc++], constraints); } else if (pd.parameter instanceof FontG) { GraphicsEnvironment gE; gE = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] s = gE.getAvailableFontFamilyNames(); jco[co] = new JComboBox(); for (int i = 0; i < s.length; ++i) { jco[co].addItem(s[i]); if (s[i].equals(((FontG) pd.parameter).getFamily())) { jco[co].setSelectedIndex(i); } } constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 2; constraints.gridy = ycount; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets = new Insets(top, 0, 0, 20); constraints.fill = GridBagConstraints.HORIZONTAL; jco[co].setEnabled(!(pd.isExtension && extStrict)); contentPane.add(jco[co++], constraints); } else if (pd.parameter instanceof LayerInfo) { jco[co] = new JComboBox(new Vector<LayerDesc>(layers)); jco[co].setSelectedIndex(((LayerInfo) pd.parameter).layer); jco[co].setRenderer(new LayerCellRenderer()); constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 2; constraints.gridy = ycount; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets = new Insets(top, 0, 0, 20); constraints.fill = GridBagConstraints.HORIZONTAL; jco[co].setEnabled(!(pd.isExtension && extStrict)); contentPane.add(jco[co++], constraints); } else if (pd.parameter instanceof ArrowInfo) { jco[co] = new JComboBox<ArrowInfo>(); jco[co].addItem(new ArrowInfo(0)); jco[co].addItem(new ArrowInfo(1)); jco[co].addItem(new ArrowInfo(2)); jco[co].addItem(new ArrowInfo(3)); jco[co].setSelectedIndex(((ArrowInfo) pd.parameter).style); jco[co].setRenderer(new ArrowCellRenderer()); constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 2; constraints.gridy = ycount; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets = new Insets(top, 0, 0, 20); constraints.fill = GridBagConstraints.HORIZONTAL; jco[co].setEnabled(!(pd.isExtension && extStrict)); contentPane.add(jco[co++], constraints); } else if (pd.parameter instanceof DashInfo) { jco[co] = new JComboBox<DashInfo>(); for (int k = 0; k < Globals.dashNumber; ++k) { jco[co].addItem(new DashInfo(k)); } jco[co].setSelectedIndex(((DashInfo) pd.parameter).style); jco[co].setRenderer(new DashCellRenderer()); constraints.weightx = 100; constraints.weighty = 100; constraints.gridx = 2; constraints.gridy = ycount; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets = new Insets(top, 0, 0, 20); constraints.fill = GridBagConstraints.HORIZONTAL; jco[co].setEnabled(!(pd.isExtension && extStrict)); contentPane.add(jco[co++], constraints); } ++ycount; if (ycount >= MAX) { break; } } // Put the OK and Cancel buttons and make them active. JButton ok = new JButton(Globals.messages.getString("Ok_btn")); JButton cancel = new JButton(Globals.messages.getString("Cancel_btn")); JButton keybd = new JButton("\u00B6\u2211\u221A");// phylum keybd.setFocusable(false); keybd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // If at this point, the keyboard is not visible, this means // that it will become visible in a while. It is better to // resize first and then show up the keyboard. /*if (keyb.isVisible()) { minWidth = 400; minHeight = 350; } else { minWidth = 400; minHeight = 500; }*/ keyb.setVisible(!keyb.isVisible()); pack(); } }); ++ycount; constraints.gridx = 0; constraints.gridy = ycount++; constraints.gridwidth = 4; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.EAST; constraints.insets = new Insets(6, 20, 20, 20); // Put the OK and Cancel buttons and make them active. Box b = Box.createHorizontalBox(); b.add(keybd); // phylum b.add(Box.createHorizontalGlue()); ok.setPreferredSize(cancel.getPreferredSize()); if (Globals.okCancelWinOrder) { b.add(ok); b.add(Box.createHorizontalStrut(12)); b.add(cancel); } else { b.add(cancel); b.add(Box.createHorizontalStrut(12)); b.add(ok); } contentPane.add(b, constraints); constraints.gridx = 0; constraints.gridy = ycount; constraints.gridwidth = 4; constraints.gridheight = 1; constraints.anchor = GridBagConstraints.EAST; constraints.insets = new Insets(6, 20, 20, 20); contentPane.add(keyb, constraints); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { try { int ycount=0; //ParameterDescription pd; tc = 0; cc = 0; co = 0; // Here we read all the contents of the interface and we // update the contents of the parameter description array. for (ParameterDescription pd: v) { ++ycount; if (ycount >= MAX) { break; } if (pd.parameter instanceof PointG) { ((PointG) pd.parameter).x = Integer .parseInt(jtf[tc++].getText()); ((PointG) pd.parameter).y = Integer .parseInt(jtf[tc++].getText()); } else if (pd.parameter instanceof String) { pd.parameter = jtf[tc++].getText(); } else if (pd.parameter instanceof Boolean) { pd.parameter = Boolean.valueOf( jcb[cc++].isSelected()); } else if (pd.parameter instanceof Integer) { pd.parameter = Integer.valueOf(Integer .parseInt(jtf[tc++].getText())); } else if (pd.parameter instanceof Float) { pd.parameter = Float.valueOf(Float .parseFloat(jtf[tc++].getText())); } else if (pd.parameter instanceof FontG) { pd.parameter = new FontG((String) jco[co++] .getSelectedItem()); } else if (pd.parameter instanceof LayerInfo) { pd.parameter = new LayerInfo(jco[co++] .getSelectedIndex()); } else if (pd.parameter instanceof ArrowInfo) { pd.parameter = new ArrowInfo(jco[co++] .getSelectedIndex()); } else if (pd.parameter instanceof DashInfo) { pd.parameter = new DashInfo(jco[co++] .getSelectedIndex()); } } } catch (NumberFormatException eE) { // Error detected. Probably, the user has entered an // invalid string when FidoCadJ was expecting a numerical // input. JOptionPane.showMessageDialog(parent, Globals.messages.getString("Format_invalid")+ " ("+eE.getMessage()+")", "", JOptionPane.INFORMATION_MESSAGE); return; } active = true; setVisible(false); keyb.setVisible(false); } }); // Here is an action in which the dialog is closed AbstractAction cancelAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { setVisible(false); keyb.setVisible(false); } }; cancel.addActionListener(cancelAction); DialogUtil.addCancelEscape(this, cancelAction); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { keyb.setVisible(false); } }); pack(); DialogUtil.center(this); getRootPane().setDefaultButton(ok); } /** 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(); } /** Get a ParameterDescription vector describing the characteristics modified by the user. @return a ParameterDescription vector describing each parameter. */ public java.util.List<ParameterDescription> getCharacteristics() { return v; } }
21,346
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z
OriginCircuitPanel.java
/FileExtraction/Java_unseen/DarwinNE_FidoCadJ/src/net/sourceforge/fidocadj/dialogs/OriginCircuitPanel.java
package net.sourceforge.fidocadj.dialogs; import net.sourceforge.fidocadj.circuit.CircuitPanel; import net.sourceforge.fidocadj.globals.Globals; import java.io.*; import java.awt.*; /** The class OriginCircuitPanel extends the CircuitPanel class by adding coordinate axis which can be moved. <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 Phylum2, Davide Bucci </pre> @author Phylum2, Davide Bucci */ public final class OriginCircuitPanel extends CircuitPanel { final float dash1[] = {2.0f}; final BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1.0f, dash1, 1.0f); // x and y coordinates of the origin in pixel. private int dx = 20; private int dy = 20; // x and y coordinates of the origin in logical units. // TODO: improve data encapsulation (these should be private). public int xl=5; public int yl=5; /** 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(); } /** Get the x coordinate of the origin in pixels. @return the x coordinate of the origin in pixel. */ public int getDx() { return dx; } /** Get the y coordinate of the origin in pixels. @return the y coordinate of the origin in pixel. */ public int getDy() { return dy; } /** Put the origin in the 10,10 logical coordinates. */ public void resetOrigin() { xl=getMapCoordinates().unmapXsnap(10); yl=getMapCoordinates().unmapYsnap(10); dx=getMapCoordinates().mapXi(xl,yl,false); dy=getMapCoordinates().mapYi(xl,yl,false); } /** Set the new x coordinate of the origin. @param dx the new x coordinates in pixels. */ public void setDx(int dx) { if (dx < 0 || dx>getWidth()) { return; } this.dx = dx; } /** Set the new y coordinate of the origin. @param dy the new y coordinates in pixels. */ public void setDy(int dy) { if (dy<0 || dy>getHeight()) { return; } this.dy = dy; } /** Constructor. @param isEditable true if the panel should be editable. */ public OriginCircuitPanel(boolean isEditable) { super(isEditable); } /** Show a red cross with dashed line and write "origin" near to the center. This should suggest to the user that it is worth clicking in the origin panel (some users reported they did not see the cross alone in a first instance). */ @Override public void paintComponent (Graphics g) { super.paintComponent(g); Color c = g.getColor(); Graphics2D g2 = (Graphics2D) g; g.setColor(Color.red); Stroke t=g2.getStroke(); g2.setStroke(dashed); // Show the origin of axes (red cross) g.drawLine(dx, 0, dx, getHeight()); // y g.drawLine(0, dy, getWidth(), dy); // x Font f=new Font("Helvetica",0,12); FontMetrics fm = g.getFontMetrics(f); int h = fm.getAscent(); int th = h+fm.getDescent(); g.drawString(Globals.messages.getString("Origin"), dx+5, dy+th+2); g.setColor(c); g2.setStroke(t); } }
4,477
Java
.java
DarwinNE/FidoCadJ
107
39
47
2015-07-26T02:26:30Z
2023-12-01T11:46:47Z