Search in sources :

Example 1 with VCFileChooser

use of org.vcell.util.gui.VCFileChooser in project vcell by virtualcell.

the class PDEDataViewer method makeSurfaceMovie.

private void makeSurfaceMovie(final SurfaceCanvas surfaceCanvas, final int varTotalNumIndices, final String movieDataVarName, final DisplayAdapterService movieDAS, final VCDataIdentifier movieVCDataIdentifier) {
    final SurfaceMovieSettingsPanel smsp = new SurfaceMovieSettingsPanel();
    final double[] timePoints = getPdeDataContext().getTimePoints();
    final int surfaceWidth = surfaceCanvas.getWidth();
    final int surfaceHeight = surfaceCanvas.getHeight();
    smsp.init(surfaceWidth, surfaceHeight, timePoints);
    while (true) {
        if (PopupGenerator.showComponentOKCancelDialog(this, smsp, "Movie Settings for var " + movieDataVarName) != JOptionPane.OK_OPTION) {
            return;
        }
        long movieSize = (smsp.getTotalFrames() * surfaceWidth * surfaceHeight * 3);
        // raw data size;
        long rawDataSize = (smsp.getTotalFrames() * varTotalNumIndices * 8);
        if (movieSize + rawDataSize > 50000000) {
            final String YES_RESULT = "Yes";
            String result = PopupGenerator.showWarningDialog(this, "Movie processing will require at least " + (movieSize + rawDataSize) / 1000000 + " mega-bytes of memory.\nMovie size will be " + (movieSize >= 1000000 ? movieSize / 1000000 + " mega-bytes." : movieSize / 1000.0 + " kilo-bytes.") + " Continue?", new String[] { YES_RESULT, "No" }, YES_RESULT);
            if (result != null && result.equals(YES_RESULT)) {
                break;
            }
        } else {
            break;
        }
    }
    final int beginTimeIndex = smsp.getBeginTimeIndex();
    final int endTimeIndex = smsp.getEndTimeIndex();
    final int step = smsp.getSkipParameter() + 1;
    final String[] varNames = new String[] { movieDataVarName };
    int[] allIndices = new int[varTotalNumIndices];
    for (int i = 0; i < allIndices.length; i++) {
        allIndices[i] = i;
    }
    final TimeSeriesJobSpec timeSeriesJobSpec = new TimeSeriesJobSpec(varNames, new int[][] { allIndices }, null, timePoints[beginTimeIndex], step, timePoints[endTimeIndex], VCDataJobID.createVCDataJobID(getDataViewerManager().getUser(), true));
    Hashtable<String, Object> hash = new Hashtable<String, Object>();
    hash.put(StringKey_timeSeriesJobSpec, timeSeriesJobSpec);
    AsynchClientTask task1 = new TimeSeriesDataRetrievalTask("Retrieving data for variable '" + movieDataVarName + "'", PDEDataViewer.this, getPdeDataContext());
    AsynchClientTask task2 = new AsynchClientTask("select a file", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            VCFileChooser fileChooser = new VCFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_MOV);
            // Set the default file filter...
            fileChooser.setFileFilter(FileFilters.FILE_FILTER_MOV);
            // remove all selector
            fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
            fileChooser.setDialogTitle("Saving surface movie");
            File selectedFile = null;
            while (true) {
                if (fileChooser.showSaveDialog(PDEDataViewer.this) != JFileChooser.APPROVE_OPTION) {
                    return;
                }
                selectedFile = fileChooser.getSelectedFile();
                if (!selectedFile.getName().endsWith(".mov")) {
                    selectedFile = new File(selectedFile.getAbsolutePath() + ".mov");
                }
                if (selectedFile.exists()) {
                    final String YES_RESULT = "Yes";
                    String result = PopupGenerator.showWarningDialog(PDEDataViewer.this, "Overwrite exisitng file:\n" + selectedFile.getAbsolutePath() + "?", new String[] { YES_RESULT, "No" }, YES_RESULT);
                    if (result != null && result.equals(YES_RESULT)) {
                        break;
                    }
                } else {
                    break;
                }
            }
            hashTable.put("selectedFile", selectedFile);
        }
    };
    AsynchClientTask task3 = new AsynchClientTask("create movie", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            File selectedFile = (File) hashTable.get("selectedFile");
            if (selectedFile == null) {
                return;
            }
            TSJobResultsNoStats tsJobResultsNoStats = (TSJobResultsNoStats) hashTable.get(StringKey_timeSeriesJobResults);
            double[][] timeSeries = tsJobResultsNoStats.getTimesAndValuesForVariable(movieDataVarName);
            int[] singleFrame = new int[surfaceWidth * surfaceHeight];
            BufferedImage bufferedImage = new BufferedImage(surfaceWidth, surfaceHeight, BufferedImage.TYPE_3BYTE_BGR);
            Graphics2D g2D = bufferedImage.createGraphics();
            VideoMediaChunk[] chunks = new VideoMediaChunk[tsJobResultsNoStats.getTimes().length];
            VideoMediaSample sample;
            int sampleDuration = 0;
            int timeScale = smsp.getFramesPerSecond();
            int bitsPerPixel = 32;
            DisplayAdapterService das = new DisplayAdapterService(movieDAS);
            int[][] origSurfacesColors = surfaceCanvas.getSurfacesColors();
            DataInfoProvider dataInfoProvider = getPDEDataContextPanel1().getDataInfoProvider();
            FileDataContainerManager fileDataContainerManager = new FileDataContainerManager();
            try {
                try {
                    for (int t = 0; t < tsJobResultsNoStats.getTimes().length; t++) {
                        getClientTaskStatusSupport().setMessage("Creating Movie... Progress " + NumberUtils.formatNumber(100.0 * ((double) t / (double) tsJobResultsNoStats.getTimes().length), 3) + "%");
                        double min = Double.POSITIVE_INFINITY;
                        double max = Double.NEGATIVE_INFINITY;
                        for (int index = 1; index < timeSeries.length; index++) {
                            double v = timeSeries[index][t];
                            if ((dataInfoProvider == null || dataInfoProvider.isDefined(index - 1)) && !Double.isNaN(v) && !Double.isInfinite(v)) {
                                min = Math.min(min, v);
                                max = Math.max(max, v);
                            }
                        }
                        das.setValueDomain(new Range(min, max));
                        if (das.getAutoScale()) {
                            das.setActiveScaleRange(new Range(min, max));
                        }
                        int[][] surfacesColors = new int[surfaceCanvas.getSurfaceCollection().getSurfaceCount()][];
                        for (int i = 0; i < surfaceCanvas.getSurfaceCollection().getSurfaceCount(); i += 1) {
                            Surface surface = surfaceCanvas.getSurfaceCollection().getSurfaces(i);
                            surfacesColors[i] = new int[surface.getPolygonCount()];
                            for (int j = 0; j < surface.getPolygonCount(); j += 1) {
                                int membIndex = meshRegionSurfaces.getMembraneIndexForPolygon(i, j);
                                surfacesColors[i][j] = das.getColorFromValue(timeSeries[membIndex + 1][t]);
                            }
                        }
                        surfaceCanvas.setSurfacesColors(surfacesColors);
                        surfaceCanvas.paintImmediately(0, 0, surfaceWidth, surfaceHeight);
                        surfaceCanvas.paint(g2D);
                        bufferedImage.getRGB(0, 0, surfaceWidth, surfaceHeight, singleFrame, 0, surfaceWidth);
                        sampleDuration = 1;
                        sample = FormatSpecificSpecs.getVideoMediaSample(surfaceWidth, surfaceHeight * varNames.length, sampleDuration, false, FormatSpecificSpecs.CODEC_JPEG, 1.0f, singleFrame);
                        chunks[t] = new VideoMediaChunk(sample, fileDataContainerManager);
                    }
                } finally {
                    surfaceCanvas.setSurfacesColors(origSurfacesColors);
                    surfaceCanvas.paintImmediately(0, 0, surfaceWidth, surfaceHeight);
                }
                MediaTrack videoTrack = new MediaTrack(chunks);
                MediaMovie newMovie = new MediaMovie(videoTrack, videoTrack.getDuration(), timeScale);
                newMovie.addUserDataEntry(new UserDataEntry("cpy", "\u00A9" + (new GregorianCalendar()).get(Calendar.YEAR) + ", UCHC"));
                newMovie.addUserDataEntry(new UserDataEntry("des", "Dataset name: " + movieVCDataIdentifier.getID()));
                newMovie.addUserDataEntry(new UserDataEntry("cmt", "Time range: " + timePoints[beginTimeIndex] + " - " + timePoints[endTimeIndex]));
                for (int k = 0; k < varNames.length; k++) {
                    // pad with 0 if k < 10
                    String entryType = "v" + (k < 10 ? "0" : "") + k;
                    UserDataEntry entry = new UserDataEntry(entryType, "Variable name: " + varNames[k] + " min: " + das.getValueDomain().getMin() + " max: " + das.getValueDomain().getMax());
                    newMovie.addUserDataEntry(entry);
                }
                getClientTaskStatusSupport().setMessage("Writing Movie to disk...");
                FileOutputStream fos = new FileOutputStream(selectedFile);
                DataOutputStream movieOutput = new DataOutputStream(new BufferedOutputStream(fos));
                MediaMethods.writeMovie(movieOutput, newMovie);
                movieOutput.close();
                fos.close();
            } finally {
                fileDataContainerManager.closeAllAndDelete();
            }
        }
    };
    ClientTaskDispatcher.dispatch(this, hash, new AsynchClientTask[] { task1, task2, task3 }, true, true, null);
}
Also used : DisplayAdapterService(cbit.image.DisplayAdapterService) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) TimeSeriesJobSpec(org.vcell.util.document.TimeSeriesJobSpec) DataOutputStream(java.io.DataOutputStream) DataInfoProvider(cbit.vcell.simdata.DataInfoProvider) FileDataContainerManager(cbit.vcell.export.server.FileDataContainerManager) BufferedImage(java.awt.image.BufferedImage) VideoMediaSample(cbit.vcell.export.gloworm.quicktime.VideoMediaSample) Surface(cbit.vcell.geometry.surface.Surface) VCFileChooser(org.vcell.util.gui.VCFileChooser) VideoMediaChunk(cbit.vcell.export.gloworm.quicktime.VideoMediaChunk) BufferedOutputStream(java.io.BufferedOutputStream) Hashtable(java.util.Hashtable) UserDataEntry(cbit.vcell.export.gloworm.atoms.UserDataEntry) GregorianCalendar(java.util.GregorianCalendar) Range(org.vcell.util.Range) Point(java.awt.Point) SinglePoint(cbit.vcell.geometry.SinglePoint) Graphics2D(java.awt.Graphics2D) MediaTrack(cbit.vcell.export.gloworm.quicktime.MediaTrack) FileOutputStream(java.io.FileOutputStream) SurfaceMovieSettingsPanel(cbit.vcell.geometry.gui.SurfaceMovieSettingsPanel) File(java.io.File) TSJobResultsNoStats(org.vcell.util.document.TSJobResultsNoStats) MediaMovie(cbit.vcell.export.gloworm.quicktime.MediaMovie)

