public String saveAsFile(boolean accessingAsFile) throws IOException { File file = new SikuliIDEFileChooser(SikuliIDE.getInstance(), accessingAsFile).save(); if (file == null) { return null; } String bundlePath = FileManager.slashify(file.getAbsolutePath(), false); if (!file.getAbsolutePath().endsWith(".sikuli")) { bundlePath += ".sikuli"; } if (FileManager.exists(bundlePath)) { int res = JOptionPane.showConfirmDialog( null, SikuliIDEI18N._I("msgFileExists", bundlePath), SikuliIDEI18N._I("dlgFileExists"), JOptionPane.YES_NO_OPTION); if (res != JOptionPane.YES_OPTION) { return null; } } else { FileManager.mkdir(bundlePath); } try { saveAsBundle(bundlePath, (SikuliIDE.getInstance().getCurrentFileTabTitle())); if (Settings.isMac()) { if (!Settings.handlesMacBundles) { makeBundle(bundlePath, accessingAsFile); } } } catch (IOException iOException) { } return getCurrentShortFilename(); }
private static boolean validateOldConfigDir( @Nullable File installationHome, @Nullable File oldConfigDir, @NotNull ConfigImportSettings settings) { if (oldConfigDir == null) { if (installationHome != null) { JOptionPane.showMessageDialog( JOptionPane.getRootFrame(), ApplicationBundle.message( "error.invalid.installation.home", installationHome.getAbsolutePath(), settings.getProductName(ThreeState.YES))); } return false; } if (!oldConfigDir.exists()) { JOptionPane.showMessageDialog( JOptionPane.getRootFrame(), ApplicationBundle.message("error.no.settings.path", oldConfigDir.getAbsolutePath()), ApplicationBundle.message("title.settings.import.failed"), JOptionPane.WARNING_MESSAGE); return false; } return true; }
public void loadFile(String filename) { filename = FileManager.slashify(filename, false); setSrcBundle(filename + "/"); File script = new File(filename); _editingFile = FileManager.getScriptFile(script, null, null); if (_editingFile != null) { editingType = _editingFile .getAbsolutePath() .substring(_editingFile.getAbsolutePath().lastIndexOf(".") + 1); initBeforeLoad(editingType); try { this.read( new BufferedReader(new InputStreamReader(new FileInputStream(_editingFile), "UTF8")), null); } catch (Exception ex) { _editingFile = null; } } if (_editingFile != null) { updateDocumentListeners(); setDirty(false); _srcBundleTemp = false; } else { _srcBundlePath = null; } }
/** * Locate the linux fonts based on the XML configuration file * * @param file The location of the XML file */ private static void locateLinuxFonts(File file) { if (!file.exists()) { System.err.println("Unable to open: " + file.getAbsolutePath()); return; } try { InputStream in = new FileInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); ByteArrayOutputStream temp = new ByteArrayOutputStream(); PrintStream pout = new PrintStream(temp); while (reader.ready()) { String line = reader.readLine(); if (line.indexOf("DOCTYPE") == -1) { pout.println(line); } } in = new ByteArrayInputStream(temp.toByteArray()); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(in); NodeList dirs = document.getElementsByTagName("dir"); for (int i = 0; i < dirs.getLength(); i++) { Element element = (Element) dirs.item(i); String dir = element.getFirstChild().getNodeValue(); if (dir.startsWith("~")) { dir = dir.substring(1); dir = userhome + dir; } addFontDirectory(new File(dir)); } NodeList includes = document.getElementsByTagName("include"); for (int i = 0; i < includes.getLength(); i++) { Element element = (Element) dirs.item(i); String inc = element.getFirstChild().getNodeValue(); if (inc.startsWith("~")) { inc = inc.substring(1); inc = userhome + inc; } locateLinuxFonts(new File(inc)); } } catch (Exception e) { e.printStackTrace(); System.err.println("Unable to process: " + file.getAbsolutePath()); } }
/** Returns false if Exception is thrown. */ private boolean setDirectory() { String pathStr = dirTF.getText().trim(); if (pathStr.equals("")) pathStr = System.getProperty("user.dir"); try { File dirPath = new File(pathStr); if (!dirPath.isDirectory()) { if (!dirPath.exists()) { if (recursiveCheckBox.isSelected()) throw new NotDirectoryException(dirPath.getAbsolutePath()); else throw new NotFileException(dirPath.getAbsolutePath()); } else { convertSet.setFile(dirPath); convertSet.setDestinationPath(dirPath.getParentFile()); } } else { // Set the descriptors setMatchingFileNames(); FlexFilter flexFilter = new FlexFilter(); flexFilter.addDescriptors(descriptors); flexFilter.setFilesOnly(!recursiveCheckBox.isSelected()); convertSet.setSourcePath(dirPath, flexFilter); convertSet.setDestinationPath(dirPath); } } catch (NotDirectoryException e1) { final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption1"); MessageFormat formatter; String info_msg; if (pathStr.equals("")) { info_msg = ResourceHandler.getMessage("notdirectory_dialog.info5"); } else { formatter = new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info0")); info_msg = formatter.format(new Object[] {pathStr}); } final String info = info_msg; JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE); return false; } catch (NotFileException e2) { final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption0"); MessageFormat formatter = new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info1")); final String info = formatter.format(new Object[] {pathStr}); JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE); return false; } return true; // no exception thrown }
String askForReadFilename() { int returnVal = sqlLoadChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = sqlLoadChooser.getSelectedFile(); System.out.println("Selected read file " + file.getAbsolutePath()); // return file.getName(); return file.getAbsolutePath(); } else { System.out.println("Open command cancelled by user."); } return null; }
private boolean _assignValues(File fle) { String strMethod = "_assignValues(fle)"; if (fle == null) { MySystem.s_printOutError(this, strMethod, "nil fle"); return false; } if (!fle.exists()) { MySystem.s_printOutWarning( this, strMethod, "! fle.exists(), fle.getAbsolutePath()=" + fle.getAbsolutePath()); String strBody = fle.getAbsolutePath(); strBody += ":\nDirectory not found."; OPAbstract.s_showDialogWarning(super._frmParent_, strBody); return true; } if (!fle.isDirectory()) // statement should never be reached!!! { MySystem.s_printOutWarning( this, strMethod, "! fle.isDirectory(), fle.getAbsolutePath()=" + fle.getAbsolutePath()); String strBody = fle.getAbsolutePath(); strBody += ":\n not a directory."; OPAbstract.s_showDialogWarning(super._frmParent_, strBody); return true; } if (super._tfdCurSelection_ == null) { MySystem.s_printOutError(this, strMethod, "nil super._tfdCurSelection_"); return false; } super._tfdCurSelection_.setText(fle.getAbsolutePath()); super._setSelectedValue_(true); if (!_enableButtonsSelectionDone_()) { MySystem.s_printOutError(this, strMethod, "failed"); return false; } // -- // ending return true; }
private void writeSrcFile() throws IOException { Debug.log(3, "IDE: writeSrcFile: " + _editingFile.getName()); writeFile(_editingFile.getAbsolutePath()); if (PreferencesUser.getInstance().getAtSaveMakeHTML()) { convertSrcToHtml(getSrcBundle()); } else { String snameDir = new File(_editingFile.getAbsolutePath()).getParentFile().getName(); String sname = snameDir.replace(".sikuli", "") + ".html"; (new File(snameDir, sname)).delete(); } if (PreferencesUser.getInstance().getAtSaveCleanBundle()) { cleanBundle(getSrcBundle()); } setDirty(false); }
private void updateLinuxServiceInstaller() { try { File dir = new File(directory, "CTP"); if (suppressFirstPathElement) dir = dir.getParentFile(); Properties props = new Properties(); String ctpHome = dir.getAbsolutePath(); cp.appendln(Color.black, "...CTP_HOME: " + ctpHome); ctpHome = ctpHome.replaceAll("\\\\", "\\\\\\\\"); props.put("CTP_HOME", ctpHome); File javaHome = new File(System.getProperty("java.home")); String javaBin = (new File(javaHome, "bin")).getAbsolutePath(); cp.appendln(Color.black, "...JAVA_BIN: " + javaBin); javaBin = javaBin.replaceAll("\\\\", "\\\\\\\\"); props.put("JAVA_BIN", javaBin); File linux = new File(dir, "linux"); File install = new File(linux, "ctpService-ubuntu.sh"); cp.appendln(Color.black, "Linux service installer:"); cp.appendln(Color.black, "...file: " + install.getAbsolutePath()); String bat = getFileText(install); bat = replace(bat, props); // do the substitutions bat = bat.replace("\r", ""); setFileText(install, bat); // If this is an ISN installation, put the script in the correct place. String osName = System.getProperty("os.name").toLowerCase(); if (programName.equals("ISN") && !osName.contains("windows")) { install = new File(linux, "ctpService-red.sh"); cp.appendln(Color.black, "ISN service installer:"); cp.appendln(Color.black, "...file: " + install.getAbsolutePath()); bat = getFileText(install); bat = replace(bat, props); // do the substitutions bat = bat.replace("\r", ""); File initDir = new File("/etc/init.d"); File initFile = new File(initDir, "ctpService"); if (initDir.exists()) { setOwnership(initDir, "edge", "edge"); setFileText(initFile, bat); initFile.setReadable(true, false); // everybody can read //Java 1.6 initFile.setWritable(true); // only the owner can write //Java 1.6 initFile.setExecutable(true, false); // everybody can execute //Java 1.6 } } } catch (Exception ex) { ex.printStackTrace(); System.err.println("Unable to update the Linux service ctpService.sh file"); } }
private void saveSrc() { fileChooser.resetChoosableFileFilters(); fileChooser.addChoosableFileFilter(asmFilter); fileChooser.setFileFilter(asmFilter); if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) { try { File file = fileChooser.getSelectedFile(); if (fileChooser.getFileFilter() == asmFilter && !asmFilter.accept(file)) { file = new File(file.getAbsolutePath() + asmFilter.getExtensions()[0]); } if (file.exists()) { if (JOptionPane.showConfirmDialog( frame, "File exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; } } PrintStream output = new PrintStream(file); output.print(sourceTextarea.getText()); output.close(); } catch (IOException e1) { JOptionPane.showMessageDialog( frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } }
private void saveBin() { fileChooser.resetChoosableFileFilters(); fileChooser.addChoosableFileFilter(binFilter); fileChooser.setFileFilter(binFilter); if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) { try { File file = fileChooser.getSelectedFile(); if (fileChooser.getFileFilter() == binFilter && !binFilter.accept(file)) { file = new File(file.getAbsolutePath() + binFilter.getExtensions()[0]); } if (file.exists()) { if (JOptionPane.showConfirmDialog( frame, "File exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; } } FileOutputStream output = new FileOutputStream(file); for (char i : binary) { output.write(i & 0xff); output.write((i >> 8) & 0xff); } output.close(); } catch (IOException e1) { JOptionPane.showMessageDialog( frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } } }
private boolean _assignValues(File fle) { String strMethod = "_assignValues(fle)"; if (fle == null) { MySystem.s_printOutError(this, strMethod, "nil fle"); return false; } // -- // allow overwriting // -- if (super._tfdCurSelection_ == null) { MySystem.s_printOutError(this, strMethod, "nil super._tfdCurSelection_"); return false; } super._tfdCurSelection_.setText(fle.getAbsolutePath()); super._setSelectedValue_(true); if (super._btnClearSelection_ == null) { MySystem.s_printOutError(this, strMethod, "nil super._btnClearSelection_"); return false; } super._btnClearSelection_.setEnabled(true); // -- // ending return true; }
private void changeDirectory(File dir) { JFileChooser fc = getFileChooser(); // Traverse shortcuts on Windows if (dir != null && FilePane.usesShellFolder(fc)) { try { ShellFolder shellFolder = ShellFolder.getShellFolder(dir); if (shellFolder.isLink()) { File linkedTo = shellFolder.getLinkLocation(); // If linkedTo is null we try to use dir if (linkedTo != null) { if (fc.isTraversable(linkedTo)) { dir = linkedTo; } else { return; } } else { dir = shellFolder; } } } catch (FileNotFoundException ex) { return; } } fc.setCurrentDirectory(dir); if (fc.getFileSelectionMode() == JFileChooser.FILES_AND_DIRECTORIES && fc.getFileSystemView().isFileSystem(dir)) { setFileName(dir.getAbsolutePath()); } }
public void totalExport() { File expf = new File("export"); if (expf.exists()) rmrf(expf); expf.mkdirs(); for (int sto = 0; sto < storeLocs.size(); sto++) { try { String sl = storeLocs.get(sto).getAbsolutePath().replaceAll("/", "-").replaceAll("\\\\", "-"); File estore = new File(expf, sl); estore.mkdir(); File log = new File(estore, LIBRARY_NAME); PrintWriter pw = new PrintWriter(log); for (int i = 0; i < store.getRowCount(); i++) if (store.curStore(i) == sto) { File enc = store.locate(i); File dec = sec.prepareMainFile(enc, estore, false); pw.println(dec.getName()); pw.println(store.getValueAt(i, Storage.COL_DATE)); pw.println(store.getValueAt(i, Storage.COL_TAGS)); synchronized (jobs) { jobs.addLast(expJob(enc, dec)); } } pw.close(); } catch (IOException exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frm, "Exporting Failed"); return; } } JOptionPane.showMessageDialog(frm, "Exporting to:\n " + expf.getAbsolutePath()); }
/** * Prepare delete files handler. * * @param project the project * @param root a vcs root * @param files a files to commit * @param message a message file to use * @param nextCommitAuthor a author for the next commit * @param nextCommitAmend true, if the commit should be amended * @param nextCommitAuthorDate Author date timestamp to override the date of the commit or null if * this overriding is not needed. * @return a simple handler that does the task * @throws VcsException in case of git problem */ private static void commit( Project project, VirtualFile root, Collection<FilePath> files, File message, final String nextCommitAuthor, boolean nextCommitAmend, Date nextCommitAuthorDate) throws VcsException { boolean amend = nextCommitAmend; for (List<String> paths : VcsFileUtil.chunkPaths(root, files)) { GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT); handler.setStdoutSuppressed(false); if (amend) { handler.addParameters("--amend"); } else { amend = true; } handler.addParameters("--only", "-F", message.getAbsolutePath()); if (nextCommitAuthor != null) { handler.addParameters("--author=" + nextCommitAuthor); } if (nextCommitAuthorDate != null) { handler.addParameters("--date", COMMIT_DATE_FORMAT.format(nextCommitAuthorDate)); } handler.endOptions(); handler.addParameters(paths); handler.run(); } if (!project.isDisposed()) { GitRepositoryManager manager = GitUtil.getRepositoryManager(project); manager.updateRepository(root); } }
public void secureDelete() { int rw = tblItems.getSelectedRow(); if (rw == -1) { JOptionPane.showMessageDialog(frm, "No item selected", "Error", JOptionPane.ERROR_MESSAGE); return; } int idx = tblItems.convertRowIndexToModel(rw); if (JOptionPane.showConfirmDialog( frm, "Delete " + store.plainName(idx) + "?", "Confirm Delete", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return; File del = store.delete(idx); store.fireTableDataChanged(); if (del != null) { if (del.delete()) { // successful needsSave = true; } else { System.err.println("Delete " + del.getAbsolutePath() + " failed"); } } updateStatus(); }
public GraphicSet importSetFromFile(File inputFile, List<String> warnings) throws ImportException { Writer out = null; try { // Get a DOMImplementation DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document Document document = domImpl.createDocument(null, "svg", null); // Create an instance of the SVG Generator final SVGGraphics2D svgGenerator = new SVGGraphics2D(document); svgGenerator.setTransform(new AffineTransform()); // Open input file PSInputFile in = new PSInputFile(inputFile.getAbsolutePath()); Rectangle2D bb = this.getBoundingBox(inputFile); svgGenerator.setTransform(AffineTransform.getTranslateInstance(-bb.getX(), -bb.getY())); Dimension d = new Dimension((int) bb.getWidth(), (int) bb.getHeight()); // Create processor and associate to input and output file Processor processor = new Processor(svgGenerator, d, false); processor.setData(in); // Process processor.process(); File tmp = File.createTempFile("temp", "svg"); tmp.deleteOnExit(); svgGenerator.stream(new FileWriter(tmp)); GraphicSet result = new SVGImporter().importSetFromFile(tmp, warnings); // Assume the EPS has been created with 72DPI (from Inkscape) double px2mm = Util.inch2mm(1d / 72d); result.setBasicTransform(AffineTransform.getScaleInstance(px2mm, px2mm)); return result; } catch (Exception ex) { Logger.getLogger(EPSImporter.class.getName()).log(Level.SEVERE, null, ex); throw new ImportException(ex); } }
private static void validateXMLWithURL(File nmlFile, String schemaUrl) { try { Source schemaFileSource = new StreamSource(schemaUrl); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(schemaFileSource); Validator validator = schema.newValidator(); Source xmlFileSource = new StreamSource(nmlFile); validator.validate(xmlFileSource); System.out.println( "**** File: " + nmlFile + " is VALID according to " + schemaUrl + "!!! ****"); } catch (Exception ex) { System.err.println( "Problem validating xml file: " + nmlFile.getAbsolutePath() + " according to " + schemaUrl + "!!!"); ex.printStackTrace(); System.exit(1); } }
/** * Opens a project. * * @param directory Where the project is stored. * @return the BProject that describes the newly opened project or null if it cannot be opened. */ public final BProject openProject(File directory) { if (!myWrapper.isValid()) throw new ExtensionUnloadedException(); // Yes somebody may just call it with null, for fun.. if (directory == null) return null; Project openProj = Project.openProject(directory.getAbsolutePath(), null); if (openProj == null) return null; // a hack, since bluej does not handle "opening" of projects correctly. // this code should really be into openProject or it should not be possible to open // a project is the initial package name is not there. Package pkg = openProj.getCachedPackage(openProj.getInitialPackageName()); if (pkg == null) return null; // I make a new identifier out of this Identifier aProject = new Identifier(openProj, pkg); // This will make the frame if not already there. should not be needed... try { aProject.getPackageFrame(); } catch (ExtensionException exc) { } // Note: the previous Identifier is not used here. return openProj.getBProject(); }
public String getSrcBundle() { if (_srcBundlePath == null) { File tmp = FileManager.createTempDir(); setSrcBundle(FileManager.slashify(tmp.getAbsolutePath(), true)); _srcBundleTemp = true; } return _srcBundlePath; }
public void save(String s, File f) { try { int saveNumber = 1; File file = new File(f.getAbsolutePath() + "/save.adv"); while (file.exists()) { file = new File(f.getAbsolutePath() + "/save" + saveNumber + ".adv"); saveNumber++; } file.createNewFile(); FileWriter fWriter = new FileWriter(file.getAbsoluteFile()); BufferedWriter bWriter = new BufferedWriter(fWriter); bWriter.write(s); bWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
/** * The FileEvent listener. * * @param event the event. */ public void fileEventOccurred(FileEvent event) { File file = event.getFile(); if (file != null) { String dirPath; if (file.isDirectory()) dirPath = file.getAbsolutePath(); else dirPath = file.getParentFile().getAbsolutePath(); properties.setProperty("directory", dirPath); } else properties.remove("directory"); }
public String exportAsZip() throws IOException, FileNotFoundException { File file = new SikuliIDEFileChooser(SikuliIDE.getInstance()).export(); if (file == null) { return null; } String zipPath = file.getAbsolutePath(); String srcName = file.getName(); if (!file.getAbsolutePath().endsWith(".skl")) { zipPath += ".skl"; } else { srcName = srcName.substring(0, srcName.lastIndexOf('.')); } writeFile(getSrcBundle() + srcName + ".py"); FileManager.zip(getSrcBundle(), zipPath); Debug.log(2, "export to executable file: " + zipPath); return zipPath; }
/** * Creates a new BlueJ project. * * @param directory where you want the project be placed, it must be writable. * @param projectType the type of project, such as ME or SE. * @return the newly created BProject if successful, null otherwise. */ public BProject newProject(File directory, int projectType) { if (!myWrapper.isValid()) throw new ExtensionUnloadedException(); String pathString = directory.getAbsolutePath(); if (!pathString.endsWith(File.separator)) pathString += File.separator; if (!Project.createNewProject(pathString, projectType == ME_PROJECT)) return null; return openProject(directory); }
public boolean edtImport(File fi, String date, String tags) { if (!fi.exists()) { System.err.println("import: file " + fi.getAbsolutePath() + " doesnt exist"); return false; } String pname = fi.getName(); if (store.containsEntry(pname)) { System.err.println("import: already have a file named " + pname); return false; } long size = fi.length() / KILOBYTE; File save = sec.encryptMainFile(fi, storeLocs.get(0), true); if (save == null) { System.err.println("import: Encryption failure"); return false; } if (checkImports) { boolean success = true; File checkfi = new File(idx + ".check"); File checkOut = sec.encryptSpecialFile(save, checkfi, false); if (checkOut == null) success = false; else { String fiHash = sec.digest(fi); String outHash = sec.digest(checkOut); if (fiHash == null || outHash == null || fiHash.length() < 1 || !fiHash.equals(outHash)) success = false; } checkfi.delete(); if (!success) { save.delete(); if (JOptionPane.showConfirmDialog( frm, "Confirming " + fi.getName() + "failed\n\n - Would you like to re-import the file?", "Import failed", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { String j = impJob(fi, date, tags); synchronized (jobs) { if (priorityExport) jobs.addLast(j); else jobs.addFirst(j); } } return false; } } if (!fi.delete()) { System.err.println("import: Couldnt delete old file - continuing"); } store.add(save.getName(), pname, date, size, tags, 0); needsSave = true; return true; }
private void saveDataToFile(File file) { try { PrintStream out = new PrintStream(new FileOutputStream(file)); // Print header line out.print("Time"); for (Sequence seq : seqs) { out.print("," + seq.name); } out.println(); // Print data lines if (seqs.size() > 0 && seqs.get(0).size > 0) { for (int i = 0; i < seqs.get(0).size; i++) { double excelTime = toExcelTime(times.time(i)); out.print(String.format(Locale.ENGLISH, "%.6f", excelTime)); for (Sequence seq : seqs) { out.print("," + getFormattedValue(seq.value(i), false)); } out.println(); } } out.close(); JOptionPane.showMessageDialog( this, Resources.format( Messages.FILE_CHOOSER_SAVED_FILE, file.getAbsolutePath(), file.length())); } catch (IOException ex) { String msg = ex.getLocalizedMessage(); String path = file.getAbsolutePath(); if (msg.startsWith(path)) { msg = msg.substring(path.length()).trim(); } JOptionPane.showMessageDialog( this, Resources.format(Messages.FILE_CHOOSER_SAVE_FAILED_MESSAGE, path, msg), Messages.FILE_CHOOSER_SAVE_FAILED_TITLE, JOptionPane.ERROR_MESSAGE); } }
public static String getGarbageDirectory() { final File dir = new File(Configuration.Paths.getScriptCacheDirectory(), ".java"); if (!dir.exists()) { dir.mkdirs(); } String path = dir.getAbsolutePath(); try { path = URLDecoder.decode(path, "UTF-8"); } catch (final UnsupportedEncodingException ignored) { } return path; }
@Override public void actionPerformed(ActionEvent e) { if (fc == null) { fc = new IDEFileChooser(); fc.setFileView(new IDEFileView()); fc.setAcceptAllFileFilterUsed(false); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setMultiSelectionEnabled(false); fc.setDialogTitle( messagesBundle.getString("ImageViewerPanelSaveAction.Choose_filename_to_save_4")); //$NON-NLS-1$ // prepare file filters IIORegistry theRegistry = IIORegistry.getDefaultInstance(); Iterator it = theRegistry.getServiceProviders(ImageWriterSpi.class, false); while (it.hasNext()) { ImageWriterSpi writer = (ImageWriterSpi) it.next(); if ((imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_ARGB_PRE) && "JPEG".equals(writer.getFormatNames()[0].toUpperCase())) continue; ImageWriterSpiFileFilter ff = new ImageWriterSpiFileFilter(writer); fc.addChoosableFileFilter(ff); } } if (fc.showSaveDialog(viewerPanel) == JFileChooser.APPROVE_OPTION) { File selectedFile = fc.getSelectedFile(); if (selectedFile != null) { String fileName = selectedFile.getAbsolutePath(); ImageWriterSpiFileFilter ff = (ImageWriterSpiFileFilter) fc.getFileFilter(); if (!ff.hasCorrectSuffix(fileName)) fileName = ff.addSuffix(fileName); selectedFile = new File(fileName); if (selectedFile.exists()) { String message = MessageFormat.format( messagesBundle.getString("ImageViewerPanelSaveAction.Overwrite_question_5"), //$NON-NLS-1$ fileName); if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog( viewerPanel, message, messagesBundle.getString("ImageViewerPanelSaveAction.Warning_6"), //$NON-NLS-1$ JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE)) return; } writeToFile(selectedFile, ff); } } }
public GalaxyViewer(Settings settings, boolean animatorFrame) throws Exception { super("Stars GalaxyViewer"); this.settings = settings; this.animatorFrame = animatorFrame; if (settings.gameName.equals("")) throw new Exception("GameName not defined in settings."); setDefaultCloseOperation(EXIT_ON_CLOSE); File dir = new File(settings.directory); File map = new File(dir, settings.getGameName() + ".MAP"); if (map.exists() == false) { File f = new File(dir.getParentFile(), settings.getGameName() + ".MAP"); if (f.exists()) map = f; else { String error = "Could not find " + map.getAbsolutePath() + "\n"; error += "Export this file from Stars! (Only needs to be done one time pr game)"; throw new Exception(error); } } Vector<File> mFiles = new Vector<File>(); Vector<File> hFiles = new Vector<File>(); for (File f : dir.listFiles()) { if (f.getName().toUpperCase().endsWith("MAP")) continue; if (f.getName().toUpperCase().endsWith("HST")) continue; if (f.getName().toUpperCase().startsWith(settings.getGameName() + ".M")) mFiles.addElement(f); else if (f.getName().toUpperCase().startsWith(settings.getGameName() + ".H")) hFiles.addElement(f); } if (mFiles.size() == 0) throw new Exception("No M-files found matching game name."); if (hFiles.size() == 0) throw new Exception("No H-files found matching game name."); parseMapFile(map); Vector<File> files = new Vector<File>(); files.addAll(mFiles); files.addAll(hFiles); p = new Parser(files); calculateColors(); // UI: JPanel cp = (JPanel) getContentPane(); cp.setLayout(new BorderLayout()); cp.add(universe, BorderLayout.CENTER); JPanel south = createPanel(0, hw, new JLabel("Search: "), search, names, zoom, colorize); search.setPreferredSize(new Dimension(100, -1)); cp.add(south, BorderLayout.SOUTH); hw.addActionListener(this); names.addActionListener(this); zoom.addChangeListener(this); search.addKeyListener(this); colorize.addActionListener(this); setSize(800, 600); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation((screen.width - getWidth()) / 2, (screen.height - getHeight()) / 2); setVisible(animatorFrame == false); if (animatorFrame) names.setSelected(false); }
/* * This function just finds and loads the file */ private boolean loadFile() { JFileChooser fc = new JFileChooser(); fc.setDialogTitle("Load File"); // Choose only files, not directories fc.setFileSelectionMode(JFileChooser.FILES_ONLY); // Start in current directory fc.setCurrentDirectory(new File(".")); // Set filter for Java source files. fc.setFileFilter(fJavaFilter); // Now open chooser int result = fc.showOpenDialog(this); if (result == JFileChooser.CANCEL_OPTION) { // return true; } else if (result == JFileChooser.APPROVE_OPTION) { fFile = fc.getSelectedFile(); String textFile = fFile.toString(); if (fileNo.equalsIgnoreCase("LOAD1")) { UpLoadFile.filePath1.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD2")) { UpLoadFile.filePath2.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD3")) { VisualizationInput.originalFilePath.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD4")) { VisualizationInput.DWDVecFilePath.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD5")) { VisualizationInput.DWDOutputFilePath.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD6")) { UpLoadMAGEMLFile.filePath1.setText(textFile); } else if (fileNo.equalsIgnoreCase("LOAD7")) { UpLoadMAGEMLFile.filePath2.setText(textFile); } // Get the absolute path for the file being opened filePath = fFile.getAbsolutePath(); if (filePath == null) { // fTextField.setText (filePath); return false; } } else { return false; } return true; } /*End of loadFile*/