Example 2 with VCFileChooser

use of org.vcell.util.gui.VCFileChooser in project vcell by virtualcell.

the class ReferenceDataPanel method updateReferenceDataFromFile.

/**
 * Comment
 */
private void updateReferenceDataFromFile() {
    try {
        VCFileChooser fileChooser = new VCFileChooser();
        fileChooser.setFileSelectionMode(javax.swing.JFileChooser.FILES_ONLY);
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_CSV);
        // Set the default file filter...
        fileChooser.setFileFilter(FileFilters.FILE_FILTER_CSV);
        // remove all selector
        fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
        File defaultPath = null;
        if (getUserPreferences() != null) {
            defaultPath = getUserPreferences().getCurrentDialogPath();
            if (defaultPath != null) {
                fileChooser.setCurrentDirectory(defaultPath);
            }
        }
        fileChooser.setDialogTitle("Import Data File");
        if (fileChooser.showOpenDialog(this) != javax.swing.JFileChooser.APPROVE_OPTION) {
            // user didn't choose save
            throw UserCancelException.CANCEL_FILE_SELECTION;
        } else {
            File selectedFile = fileChooser.getSelectedFile();
            if (selectedFile == null) {
                // no file selected (no name given)
                throw UserCancelException.CANCEL_FILE_SELECTION;
            } else {
                if (getUserPreferences() != null) {
                    File newPath = selectedFile.getParentFile();
                    if (!newPath.equals(defaultPath)) {
                        getUserPreferences().setCurrentDialogPath(newPath);
                    }
                }
                CSV csv = new CSV();
                RowColumnResultSet rowColumnResultSet = csv.importFrom(new java.io.FileReader(selectedFile));
                double[] weights = new double[rowColumnResultSet.getDataColumnCount()];
                java.util.Arrays.fill(weights, 1.0);
                ReferenceData referenceData = new SimpleReferenceData(rowColumnResultSet, weights);
                updateReferenceData(referenceData);
            }
        }
    } catch (UserCancelException e) {
    // ignore
    } catch (Exception e) {
        e.printStackTrace();
        if (e instanceof ParseException) {
            showHelp((ParseException) e);
        } else {
            DialogUtils.showErrorDialog(this, e.getMessage(), e);
        }
    }
}
Also used : SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) ReferenceData(cbit.vcell.opt.ReferenceData) CSV(cbit.vcell.math.CSV) VCFileChooser(org.vcell.util.gui.VCFileChooser) UserCancelException(org.vcell.util.UserCancelException) ParseException(java.text.ParseException) File(java.io.File) SimpleReferenceData(cbit.vcell.opt.SimpleReferenceData) ParseException(java.text.ParseException) UserCancelException(org.vcell.util.UserCancelException) RowColumnResultSet(cbit.vcell.math.RowColumnResultSet)

Example 3 with VCFileChooser

use of org.vcell.util.gui.VCFileChooser in project vcell by virtualcell.

the class ClientRequestManager method downloadExportedData.

/**
 * Comment
 */
public static void downloadExportedData(final Component requester, final UserPreferences userPrefs, final ExportEvent evt) {
    AsynchClientTask task1 = new AsynchClientTask("Retrieving data from '" + evt.getLocation() + "'", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            final Exception[] excArr = new Exception[] { null };
            final boolean[] bFlagArr = new boolean[] { false };
            final ByteArrayOutputStream[] baosArr = new ByteArrayOutputStream[1];
            final HttpGet[] httpGetArr = new HttpGet[1];
            final ImageJConnection[] imagejConnetArr = new ImageJConnection[1];
            // Start download of exported file in separate thread that is interruptible (apache HTTPClient)
            Thread interruptible = new Thread(new Runnable() {

                @Override
                public void run() {
                    if (getClientTaskStatusSupport() != null) {
                        getClientTaskStatusSupport().setMessage("downloading data...");
                    }
                    CloseableHttpClient httpclient = HttpClients.createDefault();
                    httpGetArr[0] = new HttpGet(evt.getLocation());
                    CloseableHttpResponse response = null;
                    try {
                        response = httpclient.execute(httpGetArr[0]);
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            long size = entity.getContentLength();
                            InputStream instream = entity.getContent();
                            try {
                                // Thread.sleep(60000);
                                if (size > 0) {
                                    baosArr[0] = new ByteArrayOutputStream((int) size);
                                } else {
                                    baosArr[0] = new ByteArrayOutputStream();
                                }
                                IOUtils.copy(instream, baosArr[0]);
                            } finally {
                                instream.close();
                            }
                        }
                    } catch (Exception e) {
                        excArr[0] = e;
                    } finally {
                        if (imagejConnetArr[0] != null) {
                            imagejConnetArr[0].closeConnection();
                        }
                        if (response != null) {
                            try {
                                response.close();
                            } catch (Exception e) {
                            }
                        }
                        if (httpclient != null) {
                            try {
                                httpclient.close();
                            } catch (Exception e) {
                            }
                        }
                        bFlagArr[0] = true;
                    }
                }
            });
            interruptible.start();
            // Wait for download to 1-finish, 2-fail or 3-be cancelled by user
            while (!bFlagArr[0]) {
                if (getClientTaskStatusSupport() != null && getClientTaskStatusSupport().isInterrupted()) {
                    // user cancelled
                    if (httpGetArr[0] != null) {
                        httpGetArr[0].abort();
                    }
                    if (imagejConnetArr[0] != null) {
                        imagejConnetArr[0].closeConnection();
                    }
                    throw UserCancelException.CANCEL_GENERIC;
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // caused by pressing 'cancel' button on progresspopup
                    if (httpGetArr[0] != null) {
                        httpGetArr[0].abort();
                    }
                    if (imagejConnetArr[0] != null) {
                        imagejConnetArr[0].closeConnection();
                    }
                    if (getClientTaskStatusSupport() != null && getClientTaskStatusSupport().isInterrupted()) {
                        throw UserCancelException.CANCEL_GENERIC;
                    }
                }
            }
            if (excArr[0] != null) {
                // download failed
                throw excArr[0];
            }
            // 
            if (evt.getFormat() == null || !evt.getFormat().equals("IMAGEJ")) {
                // save for file save operations
                hashTable.put(BYTES_KEY, baosArr[0].toByteArray());
            } else {
                // NRRD format send to ImageJ
                if (getClientTaskStatusSupport() != null) {
                    getClientTaskStatusSupport().setMessage("unpacking data...");
                }
                ByteArrayInputStream bais = new ByteArrayInputStream(baosArr[0].toByteArray());
                ZipInputStream zis = null;
                BufferedInputStream bis = null;
                try {
                    zis = new ZipInputStream(bais);
                    ZipEntry entry = zis.getNextEntry();
                    // System.out.println("zipfile entry name="+entry.getName()+"zipfile entry size="+entry.getSize());
                    // File tempf = new File("C:\\temp\\tempf.nrrd");
                    // FileOutputStream fos = new FileOutputStream(tempf);
                    // byte[] mybuf = new byte[1000];
                    // int numread = 0;
                    // while((numread = zis.read(mybuf)) != -1){
                    // fos.write(mybuf, 0, numread);
                    // }
                    // fos.close();
                    TimeSpecs timeSpecs = evt.getTimeSpecs();
                    double[] timePoints = new double[timeSpecs.getEndTimeIndex() - timeSpecs.getBeginTimeIndex() + 1];
                    for (int tp = timeSpecs.getBeginTimeIndex(); tp <= timeSpecs.getEndTimeIndex(); tp++) {
                        timePoints[tp - timeSpecs.getBeginTimeIndex()] = timeSpecs.getAllTimes()[tp];
                    }
                    // doesn't open connection until later
                    imagejConnetArr[0] = new ImageJConnection(ImageJHelper.ExternalCommunicator.IMAGEJ);
                    bis = new BufferedInputStream(zis);
                    ImageJHelper.vcellSendNRRD(requester, bis, getClientTaskStatusSupport(), imagejConnetArr[0], "VCell exported data '" + entry.getName() + "'", timePoints, evt.getVariableSpecs().getVariableNames());
                } finally {
                    if (zis != null) {
                        try {
                            zis.closeEntry();
                            zis.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                // finished, exit all further tasks
                throw UserCancelException.CANCEL_GENERIC;
            }
        }
    };
    AsynchClientTask task2 = new AsynchClientTask("selecting file to save", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            // user pref could be null if trying local export
            String defaultPath = getPreferredPath(userPrefs);
            final VCFileChooser fileChooser = new VCFileChooser(defaultPath);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            String name = evt.getDataIdString();
            String suffix = null;
            if (evt.getLocation().toLowerCase().endsWith(".mov")) {
                fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_MOV);
                fileChooser.setFileFilter(FileFilters.FILE_FILTER_MOV);
                suffix = "_exported.mov";
            } else if (evt.getLocation().toLowerCase().endsWith(".gif")) {
                fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_GIF);
                fileChooser.setFileFilter(FileFilters.FILE_FILTER_GIF);
                suffix = "_exported.gif";
            } else if (evt.getLocation().toLowerCase().endsWith(".jpeg")) {
                fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_JPEG);
                fileChooser.setFileFilter(FileFilters.FILE_FILTER_JPEG);
                suffix = "_exported.jpeg";
            } else {
                fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_ZIP);
                fileChooser.setFileFilter(FileFilters.FILE_FILTER_ZIP);
                suffix = "_exported.zip";
            }
            File file = new File(name + suffix);
            if (file.exists()) {
                int count = 0;
                do {
                    file = new File(name + "_" + count + suffix);
                    count++;
                } while (file.exists());
            }
            fileChooser.setSelectedFile(file);
            fileChooser.setDialogTitle("Save exported dataset...");
            int approve = fileChooser.showSaveDialog(requester);
            if (approve == JFileChooser.APPROVE_OPTION) {
                hashTable.put("selectedFile", fileChooser.getSelectedFile());
            } else {
                fileChooser.setSelectedFile(null);
            }
        }
    };
    AsynchClientTask task3 = new AsynchClientTask("saving to file", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            File selectedFile = (File) hashTable.get("selectedFile");
            if (selectedFile == null) {
                return;
            }
            setPreferredPath(userPrefs, selectedFile);
            // System.out.println("New preferred file path: " + newPath + ", Old preferred file path: " + defaultPath);
            if (selectedFile.exists()) {
                String question = null;
                if (userPrefs != null) {
                    question = PopupGenerator.showWarningDialog(requester, userPrefs, UserMessage.warn_OverwriteFile, selectedFile.getAbsolutePath());
                } else {
                    question = DialogUtils.showWarningDialog(requester, "Overwrite File?", "Overwrite file '" + selectedFile.getAbsolutePath() + "'?", new String[] { UserMessage.OPTION_OVERWRITE_FILE, UserMessage.OPTION_CANCEL }, UserMessage.OPTION_OVERWRITE_FILE);
                }
                if (question != null && question.equals(UserMessage.OPTION_CANCEL)) {
                    return;
                }
            }
            byte[] bytes = (byte[]) hashTable.get(BYTES_KEY);
            FileOutputStream fo = new FileOutputStream(selectedFile);
            fo.write(bytes);
            fo.close();
        }
    };
    ClientTaskDispatcher.dispatch(requester, new Hashtable<String, Object>(), new AsynchClientTask[] { task1, task2, task3 }, false, true, null);
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) ZipEntry(java.util.zip.ZipEntry) BufferedInputStream(java.io.BufferedInputStream) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) VCFileChooser(org.vcell.util.gui.VCFileChooser) TimeSpecs(cbit.vcell.export.server.TimeSpecs) ImageJConnection(org.vcell.imagej.ImageJHelper.ImageJConnection) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Hashtable(java.util.Hashtable) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) DataInputStream(java.io.DataInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UtilCancelException(org.vcell.util.UtilCancelException) DataFormatException(java.util.zip.DataFormatException) UserCancelException(org.vcell.util.UserCancelException) ZipInputStream(java.util.zip.ZipInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) CSGObject(cbit.vcell.geometry.CSGObject) ChooseFile(cbit.vcell.client.task.ChooseFile) File(java.io.File)

Example 4 with VCFileChooser

use of org.vcell.util.gui.VCFileChooser in project vcell by virtualcell.

the class DatabaseWindowManager method showFileChooserDialog.

/**
 * Insert the method's description here.
 * Creation date: (5/14/2004 6:11:35 PM)
 */
public static File showFileChooserDialog(TopLevelWindowManager requester, final FileFilter fileFilter, final UserPreferences currentUserPreferences, int fileSelectMode) throws Exception {
    // the boolean isXMLNotImage is true if we are trying to choose an XML file
    // It is false if we are trying to choose an image file
    // This is used to set the appropriate File filters.
    File defaultPath = (File) (currentUserPreferences != null ? currentUserPreferences.getCurrentDialogPath() : "");
    VCFileChooser fileChooser = new VCFileChooser(defaultPath);
    fileChooser.setFileSelectionMode(fileSelectMode);
    // setting fileFilter for xml files
    fileChooser.setFileFilter(fileFilter);
    int returnval = fileChooser.showOpenDialog(requester.getComponent());
    if (returnval == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        // reset the user preference for the default path, if needed.
        File newPath = selectedFile.getParentFile();
        if (newPath != null && !newPath.equals(defaultPath)) {
            if (currentUserPreferences != null) {
                currentUserPreferences.setCurrentDialogPath(newPath);
            }
        }
        // System.out.println("New preferred file path: " + newPath + ", Old preferred file path: " + defaultPath);
        return selectedFile;
    } else {
        // user didn't select a file
        throw UserCancelException.CANCEL_FILE_SELECTION;
    }
}
Also used : VCFileChooser(org.vcell.util.gui.VCFileChooser) File(java.io.File)

Example 5 with VCFileChooser

use of org.vcell.util.gui.VCFileChooser in project vcell by virtualcell.

the class ChooseFile method showBioModelXMLFileChooser.

/**
 * Insert the method's description here.
 * Creation date: (5/31/2004 6:04:14 PM)
 */
private File showBioModelXMLFileChooser(Hashtable<String, Object> hashTable) throws java.lang.Exception {
    BioModel bioModel = (BioModel) hashTable.get("documentToExport");
    JFrame currentWindow = (JFrame) hashTable.get("currentWindow");
    UserPreferences userPreferences = (UserPreferences) hashTable.get("userPreferences");
    TopLevelWindowManager topLevelWindowManager = (TopLevelWindowManager) hashTable.get("topLevelWindowManager");
    SelectorExtensionFilter forceFileFilter = null;
    {
        Object obj = hashTable.get(FORCE_FILE_FILTER);
        if (obj != null) {
            VCAssert.ofType(obj, SelectorExtensionFilter.class);
            forceFileFilter = (SelectorExtensionFilter) obj;
            VCAssert.assertTrue(forceFileFilter.supports(Selector.FULL_MODEL), "only " + Selector.FULL_MODEL + " filters supported for force file filter");
        }
    }
    if (topLevelWindowManager == null) {
        throw new RuntimeException("toplLevelWindowManager required");
    }
    File defaultPath = userPreferences.getCurrentDialogPath();
    // JFileChooser fileChooser = new JFileChooser(defaultPath);
    VCFileChooser fileChooser = new VCFileChooser(defaultPath);
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setMultiSelectionEnabled(false);
    final SimulationContext[] simContexts = bioModel.getSimulationContexts();
    boolean spatialDeterministicSim = false;
    boolean nonspatialDeterministicSim = false;
    boolean stochasticSim = false;
    @SuppressWarnings("unused") boolean // add logic to set this
    bnglSim = false;
    for (SimulationContext sc : simContexts) {
        if (sc.getApplicationType() == Application.NETWORK_STOCHASTIC) {
            stochasticSim = true;
        } else {
            if (sc.getGeometry().getDimension() > 0) {
                spatialDeterministicSim = true;
            } else {
                nonspatialDeterministicSim = true;
            }
        }
    }
    FileFilter defaultFileFilter;
    if (forceFileFilter == null) {
        List<FileFilter> dlist = FileFilters.supports(SelectorExtensionFilter.Selector.DEFAULT);
        VCAssert.assertTrue(dlist.size() == 1, "Exactly one filter must be designated default");
        defaultFileFilter = dlist.get(0);
        // use a set to avoid duplicated entries; TreeSet show listing is alphabetical
        Set<FileFilter> filters = new TreeSet<>();
        filters.addAll(FileFilters.supports(SelectorExtensionFilter.Selector.FULL_MODEL));
        if (spatialDeterministicSim) {
            filters.addAll(FileFilters.supports(SelectorExtensionFilter.Selector.DETERMINISTIC, SelectorExtensionFilter.Selector.SPATIAL));
        }
        if (nonspatialDeterministicSim) {
            filters.addAll(FileFilters.supports(SelectorExtensionFilter.Selector.DETERMINISTIC, SelectorExtensionFilter.Selector.NONSPATIAL));
        }
        if (stochasticSim) {
            filters.addAll(FileFilters.supports(SelectorExtensionFilter.Selector.STOCHASTIC));
        }
        /*add BNGL selector here
		if (bnglSim) {
			filters.addAll(FileFilters.supports(SelectorExtensionFilter.Selector.BNGL));
		}
		*/
        fileChooser.addChoosableFileFilter(defaultFileFilter);
        for (FileFilter f : filters) {
            if (f == defaultFileFilter) {
                continue;
            }
            fileChooser.addChoosableFileFilter(f);
        }
    /*
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_12);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_21);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_22);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_23);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_24);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_31_CORE);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SBML_31_SPATIAL);
	//	fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_CELLML);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SEDML);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_VCML);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_MATLABV6);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_PDF);
		fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_SMOLDYN_INPUT);
		*/
    } else {
        defaultFileFilter = forceFileFilter;
    }
    // remove all selectors
    fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
    // Set the default file filter...
    fileChooser.setFileFilter(defaultFileFilter);
    fileChooser.setSelectedFile(new java.io.File(TokenMangler.fixTokenStrict(bioModel.getName())));
    fileChooser.setDialogTitle("Export Virtual Cell BioModel As...");
    if (fileChooser.showSaveDialog(currentWindow) != JFileChooser.APPROVE_OPTION) {
        // user didn't choose save
        throw UserCancelException.CANCEL_FILE_SELECTION;
    }
    File selectedFile = fileChooser.getSelectedFile();
    FileFilter gfileFilter = fileChooser.getFileFilter();
    VCAssert.ofType(gfileFilter, SelectorExtensionFilter.class);
    // only ExtensionFilters should have been added;
    SelectorExtensionFilter fileFilter = (SelectorExtensionFilter) gfileFilter;
    if (selectedFile == null) {
        // no file selected (no name given)
        throw UserCancelException.CANCEL_FILE_SELECTION;
    }
    final File fileUserSpecified = selectedFile.getCanonicalFile();
    // /
    String selectedFileName = recordAndRemoveExtension(selectedFile.getPath());
    if (extensionUserProvided != null && !extensionUserProvided.isEmpty() && !extensionUserProvided.startsWith(".")) {
        extensionUserProvided = "." + extensionUserProvided;
    }
    if (fileFilter.isValidExtension(extensionUserProvided)) {
        selectedFileName += extensionUserProvided;
    } else {
        selectedFileName += fileFilter.getPrimaryExtension();
    }
    selectedFile = new File(selectedFileName);
    checkForOverwrites(selectedFile, topLevelWindowManager.getComponent(), userPreferences);
    // put the filter in the hash so the export task knows what to do...
    hashTable.put(FILE_FILTER, fileFilter);
    if (fileFilter.supports(SelectorExtensionFilter.Selector.FULL_MODEL)) {
        // nothing more to do in this case
        resetPreferredFilePath(selectedFile, userPreferences);
        return selectedFile;
    }
    // ArrayList<String> applicableAppNameList = new ArrayList<String>();
    ArrayList<SimulationContext> applicableSimContexts = new ArrayList<>();
    for (SimulationContext sc : simContexts) {
        if (sc.getGeometry().getDimension() == 0) {
            if (!fileFilter.supports(SelectorExtensionFilter.Selector.NONSPATIAL)) {
                continue;
            }
        } else if (!fileFilter.supports(SelectorExtensionFilter.Selector.SPATIAL)) {
            continue;
        }
        if (sc.getApplicationType() == Application.NETWORK_STOCHASTIC) {
            if (!fileFilter.supports(SelectorExtensionFilter.Selector.STOCHASTIC)) {
                continue;
            }
        } else if (!fileFilter.supports(SelectorExtensionFilter.Selector.DETERMINISTIC)) {
            continue;
        }
        applicableSimContexts.add(sc);
    }
    /*
		{} else {
			// all apps
			for (int i=0;i<simContexts.length;i++){
				applicableAppNameList.add(simContexts[i].getName());
			}
		}
	 */
    SimulationContext chosenSimContext = null;
    if (applicableSimContexts.size() == 1) {
        chosenSimContext = applicableSimContexts.get(0);
    } else /*
		else if (!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_PDF.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_12.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_21.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_22.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_23.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_24.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_31_CORE.getDescription()) &&
				!fileFilter.getDescription().equals(FileFilters.FILE_FILTER_SBML_31_SPATIAL.getDescription())) {
			if(fileFilter.getDescription().equals(FileFilters.FILE_FILTER_BNGL.getDescription())) {
				boolean hasReactions = bioModel.getModel().getReactionSteps().length > 0 ? true : false;
				System.out.println(hasReactions);
				if(hasReactions) {					// mixed
					String errMsg = "Simple Reactions cannot be exported to .bngl format.";
					errMsg += "<br>Some information will be lost.";
					errMsg += "<br><br>Continue anyway?";
					errMsg = "<html>" + errMsg + "</html>";
					int dialogButton = JOptionPane.YES_NO_OPTION;
					int returnCode = JOptionPane.showConfirmDialog(topLevelWindowManager.getComponent(), errMsg, "Exporting to .bngl", dialogButton);
					if (returnCode != JOptionPane.YES_OPTION) {
						throw UserCancelException.CANCEL_FILE_SELECTION;
					}
				}
			}

			//String[] applicationNames = (String[])org.vcell.util.BeanUtils.getArray(applicableAppNameList,String.class);
		}	 */
    {
        // String[] applicationNames = applicableAppNameList.toArray(new String[applicableAppNameList.size()]);
        SimContextAdapter[] scarray = adapt(applicableSimContexts);
        Object choice = PopupGenerator.showListDialog(topLevelWindowManager, scarray, "Please select Application");
        if (choice == null) {
            throw UserCancelException.CANCEL_FILE_SELECTION;
        }
        VCAssert.ofType(choice, SimContextAdapter.class);
        SimContextAdapter sca = (SimContextAdapter) choice;
        chosenSimContext = sca.simCtx;
    }
    hashTable.put(SIM_CONTEXT, chosenSimContext);
    // boolean isSbml = fileFilter.supports(SelectorExtensionFilter.Selector.SBML);
    if (fileFilter.requiresMoreChoices()) {
        ExtensionFilter.ChooseContext ctx = new ExtensionFilter.ChooseContext(hashTable, topLevelWindowManager, currentWindow, chosenSimContext, selectedFile, selectedFileName);
        fileFilter.askUser(ctx);
    }
    {
        boolean showConfirm = false;
        final boolean someContextsFiltered = simContexts.length > applicableSimContexts.size();
        showConfirm = someContextsFiltered;
        if (!showConfirm) {
            final File fileAfterProcessing = selectedFile.getCanonicalFile();
            if (!fileAfterProcessing.equals(fileUserSpecified)) {
                final String nameUserSpecified = fileUserSpecified.getCanonicalPath();
                final String nameAfterProcessing = fileAfterProcessing.getCanonicalPath();
                if (FilenameUtils.indexOfExtension(nameUserSpecified) > 0) {
                    // have extension on user path
                    showConfirm = true;
                } else {
                    // don't prompt if user left extension off
                    String nameAfterNoExtension = FilenameUtils.getFullPath(nameAfterProcessing) + FilenameUtils.getBaseName(nameAfterProcessing);
                    if (!nameAfterNoExtension.equals(nameUserSpecified)) {
                        showConfirm = true;
                    }
                }
            }
        }
        if (showConfirm) {
            final String exportDesc = fileFilter.getShortDescription();
            StringBuilder sb = new StringBuilder();
            List<SimulationContext> all = new ArrayList<>(Arrays.asList(simContexts));
            all.removeAll(applicableSimContexts);
            if (!all.isEmpty()) {
                SimContextAdapter[] removed = adapt(all);
                sb.append("The following simulations are not supported by ");
                sb.append(exportDesc);
                sb.append(" and have been removed: ");
                sb.append(StringUtils.join(removed, ", "));
                sb.append(".\n\n");
            }
            SimContextAdapter[] included = adapt(applicableSimContexts);
            sb.append("Export model with simulations ");
            sb.append(StringUtils.join(included, ", "));
            sb.append(" to file of type ");
            sb.append(exportDesc);
            sb.append(' ');
            sb.append(selectedFile.getCanonicalPath());
            sb.append('?');
            String reply = DialogUtils.showOKCancelWarningDialog(currentWindow, "Verify Export", sb.toString());
            if (!SimpleUserMessage.OPTION_OK.equals(reply)) {
                throw UserCancelException.CANCEL_GENERIC;
            }
        }
    }
    resetPreferredFilePath(selectedFile, userPreferences);
    return selectedFile;
}
Also used : UserPreferences(cbit.vcell.client.server.UserPreferences) TopLevelWindowManager(cbit.vcell.client.TopLevelWindowManager) ArrayList(java.util.ArrayList) JFrame(javax.swing.JFrame) TreeSet(java.util.TreeSet) ExtensionFilter(org.vcell.util.gui.exporter.ExtensionFilter) SelectorExtensionFilter(org.vcell.util.gui.exporter.SelectorExtensionFilter) VCFileChooser(org.vcell.util.gui.VCFileChooser) ArrayList(java.util.ArrayList) List(java.util.List) FileFilter(javax.swing.filechooser.FileFilter) SelectorExtensionFilter(org.vcell.util.gui.exporter.SelectorExtensionFilter) SimulationContext(cbit.vcell.mapping.SimulationContext) File(java.io.File) BioModel(cbit.vcell.biomodel.BioModel) File(java.io.File)

Aggregations

File (java.io.File)15 VCFileChooser (org.vcell.util.gui.VCFileChooser)15 UserCancelException (org.vcell.util.UserCancelException)5 UserPreferences (cbit.vcell.client.server.UserPreferences)4 TopLevelWindowManager (cbit.vcell.client.TopLevelWindowManager)3 FileOutputStream (java.io.FileOutputStream)3 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)2 Point (java.awt.Point)2 BufferedImage (java.awt.image.BufferedImage)2 PropertyVetoException (java.beans.PropertyVetoException)2 Hashtable (java.util.Hashtable)2 JFrame (javax.swing.JFrame)2 FileFilter (javax.swing.filechooser.FileFilter)2 UtilCancelException (org.vcell.util.UtilCancelException)2 DisplayAdapterService (cbit.image.DisplayAdapterService)1 ImageException (cbit.image.ImageException)1 BioModel (cbit.vcell.biomodel.BioModel)1 ClientServerManager (cbit.vcell.client.server.ClientServerManager)1 ChooseFile (cbit.vcell.client.task.ChooseFile)1 UserDataEntry (cbit.vcell.export.gloworm.atoms.UserDataEntry)1