Example usage for javafx.application Platform runLater

List of usage examples for javafx.application Platform runLater

Introduction

In this page you can find the example usage for javafx.application Platform runLater.

Prototype

public static void runLater(Runnable runnable) 

Source Link

Document

Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future.

Usage

From source file:com.bekwam.resignator.ResignatorAppMainViewController.java

@FXML
public void deleteProfile() {

    final String profileNameToDelete = lvProfiles.getSelectionModel().getSelectedItem();

    if (logger.isDebugEnabled()) {
        logger.debug("[DELETE PROFILE] delete {}", profileNameToDelete);
    }/* www. j a  v a2 s  . com*/

    Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Delete profile '" + profileNameToDelete + "'?");
    alert.setHeaderText("Delete profile");
    Optional<ButtonType> response = alert.showAndWait();
    if (!response.isPresent() || response.get() != ButtonType.OK) {
        if (logger.isDebugEnabled()) {
            logger.debug("[DELETE PROFILE] delete profile cancelled");
        }
        return;
    }

    final boolean apProfileNameSetFlag = StringUtils.equalsIgnoreCase(activeProfile.getProfileName(),
            profileNameToDelete);

    if (apProfileNameSetFlag) {
        activeProfile.setProfileName("");
    }

    Task<Void> task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {

            //
            // #18 adjust record prior to dao call
            //
            if (activeConfiguration.getRecentProfiles().contains(profileNameToDelete)) {
                activeConfiguration.getRecentProfiles().remove(profileNameToDelete);
            }

            if (StringUtils.equalsIgnoreCase(profileNameToDelete, activeConfiguration.getActiveProfile())) {
                activeConfiguration.setActiveProfile(null);
            }

            configurationDS.deleteProfile(profileNameToDelete);

            return null;
        }

        @Override
        protected void succeeded() {
            super.succeeded();

            Platform.runLater(() -> {

                // #18 recent profiles
                Iterator<MenuItem> iterator = mRecentProfiles.getItems().iterator();
                while (iterator.hasNext()) {
                    MenuItem mi = iterator.next();
                    if (StringUtils.equalsIgnoreCase(mi.getText(), profileNameToDelete)) {
                        iterator.remove();
                    }
                }
                if (CollectionUtils.isEmpty(mRecentProfiles.getItems())) {
                    mRecentProfiles.getItems().add(MI_NO_PROFILES);
                }

                lvProfiles.getItems().remove(profileNameToDelete);

                if (StringUtils.equalsIgnoreCase(profileNameToDelete, activeProfile.getProfileName())) {
                    newProfile();
                }

                needsSave.set(false);
            });
        }

        @Override
        protected void failed() {
            super.failed();
            Alert alert = new Alert(Alert.AlertType.ERROR, getException().getMessage());
            alert.setHeaderText("Error deleting profile");
            alert.showAndWait();
        }

    };

    new Thread(task).start();
}

From source file:com.bekwam.resignator.ResignatorAppMainViewController.java

@FXML
public void renameProfile(ListView.EditEvent<String> evt) {
    if (logger.isDebugEnabled()) {
        logger.debug("[RENAME]");
    }/*from   w ww  .java  2s .c o m*/

    final String oldProfileName = lvProfiles.getItems().get(evt.getIndex());
    final boolean apProfileNameSetFlag = StringUtils.equalsIgnoreCase(activeProfile.getProfileName(),
            oldProfileName);

    String suggestedNewProfileName = "";
    if (configurationDS.profileExists(evt.getNewValue())) {

        suggestedNewProfileName = configurationDS.suggestUniqueProfileName(evt.getNewValue());

        if (logger.isDebugEnabled()) {
            logger.debug("[RENAME] configuration exists; suggested name={}", suggestedNewProfileName);
        }

        Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "That profile name already exists."
                + System.getProperty("line.separator") + "Save as " + suggestedNewProfileName + "?");
        alert.setHeaderText("Profile name in use");
        Optional<ButtonType> response = alert.showAndWait();
        if (!response.isPresent() || response.get() != ButtonType.OK) {
            if (logger.isDebugEnabled()) {
                logger.debug("[RENAME] rename cancelled");
            }
            return;
        }
    }

    final String newProfileName = StringUtils.defaultIfBlank(suggestedNewProfileName, evt.getNewValue());

    if (apProfileNameSetFlag) { // needs to be set for save
        activeProfile.setProfileName(newProfileName);
    }

    Task<Void> renameTask = new Task<Void>() {

        @Override
        protected Void call() throws Exception {
            configurationDS.renameProfile(oldProfileName, newProfileName);
            Platform.runLater(() -> {
                lvProfiles.getItems().set(evt.getIndex(), newProfileName);

                Collections.sort(lvProfiles.getItems());
                lvProfiles.getSelectionModel().select(newProfileName);

            });
            return null;
        }

        @Override
        protected void failed() {
            super.failed();
            logger.error("can't rename profile from " + oldProfileName + " to " + newProfileName,
                    getException());
            Alert alert = new Alert(Alert.AlertType.ERROR, getException().getMessage());
            alert.setHeaderText("Can't rename profile '" + oldProfileName + "'");
            alert.showAndWait();

            if (apProfileNameSetFlag) { // revert
                activeProfile.setProfileName(oldProfileName);
            }
        }

        @Override
        protected void cancelled() {
            super.cancelled();
            Alert alert = new Alert(Alert.AlertType.ERROR, "Rename cancelled by user");
            alert.setHeaderText("Cancelled");
            alert.showAndWait();

            if (apProfileNameSetFlag) { // revert
                activeProfile.setProfileName(oldProfileName);
            }
        }
    };

    new Thread(renameTask).start();
}

From source file:com.bekwam.resignator.ResignatorAppMainViewController.java

@FXML
public void changePassword() {

    Task<Void> task = new Task<Void>() {

        @Override/*from  w ww.j  a v a2s  .  c o m*/
        protected Void call() throws Exception {

            NewPasswordController npc = newPasswordControllerProvider.get();

            Platform.runLater(() -> {
                try {
                    npc.showAndWait();
                } catch (Exception exc) {
                    logger.error("error showing change password form", exc);
                }
            });

            synchronized (npc) {
                try {
                    npc.wait(MAX_WAIT_TIME); // 10 minutes to enter the password
                } catch (InterruptedException exc) {
                    logger.error("change password operation interrupted", exc);
                }
            }

            if (logger.isDebugEnabled()) {
                logger.debug("[CHANGE PASSWORD] npc={}", npc.getHashedPassword());
            }

            if (StringUtils.isNotEmpty(npc.getHashedPassword())) {

                activeConfiguration.setHashedPassword(npc.getHashedPassword());
                activeConfiguration.setUnhashedPassword(npc.getUnhashedPassword());
                activeConfiguration.setLastUpdatedDateTime(LocalDateTime.now());

                configurationDS.saveConfiguration();

                configurationDS.loadConfiguration();

            } else {

                Platform.runLater(() -> {
                    Alert noPassword = new Alert(Alert.AlertType.INFORMATION, "Password change cancelled.");
                    noPassword.showAndWait();
                });

            }

            return null;
        }
    };
    new Thread(task).start();
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public void doBlastn(final String fasta, final String evaluestr, final boolean ids, final RunnableResult rr,
        boolean show) {
    /*File blastn;/*from   ww  w .java  2 s .  c o  m*/
    File blastp;
    File makeblastdb;
    File blastx = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastx.exe" );
    if( !blastx.exists() ) {
       blastx = new File( "/opt/ncbi-blast-2.2.29+/bin/blastx" );
       if( !blastx.exists() ) {
    blastx = new File( "/usr/local/ncbi/blast/bin/blastx" );
    blastn = new File( "/usr/local/ncbi/blast/bin/blastn" );
    blastp = new File( "/usr/local/ncbi/blast/bin/blastp" );
            
    makeblastdb = new File( "/usr/local/ncbi/blast/bin/makeblastdb" );
       } else {
    blastn = new File( "/opt/ncbi-blast-2.2.29+/bin/blastn" );
    blastp = new File( "/opt/ncbi-blast-2.2.29+/bin/blastp" );
            
    makeblastdb = new File( "/opt/ncbi-blast-2.2.29+/bin/makeblastdb" );
       }
    } else {
       blastn = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastn.exe" );
       blastp = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastp.exe" );
               
       makeblastdb = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\makeblastdb.exe" );
    }*/

    int procs = Runtime.getRuntime().availableProcessors();
    String[] mcmds = { "makeblastdb", "-dbtype", "nucl", "-title", "tmp", "-out", "tmp" };
    List<String> lcmd = new ArrayList<String>(Arrays.asList(mcmds));

    final ProcessBuilder mpb = new ProcessBuilder(lcmd);
    mpb.redirectErrorStream(true);
    try {
        final Process mp = mpb.start();

        new Thread() {
            public void run() {
                try {
                    OutputStream pos = mp.getOutputStream();
                    for (String cname : geneset.contigmap.keySet()) {
                        Sequence c = geneset.contigmap.get(cname);
                        if (ids)
                            pos.write((">" + c.id + "\n").getBytes());
                        else {
                            pos.write((">" + c.getName() + "\n").getBytes());
                        }
                        StringBuilder sb = c.getStringBuilder();
                        for (int i = 0; i < sb.length(); i += 70) {
                            pos.write(sb.substring(i, Math.min(sb.length(), i + 70)).getBytes());
                        }
                        pos.write('\n');
                    }
                    pos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            public void run() {
                try {
                    InputStream pin = mp.getInputStream();
                    InputStreamReader rdr = new InputStreamReader(pin);
                    //FileReader fr = new FileReader( new File("c:/dot.blastout") );
                    BufferedReader br = new BufferedReader(rdr);
                    String line = br.readLine();
                    while (line != null) {
                        System.out.println(line);
                        line = br.readLine();
                    }
                    pin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.run();

        //File blastFile = blastn; //dbType.equals("prot") ? type.equals("prot") ? blastp : blastx : blastn;

        String[] cmds1 = { "blastn", "-dust", "no", "-perc_identity", "99", "-word_size", "21", "-query", "-",
                "-db", "tmp", "-evalue", evaluestr, "-num_threads", Integer.toString(procs) };
        String[] cmds2 = { "blastn", "-query", "-", "-db", "tmp", "-evalue", evaluestr, "-num_threads",
                Integer.toString(procs) };
        String[] cmds = show ? cmds2 : cmds1;

        lcmd = new ArrayList<String>(Arrays.asList(cmds));
        //String[] exts = extrapar.trim().split("[\t ]+");

        ProcessBuilder pb = new ProcessBuilder(lcmd);
        pb.redirectErrorStream(true);
        final Process p = pb.start();

        final Thread t = new Thread() {
            public void run() {
                try {
                    OutputStream pos = p.getOutputStream();
                    pos.write(fasta.getBytes());
                    pos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();

        Map<String, Set<String>> tph = new HashMap<String, Set<String>>();
        Map<String, Map<String, String>> tvp = new HashMap<String, Map<String, String>>();
        Map<String, Map<String, String>> tmr = new HashMap<String, Map<String, String>>();

        Map<String, Integer> specindex = new LinkedHashMap<String, Integer>();
        Map<String, Integer> phindex = new LinkedHashMap<String, Integer>();

        /*final Thread t2 = new Thread() {
           public void run() {*/
        try {
            System.err.println("WHY NOT");
            InputStreamReader rdr = new InputStreamReader(p.getInputStream());
            //FileReader fr = new FileReader( new File("c:/dot.blastout") );

            String qspec = null;
            String query = null;
            String ctype = null;
            Annotation at = new Annotation();
            int o = 0;
            StringBuilder res = new StringBuilder();
            BufferedReader br = new BufferedReader(rdr);
            String line = br.readLine();
            res.append(line + "\n");
            while (line != null) {
                if (line.startsWith("Query= ")) {
                    query = line.substring(7, line.length());
                    int e = query.indexOf("CRISPR") - 1;
                    if (e > 0) {
                        qspec = query.substring(0, e);
                        qspec = Sequence.getSpec(qspec);
                        String rest = query.substring(e + 8);
                        int ri = rest.lastIndexOf('-');
                        if (ri != -1)
                            ctype = rest.substring(ri + 1);
                    } else {
                        System.err.println();
                    }

                    line = br.readLine();
                    res.append(line + "\n");
                    while (!line.startsWith("Length")) {
                        line = br.readLine();
                        res.append(line + "\n");
                    }
                    o = Integer.parseInt(line.substring(7));
                } else if (line.startsWith("> ")) {
                    String contname = line.substring(1).trim();
                    //line = br.readLine();
                    //res.append( line+"\n" );
                    //int o = Integer.parseInt( line.substring(7) );

                    Sequence cont = geneset.contigmap.get(contname);

                    if (cont != null) {
                        int start = -1;
                        int stop = 0;
                        line = br.readLine();
                        res.append(line + "\n");
                        String lastmatch = null;
                        while (line != null && !line.startsWith(">")
                                && !line.startsWith("Query=") /*&& !line.contains("Expect =")*/ ) {
                            if (line.startsWith("Sbjct")) {
                                String[] split = line.split("[\t ]+");
                                int k = Integer.parseInt(split[1]);
                                int m = Integer.parseInt(split[3]);
                                lastmatch = split[2];

                                if (start == -1)
                                    start = k;
                                stop = m;
                            }
                            line = br.readLine();
                            res.append(line + "\n");
                        }

                        if (start > stop) {
                            int tmp = start;
                            start = stop;
                            stop = tmp;
                        }

                        at.start = start;
                        at.stop = stop;

                        //if( stop - start < o*2 ) {
                        List<Annotation> lann = cont.getAnnotations();
                        if (lann != null) {
                            int k = Collections.binarySearch(lann, at);

                            //System.err.println( "kkk  " + k + "   " + lann.size() );

                            if (k < 0)
                                k = -(k + 1) - 1;

                            Annotation ann = lann.get(Math.max(0, k));

                            boolean yes = true;
                            if (ann.type != null && ann.type.contains("ummer")) {
                                yes = false;
                            }

                            int u = k - 1;
                            Annotation nann = null;
                            if (u >= 0 && u < lann.size())
                                nann = lann.get(u);

                            u = k + 1;
                            Annotation rann = null;
                            if (u >= 0 && u < lann.size())
                                rann = lann.get(u);

                            if (nann != null && nann.type != null && nann.type.contains("ummer")) {
                                yes = false;
                            }

                            if (rann != null && rann.type != null && rann.type.contains("ummer")) {
                                yes = false;
                            }

                            if (!yes) {
                                //System.err.println();
                            }

                            Gene g = ann.getGene();
                            String desig = ann.designation;

                            if (yes && g != null) { //ann.stop > at.start && ann.start < at.stop ) {
                                GeneGroup gg = g.getGeneGroup();
                                if (desig != null && desig.contains("phage")) {
                                    if (!phindex.containsKey(desig))
                                        phindex.put(desig, phindex.size());

                                    Map<String, String> tvps;
                                    String specname = qspec;//Sequence.nameFix(qspec, true);
                                    if (!specindex.containsKey(specname))
                                        specindex.put(specname, specindex.size());

                                    if (tvp.containsKey(specname)) {
                                        tvps = tvp.get(specname);
                                    } else {
                                        tvps = new HashMap<String, String>();
                                        tvp.put(specname, tvps);
                                    }
                                    tvps.put(desig, ctype);

                                    String contspec = cont.getSpec();
                                    System.err.println(query + " asdf " + contspec + " " + lastmatch + "  "
                                            + at.start + " " + at.stop + "  " + ann.start + " " + ann.stop
                                            + " rann " + (rann != null ? rann.start + "  " + rann.stop : "")
                                            + " nann " + (nann != null ? nann.start + "  " + nann.stop : ""));
                                    if (qspec.equals(contspec)) {
                                        if (tmr.containsKey(specname)) {
                                            tvps = tmr.get(specname);
                                        } else {
                                            tvps = new HashMap<String, String>();
                                            tmr.put(specname, tvps);
                                        }
                                        tvps.put(desig, ctype);
                                    }

                                    /*if( specname.contains("brockianus_MAT_338") ) {
                                       System.err.println();
                                    }*/
                                }

                                Platform.runLater(() -> {
                                    if (!isGeneview()) {
                                        /*int ggindex = geneset.allgenegroups.indexOf( gg );
                                        int i = table.convertRowIndexToView( ggindex );
                                        if( i != -1 ) table.addRowSelectionInterval(i, i);*/

                                        table.getSelectionModel().select(gg);
                                    } else {
                                        /*int gindex = geneset.genelist.indexOf( g );
                                        int i = table.convertRowIndexToView( gindex );
                                        table.addRowSelectionInterval(i, i);*/

                                        gtable.getSelectionModel().select(g);
                                    }
                                });
                            }

                            /*for( Annotation ann : lann ) {
                               if( ann.stop > start && ann.start < stop ) {
                            Gene g = ann.getGene();
                            if( g != null ) {
                               if( table.getModel() == groupModel ) {
                                  GeneGroup gg = g.getGeneGroup();
                                          
                                  int ggindex = allgenegroups.indexOf( gg );
                                  int i = table.convertRowIndexToView( ggindex );
                                  table.addRowSelectionInterval(i, i);
                               } else if( table.getModel() == defaultModel ) {
                                  int gindex = geneset.genelist.indexOf( g );
                                  int i = table.convertRowIndexToView( gindex );
                                  table.addRowSelectionInterval(i, i);
                               }
                            }
                               }
                            }*/
                        }
                        //}
                        continue;
                    }
                }

                /*int i = line.indexOf(' ', 2);
                if( i == -1 ) i = line.length();
                String id = line.substring(2, i);
                        
                Gene g = genemap.get( id );
                if( g != null ) {
                   if( table.getModel() == groupModel ) {
                      i = allgenegroups.indexOf( g.getGeneGroup() );
                      if( i != -1 && i < table.getRowCount() ) {
                         int r = table.convertRowIndexToView( i );
                         table.addRowSelectionInterval(r, r);
                      }
                   } else {
                      i = geneset.genelist.indexOf( g );
                      if( i != -1 && i < table.getRowCount() ) {
                         int r = table.convertRowIndexToView( i );
                         table.addRowSelectionInterval(r, r);
                      }
                   }
                }
                        
                String stuff = line+"\n";
                line = br.readLine();
                while( line != null && !line.startsWith("Query=") && !line.startsWith("> ") ) {
                   stuff += line+"\n";
                   line = br.readLine();
                }
                if( rr != null ) {
                   rr.run( stuff );
                   //res += line+"\n";
                }
                } //else*/
                line = br.readLine();
                res.append(line + "\n");
            }
            br.close();
            p.destroy();

            for (String specname : geneset.speccontigMap.keySet()) {
                List<Sequence> lseq = geneset.speccontigMap.get(specname);
                for (Sequence seq : lseq) {
                    List<Annotation> lann = seq.getAnnotations();
                    if (lann != null) {
                        for (Annotation a : lann) {
                            String desig = a.designation;
                            if (desig != null && desig.contains("phage") && phindex.containsKey(desig)) {
                                if (!specindex.containsKey(specname))
                                    specindex.put(specname, specindex.size());

                                Set<String> tvps;
                                if (tph.containsKey(specname)) {
                                    tvps = tph.get(specname);
                                } else {
                                    tvps = new HashSet<String>();
                                    tph.put(specname, tvps);
                                }
                                tvps.add(desig);
                            }
                        }
                    }
                }
            }

            int k = 0;
            int u = 0;
            Workbook wb = new XSSFWorkbook();
            Sheet sh = wb.createSheet("Phage");
            Row rw = sh.createRow(u++);
            //res = new StringBuilder();
            for (String ph : phindex.keySet()) {
                res.append("\t" + ph);
                rw.createCell(++k).setCellValue(ph);
            }
            res.append("\n");
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);
                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Map<String, String> set = tvp.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.containsKey(ph)) {
                            String type = set.get(ph);
                            if (type == null || type.length() == 0)
                                type = "yes";
                            res.append("\t" + type);
                            rw.createCell(k).setCellValue(type);
                        } else {
                            res.append("\t");
                        }

                        k++;
                    }
                }
                res.append("\n");
            }

            for (String ph : phindex.keySet()) {
                res.append("\t" + ph);
            }
            res.append("\n");

            u++;
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);

                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Map<String, String> set = tmr.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.containsKey(ph)) {
                            String type = set.get(ph);
                            if (type == null || type.length() == 0)
                                type = "yes";
                            res.append("\t" + type);
                            rw.createCell(k).setCellValue(type);
                        } else
                            res.append("\t");

                        k++;
                    }
                }
                res.append("\n");
            }

            u++;
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);

                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Set<String> set = tph.get(rspec);
                Map<String, String> setvp = tvp.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.contains(ph)) {
                            if (setvp != null && setvp.containsKey(ph)) {
                                res.append("\tyes wspacer");
                                rw.createCell(k).setCellValue("yes wspacer");
                            } else {
                                res.append("\tyes");
                                rw.createCell(k).setCellValue("yes");
                            }
                        } else
                            res.append("\t");

                        k++;
                    }
                }
                res.append("\n");
            }

            File file = new File("/Users/sigmar/phage.xlsx");
            FileOutputStream fos = new FileOutputStream(file);
            wb.write(fos);
            fos.close();

            Desktop.getDesktop().open(file);

            //if( !show ) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(800, 600);

            JTextArea ta = new JTextArea();
            ta.setFont(new Font("monospaced", Font.PLAIN, 12));
            ta.append(res.toString());
            JScrollPane sp = new JScrollPane(ta);
            frame.add(sp);

            frame.setVisible(true);

            FileWriter fw = new FileWriter("/Users/sigmar/file.txt");
            fw.write(res.toString());
            fw.close();

            if (rr != null)
                rr.run("close");
            //}

            /*if( rr != null ) {
             rr.run( res );
            }*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*   }
        };
        t2.start();*/
        //fr.close();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
}

From source file:de.bayern.gdi.gui.Controller.java

/**
 * Set the text of the status bar in UI thread.
 * Adds current message to log history.//  w ww  . j  ava  2 s .co m
 *
 * @param msg the text to set.
 */
public void setStatusTextUI(String msg) {
    String logText;
    String regexAtom = I18n.format("atom.bytes.downloaded", "[\\d|\\.|\\,]+");
    String regexWfs = I18n.format("file.download.bytes", "[\\d|\\.|\\,]+");
    //Filter atom/wfs download messages
    if (!logHistoryParent.getText().matches(regexAtom) && !logHistoryParent.getText().matches(regexWfs)) {
        logText = logHistoryParent.getText() + "\n" + logHistory.getText();
    } else {
        logText = logHistory.getText();
    }
    logToAppLog(msg);

    Platform.runLater(() -> {
        logHistoryParent.setText(msg);
        logHistory.setText(logText);
    });
}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 *///  w ww  .j a v  a2s .  co  m
private void projetsNouveau() {
    Action reponse = null;
    Localization.setLocale(locale);
    if (!dejaSauve) {
        reponse = Dialogs.create().owner(null).title("Nouveau projet")
                .masthead("Vous n'avez pas sauvegard votre projet").message("Voulez vous le sauver ?")
                .showConfirm();

    }
    if (reponse == Dialog.Actions.YES) {
        try {
            projetSauve();

        } catch (IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if ((reponse == Dialog.Actions.YES) || (reponse == Dialog.Actions.NO) || (reponse == null)) {
        panoEntree = "";
        deleteDirectory(repertTemp);
        String repertPanovisu = repertTemp + File.separator + "panovisu";
        File rptPanovisu = new File(repertPanovisu);
        rptPanovisu.mkdirs();
        copieDirectory(repertAppli + File.separator + "panovisu", repertPanovisu);
        menuPanoramique.setDisable(false);

        imgAjouterPano.setDisable(false);
        imgAjouterPano.setOpacity(1.0);
        imgSauveProjet.setDisable(false);
        imgSauveProjet.setOpacity(1.0);
        sauveProjet.setDisable(false);
        sauveSousProjet.setDisable(false);
        visiteGenere.setDisable(false);
        fichProjet = null;
        paneChoixPanoramique.setVisible(false);
        panoramiquesProjet = new Panoramique[50];
        nombrePanoramiques = 0;
        retireAffichageLigne();
        retireAffichageHotSpots();
        retireAffichagePointsHotSpots();
        numPoints = 0;
        numImages = 0;
        numHTML = 0;
        gestionnaireInterface.nombreImagesFond = 0;
        gestionnairePlan.planActuel = -1;
        imagePanoramique.setImage(null);
        listeChoixPanoramique.getItems().clear();
        listeChoixPanoramiqueEntree.getItems().clear();
        lblDragDrop.setVisible(true);
        Node ancNord = (Node) pano.lookup("#Nord");
        if (ancNord != null) {
            pano.getChildren().remove(ancNord);
        }
        Node ancPoV = (Node) pano.lookup("#PoV");
        if (ancPoV != null) {
            pano.getChildren().remove(ancPoV);
        }

        gestionnairePlan.lblDragDropPlan.setVisible(true);
        nombrePlans = 0;
        plans = new Plan[100];
        gestionnairePlan.creeInterface(largeurInterface, hauteurInterface - 60);
        Pane panneauPlan = gestionnairePlan.tabInterface;
        affichagePlan.setDisable(true);
        tabPlan.setDisable(true);
        tabPlan.setContent(panneauPlan);
        vuePanoramique.setOnDragOver((DragEvent event) -> {
            Dragboard db = event.getDragboard();
            if (db.hasFiles()) {
                event.acceptTransferModes(TransferMode.ANY);
            } else {
                event.consume();
            }
        });

        // Dropping over surface
        vuePanoramique.setOnDragDropped((DragEvent event) -> {
            Platform.runLater(() -> {
                paneAttends.setVisible(true);
            });
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles()) {
                success = true;
                String filePath = null;
                File[] list = new File[100];
                int i = 0;
                for (File file1 : db.getFiles()) {
                    filePath = file1.getAbsolutePath();
                    list[i] = file1;
                    i++;
                }
                int nb = i;
                if (list != null) {
                    i = 0;
                    File[] lstFich1 = new File[list.length];
                    String[] typeFich1 = new String[list.length];
                    for (int jj = 0; jj < nb; jj++) {
                        File file = list[jj];
                        String nomfich = file.getAbsolutePath();
                        String extension = nomfich.substring(nomfich.lastIndexOf(".") + 1, nomfich.length())
                                .toLowerCase();
                        //                            if (extension.equals("bmp") || extension.equals("jpg")) {
                        if (extension.equals("jpg") || extension.equals("bmp") || extension.equals("tif")) {
                            Image img = null;
                            if (extension.equals("tif")) {
                                try {
                                    img = ReadWriteImage.readTiff(file.getAbsolutePath());
                                } catch (ImageReadException ex) {
                                    Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null,
                                            ex);
                                } catch (IOException ex) {
                                    Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null,
                                            ex);
                                }
                            } else {
                                img = new Image("file:" + file.getAbsolutePath());
                            }
                            typeFich1[i] = "";
                            if (img.getWidth() == 2 * img.getHeight()) {
                                lstFich1[i] = file;
                                typeFich1[i] = Panoramique.SPHERE;
                                i++;
                            }
                            if (img.getWidth() == img.getHeight()) {
                                String nom = file.getAbsolutePath().substring(0,
                                        file.getAbsolutePath().length() - 6);
                                boolean trouve = false;
                                for (int j = 0; j < i; j++) {
                                    String nom1 = "";
                                    if (lstFich1[j].getAbsolutePath().length() == file.getAbsolutePath()
                                            .length()) {
                                        nom1 = lstFich1[j].getAbsolutePath().substring(0,
                                                file.getAbsolutePath().length() - 6);
                                    }
                                    if (nom.equals(nom1)) {
                                        trouve = true;
                                    }
                                }
                                if (!trouve) {
                                    lstFich1[i] = file;
                                    typeFich1[i] = Panoramique.CUBE;
                                    i++;
                                }
                            }

                        }
                    }
                    File[] lstFich = new File[i];
                    System.arraycopy(lstFich1, 0, lstFich, 0, i);

                    for (int ii = 0; ii < lstFich.length; ii++) {
                        File file1 = lstFich[ii];
                        dejaSauve = false;
                        stPrincipal.setTitle(stPrincipal.getTitle().replace(" *", "") + " *");
                        sauveProjet.setDisable(false);
                        currentDir = file1.getParent();
                        File imageRepert = new File(repertTemp + File.separator + "panos");

                        if (!imageRepert.exists()) {

                            imageRepert.mkdirs();
                        }
                        repertPanos = imageRepert.getAbsolutePath();
                        try {
                            //                            try {
                            //                                if (typeFich1[ii].equals(Panoramique.SPHERE)) {
                            //                                    copieFichierRepertoire(file1.getPath(), repertPanos);
                            //                                } else {
                            //                                    String nom = file1.getAbsolutePath().substring(0, file1.getAbsolutePath().length() - 6);
                            //                                    copieFichierRepertoire(nom + "_u.jpg", repertPanos);
                            //                                    copieFichierRepertoire(nom + "_d.jpg", repertPanos);
                            //                                    copieFichierRepertoire(nom + "_f.jpg", repertPanos);
                            //                                    copieFichierRepertoire(nom + "_b.jpg", repertPanos);
                            //                                    copieFichierRepertoire(nom + "_r.jpg", repertPanos);
                            //                                    copieFichierRepertoire(nom + "_l.jpg", repertPanos);
                            //                                }
                            //                            } catch (IOException ex) {
                            //                                Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
                            //                            }
                            if (typeFich1[ii] == Panoramique.CUBE || typeFich1[ii] == Panoramique.SPHERE) {
                                ajoutePanoramiqueProjet(file1.getPath(), typeFich1[ii]);
                            }
                        } catch (InterruptedException ex) {
                            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                    installeEvenements();

                    imgVisiteGenere.setOpacity(1.0);
                    imgVisiteGenere.setDisable(false);
                    lblDragDrop.setVisible(false);
                }

            }
            Platform.runLater(() -> {
                paneAttends.setVisible(false);
            });
            event.setDropCompleted(success);
            event.consume();
        });

    }
}

From source file:editeurpanovisu.EditeurPanovisu.java

private void analyseLigne(String ligneComplete) throws InterruptedException, ImageReadException {
    panoEntree = "";
    nombrePanoramiques = 0;/*from  w w  w  .  j a v a 2 s.c  om*/
    ligneComplete = ligneComplete.replace("[", "|");
    String lignes[] = ligneComplete.split("\\|", 500);
    String ligne;
    String[] elementsLigne;
    String[] typeElement;
    int nbHS = 0;
    int nbImg = 0;
    int nbHsplan = 0;
    nombrePlans = -1;
    for (int kk = 1; kk < lignes.length; kk++) {
        ligne = lignes[kk];
        elementsLigne = ligne.split(";", 25);
        typeElement = elementsLigne[0].split(">", 2);
        typeElement[0] = typeElement[0].replace(" ", "").replace("=", "").replace("[", "");
        elementsLigne[0] = typeElement[1];
        if ("Panoramique".equals(typeElement[0])) {
            for (int i = 0; i < elementsLigne.length; i++) {
                elementsLigne[i] = elementsLigne[i].replace("]", "").replace("\n", "");
                String[] valeur = elementsLigne[i].split(":", 2);
                System.out.println(valeur[0] + "=" + valeur[1]);

                switch (valeur[0]) {
                case "fichier":
                    String nmFich = valeur[1];
                    Platform.runLater(() -> {
                        lblCharge.setText(nmFich);
                    });
                    File imgPano = new File(nmFich);
                    File imageRepert = new File(repertTemp + File.separator + "panos");

                    if (!imageRepert.exists()) {
                        imageRepert.mkdirs();
                    }
                    repertPanos = imageRepert.getAbsolutePath();
                    String fichierPano = imgPano.getPath();
                    String extension = fichierPano.substring(fichierPano.length() - 3, fichierPano.length());
                    Image img = null;
                    if ("tif".equals(extension)) {
                        try {
                            img = ReadWriteImage.readTiff(fichierPano);
                        } catch (IOException ex) {
                            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        img = new Image("file:" + fichierPano);
                    }

                    //                            try {
                    //                                copieFichierRepertoire(imgPano.getPath(), repertPanos);
                    //
                    //                            } catch (IOException ex) {
                    //                                Logger.getLogger(EditeurPanovisu.class
                    //                                        .getName()).log(Level.SEVERE, null, ex);
                    //                            }
                    if (img.getWidth() == img.getHeight()) {
                        ajoutePanoramiqueProjet(valeur[1], Panoramique.CUBE);

                    } else {
                        ajoutePanoramiqueProjet(valeur[1], Panoramique.SPHERE);
                    }

                    break;

                case "titre":
                    if (!valeur[1].equals("'null'")) {
                        panoramiquesProjet[panoActuel].setTitrePanoramique(valeur[1]);
                    } else {
                        panoramiquesProjet[panoActuel].setTitrePanoramique("");
                    }
                    break;
                case "type":
                    panoramiquesProjet[panoActuel].setTypePanoramique(valeur[1]);
                    break;
                case "afficheInfo":
                    if (valeur[1].equals("true")) {
                        panoramiquesProjet[panoActuel].setAfficheInfo(true);
                    } else {
                        panoramiquesProjet[panoActuel].setAfficheInfo(false);
                    }
                    break;
                case "afficheTitre":
                    if (valeur[1].equals("true")) {
                        panoramiquesProjet[panoActuel].setAfficheTitre(true);
                    } else {
                        panoramiquesProjet[panoActuel].setAfficheTitre(false);
                    }
                    break;
                case "nb":
                    nbHS = Integer.parseInt(valeur[1]);
                    break;
                case "nbImg":
                    nbImg = Integer.parseInt(valeur[1]);
                    break;
                case "regardX":
                    panoramiquesProjet[panoActuel].setLookAtX(Double.parseDouble(valeur[1]));
                    break;
                case "regardY":
                    panoramiquesProjet[panoActuel].setLookAtY(Double.parseDouble(valeur[1]));
                    break;
                case "zeroNord":
                    panoramiquesProjet[panoActuel].setZeroNord(Double.parseDouble(valeur[1]));
                    break;
                case "numeroPlan":
                    panoramiquesProjet[panoActuel].setNumeroPlan(Integer.parseInt(valeur[1].replace(" ", "")));
                    break;
                case "affichePlan":
                    if (valeur[1].equals("true")) {
                        panoramiquesProjet[panoActuel].setAffichePlan(true);
                    } else {
                        panoramiquesProjet[panoActuel].setAffichePlan(false);
                    }
                    break;
                default:
                    break;
                }
            }
            for (int jj = 0; jj < nbHS; jj++) {
                kk++;
                ligne = lignes[kk];
                elementsLigne = ligne.split(";", 10);
                typeElement = elementsLigne[0].split(">", 2);
                typeElement[0] = typeElement[0].replace(" ", "").replace("=", "").replace("[", "");
                elementsLigne[0] = typeElement[1];
                HotSpot HS = new HotSpot();
                for (int i = 0; i < elementsLigne.length; i++) {
                    elementsLigne[i] = elementsLigne[i].replace("]", "");
                    String[] valeur = elementsLigne[i].split(":", 2);

                    switch (valeur[0]) {
                    case "longitude":
                        HS.setLongitude(Double.parseDouble(valeur[1]));
                        break;
                    case "latitude":
                        HS.setLatitude(Double.parseDouble(valeur[1]));
                        break;
                    case "image":
                        if ("null".equals(valeur[1])) {
                            HS.setFichierImage(null);
                        } else {
                            HS.setFichierImage(valeur[1]);
                        }
                        break;
                    case "info":
                        if ("null".equals(valeur[1])) {
                            HS.setInfo(null);
                        } else {
                            HS.setInfo(valeur[1]);
                        }
                        break;
                    case "xml":
                        if ("null".equals(valeur[1])) {
                            HS.setFichierXML(null);
                        } else {
                            HS.setFichierXML(valeur[1]);
                        }
                        break;
                    case "anime":
                        if (valeur[1].equals("true")) {
                            HS.setAnime(true);
                        } else {
                            HS.setAnime(false);
                        }
                        break;
                    }
                }
                panoramiquesProjet[panoActuel].addHotspot(HS);
            }

            for (int jj = 0; jj < nbImg; jj++) {
                kk++;
                ligne = lignes[kk];
                elementsLigne = ligne.split(";", 10);
                typeElement = elementsLigne[0].split(">", 2);
                typeElement[0] = typeElement[0].replace(" ", "").replace("=", "").replace("[", "");
                elementsLigne[0] = typeElement[1];
                HotspotImage HS = new HotspotImage();
                for (int i = 0; i < elementsLigne.length; i++) {
                    elementsLigne[i] = elementsLigne[i].replace("]", "");
                    String[] valeur = elementsLigne[i].split(":", 2);
                    switch (valeur[0]) {
                    case "longitude":
                        HS.setLongitude(Double.parseDouble(valeur[1]));
                        break;
                    case "latitude":
                        HS.setLatitude(Double.parseDouble(valeur[1]));
                        break;
                    case "image":
                        if ("null".equals(valeur[1])) {
                            HS.setFichierImage(null);
                        } else {
                            HS.setFichierImage(valeur[1]);
                        }
                        break;
                    case "info":
                        if ("null".equals(valeur[1])) {
                            HS.setInfo(null);
                        } else {
                            HS.setInfo(valeur[1]);
                        }
                        break;
                    case "img":
                        if ("null".equals(valeur[1])) {
                            HS.setLienImg(null);
                        } else {
                            HS.setLienImg(valeur[1]);
                        }
                        break;
                    case "urlImg":
                        if ("null".equals(valeur[1])) {
                            HS.setUrlImage(null);
                        } else {
                            HS.setUrlImage(valeur[1]);
                        }
                        String nmFich = valeur[1];
                        File imgPano = new File(nmFich);
                        File imageRepert = new File(repertTemp + File.separator + "images");

                        if (!imageRepert.exists()) {
                            imageRepert.mkdirs();
                        }
                        repertPanos = imageRepert.getAbsolutePath();
                        try {
                            copieFichierRepertoire(imgPano.getPath(), repertPanos);
                        } catch (IOException ex) {
                            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
                        }

                        break;
                    case "anime":
                        if (valeur[1].equals("true")) {
                            HS.setAnime(true);
                        } else {
                            HS.setAnime(false);
                        }
                        break;
                    }
                }
                panoramiquesProjet[panoActuel].addHotspotImage(HS);
            }

        }

        if ("Plan".equals(typeElement[0])) {
            for (int i = 0; i < elementsLigne.length; i++) {
                elementsLigne[i] = elementsLigne[i].replace("]", "");
                String[] valeur = elementsLigne[i].split(":", 2);
                System.out.println(valeur[0] + "=" + valeur[1]);
                switch (valeur[0]) {
                case "lienImage":
                    nombrePlans++;
                    plans[nombrePlans] = new Plan();
                    plans[nombrePlans].setLienPlan(valeur[1]);
                    File repertoirePlan = new File(repertTemp + File.separator + "images");
                    if (!repertoirePlan.exists()) {
                        repertoirePlan.mkdirs();
                    }
                    try {
                        copieFichierRepertoire(plans[nombrePlans].getLienPlan(),
                                repertoirePlan.getAbsolutePath());
                    } catch (IOException ex) {
                        Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    break;
                case "image":
                    plans[nombrePlans].setImagePlan(valeur[1]);
                    break;
                case "titre":
                    if (!valeur[1].equals("'null'")) {
                        plans[nombrePlans].setTitrePlan(valeur[1]);
                    } else {
                        plans[nombrePlans].setTitrePlan("");
                    }
                    break;
                case "nb":
                    nbHsplan = Integer.parseInt(valeur[1]);
                    break;
                case "position":
                    plans[nombrePlans].setPosition(valeur[1]);
                    break;
                case "positionX":
                    plans[nombrePlans].setPositionX(Double.parseDouble(valeur[1]));
                    break;
                case "positionY":
                    plans[nombrePlans].setPositionY(Double.parseDouble(valeur[1]));
                    break;
                case "directionNord":
                    plans[nombrePlans].setDirectionNord(Double.parseDouble(valeur[1]));
                    break;
                default:
                    break;
                }
            }
            for (int jj = 0; jj < nbHsplan; jj++) {
                kk++;
                ligne = lignes[kk];
                elementsLigne = ligne.split(";", 15);
                typeElement = elementsLigne[0].split(">", 2);
                typeElement[0] = typeElement[0].replace(" ", "").replace("=", "").replace("[", "");
                elementsLigne[0] = typeElement[1];
                HotSpot HS = new HotSpot();
                for (int i = 0; i < elementsLigne.length; i++) {
                    elementsLigne[i] = elementsLigne[i].replace("]", "");
                    String[] valeur = elementsLigne[i].split(":", 2);
                    switch (valeur[0]) {
                    case "longitude":
                        HS.setLongitude(Double.parseDouble(valeur[1]));
                        break;
                    case "latitude":
                        HS.setLatitude(Double.parseDouble(valeur[1]));
                        break;
                    case "image":
                        if ("null".equals(valeur[1])) {
                            HS.setFichierImage(null);
                        } else {
                            HS.setFichierImage(valeur[1]);
                        }
                        break;
                    case "info":
                        if ("null".equals(valeur[1])) {
                            HS.setInfo(null);
                        } else {
                            HS.setInfo(valeur[1]);
                        }
                        break;
                    case "xml":
                        if ("null".equals(valeur[1])) {
                            HS.setFichierXML(null);
                        } else {
                            HS.setFichierXML(valeur[1]);
                        }
                        break;
                    case "numeroPano":
                        HS.setNumeroPano(Integer.parseInt(valeur[1].replace("\n", "").replace(" ", "")));
                        break;
                    case "anime":
                        if (valeur[1].equals("true")) {
                            HS.setAnime(true);
                        } else {
                            HS.setAnime(false);
                        }
                        break;
                    }
                }
                plans[nombrePlans].addHotspot(HS);
            }
            gestionnairePlan.ajouterPlan();
        }
        if ("Interface".equals(typeElement[0])) {
            String[] elts = elementsLigne[0].replace("]", "").split("\n");
            List<String> listeTemplate = new ArrayList<>();
            for (String texte : elts) {
                if (!texte.equals("")) {
                    listeTemplate.add(texte);
                }
            }
            gestionnaireInterface.setTemplate(listeTemplate);
            gestionnaireInterface.afficheTemplate();
        }
        if ("PanoEntree".equals(typeElement[0])) {
            panoEntree = elementsLigne[0].split("]")[0];
        }
        if ("titreVisite".equals(typeElement[0])) {
            TextArea tfVisite = (TextArea) paneChoixPanoramique.lookup("#titreVisite");
            tfVisite.setText(elementsLigne[0].split("]")[0]);
        }

    }
    if (!panoEntree.equals("")) {
        listeChoixPanoramiqueEntree.setValue(panoEntree + ".jpg");
    }
    for (int ii = 0; ii < nombrePanoramiques; ii++) {
        Panoramique pano1 = panoramiquesProjet[ii];
    }
    nombrePlans++;
    gestionnaireInterface.rafraichit();
}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 *     /**//w ww . j  a  va 2s . co m
 *
 * @param strFichierImage fichier image  charger
 * @param strRepertoire rpertoire de sauvegarde
 * @param iNumPanoXML numro pour la gnration des fichiers
 * "panovisu"+iNumPanoXML+".jpg"
 * @param strNomFichierSauvegarde nom du fichier de sauvegarde
 * @param iNumero numro d'ordre du pano dans la liste  charger
 * @param iTotal nombre de panos  charger
 * @return nombre de niveaux
 */
private static int iCreeNiveauxImageEqui(String strFichierImage, String strNomFichierSauvegarde,
        String strRepertoire, int iNumPanoXML, int iNumero, int iTotal) {
    Platform.runLater(() -> {
        lblNiveaux.setText("Cration niveau principal");
    });

    double tailleNiv0 = 512.d;
    String strExtension = strFichierImage.substring(strFichierImage.length() - 3, strFichierImage.length());
    Image imgPano = null;
    if (strExtension.equals("tif")) {
        try {
            imgPano = ReadWriteImage.readTiff(strFichierImage);
            if (imgPano.getWidth() > 8192) {
                imgPano = ReadWriteImage.resizeImage(imgPano, 8192, 4096);

            }
        } catch (ImageReadException | IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        imgPano = new Image("file:" + strFichierImage);
        if (imgPano.getWidth() > 8192) {
            imgPano = new Image("file:" + strFichierImage, 8192, 4096, true, true);
        }
    }
    String strNomPano = strNomFichierSauvegarde
            .substring(strNomFichierSauvegarde.lastIndexOf(File.separator) + 1,
                    strNomFichierSauvegarde.length())
            .split("\\.")[0] + ".jpg";
    String strFicImage = strRepertoire + File.separator + "panovisu" + iNumPanoXML + ".jpg";
    try {
        ReadWriteImage.writeJpeg(imgPano, strFicImage, 0.95f, true, 0.25f);

    } catch (IOException ex) {
        Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
    }
    int iNombreNiveaux = 0;
    if (imgPano != null) {
        double tailleImage = imgPano.getWidth();
        strFichierImage = strFicImage;
        iNombreNiveaux = (int) (Math.log(tailleImage / tailleNiv0) / Math.log(2.d)) + 1;
        int iNbNiv = iNombreNiveaux;
        for (int i = 0; i < iNombreNiveaux; i++) {
            int ii = i;
            int iNombreNiv2 = iNombreNiveaux;
            Platform.runLater(() -> {
                lblNiveaux.setText("Cration niveau " + ii + "/" + (iNbNiv - 1));
                pbarAvanceChargement.setProgress(
                        ((double) (iNumero - 1) + 1.d / 3.d + 1.d / 3.d * ((double) ii) / iNombreNiv2)
                                / (double) iTotal);
            });
            try {
                double tailleNiveau = tailleImage * Math.pow(2.d, i) / Math.pow(2.d, iNombreNiveaux);
                if (strExtension.equals("tif")) {
                    try {
                        imgPano = ReadWriteImage.readTiff(strFichierImage);
                        imgPano = ReadWriteImage.resizeImage(imgPano, (int) tailleNiveau,
                                (int) tailleNiveau / 2);

                    } catch (ImageReadException ex) {
                        Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    imgPano = new Image("file:" + strFichierImage, Math.round(tailleNiveau * 2.d) / 2.d,
                            Math.round(tailleNiveau / 2.d), true, true);
                }
                String strRepNiveau = strRepertoire + File.separator + "niveau" + i;
                File fileRepert = new File(strRepNiveau);
                if (!fileRepert.exists()) {
                    fileRepert.mkdirs();
                }
                strNomPano = strNomFichierSauvegarde.substring(
                        strNomFichierSauvegarde.lastIndexOf(File.separator) + 1,
                        strNomFichierSauvegarde.length());
                strNomPano = strNomPano
                        .substring(strNomPano.lastIndexOf(File.separator) + 1, strNomPano.length())
                        .split("\\.")[0] + ".jpg";
                strFicImage = strRepNiveau + File.separator + "panovisu" + iNumPanoXML + ".jpg";
                if (i < iNombreNiveaux - 1) {
                    ReadWriteImage.writeJpeg(imgPano, strFicImage, 0.7f, true, 0.1f);
                } else {
                    ReadWriteImage.writeJpeg(imgPano, strFicImage, 0.95f, true, 0.25f);
                }

            } catch (IOException ex) {
                Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return iNombreNiveaux;
}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 * @param strFichierImage fichier image  charger
 * @param strRepertoire rpertoire de sauvegarde
 * @param iNumPanoXML numro pour la gnration des fichiers
 * @param strFace face calcule/*from w  w w.j a v  a  2s . c  o  m*/
 * @return
 */
private static int iCreeNiveauxImageCube(String strFichierImage, String strRepertoire, int iNumPanoXML,
        String strFace) {
    Platform.runLater(() -> {
        lblNiveaux.setText("Cration face : " + strFace + " niveau principal");
    });
    String strSuffixe = "";
    switch (strFace) {
    case "dessus":
        strSuffixe = "_u";
        break;
    case "dessous":
        strSuffixe = "_d";
        break;
    case "droite":
        strSuffixe = "_r";
        break;
    case "gauche":
        strSuffixe = "_l";
        break;
    case "devant":
        strSuffixe = "_f";
        break;
    case "derriere":
        strSuffixe = "_b";
        break;
    }
    double tailleNiv0 = 256.d;
    String strExtension = strFichierImage.substring(strFichierImage.length() - 3, strFichierImage.length());
    Image imgPano = null;
    if (strExtension.equals("tif")) {
        try {
            imgPano = ReadWriteImage.readTiff(strFichierImage);
            if (imgPano.getWidth() > 4096) {
                imgPano = ReadWriteImage.resizeImage(imgPano, 4096, 4096);

            }
        } catch (ImageReadException | IOException ex) {
            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        imgPano = new Image("file:" + strFichierImage);
        if (imgPano.getWidth() > 4096) {
            imgPano = new Image("file:" + strFichierImage, 4096, 4096, true, true);
        }
    }
    String strNomPano = strFichierImage.substring(strFichierImage.lastIndexOf(File.separator) + 1,
            strFichierImage.length());
    String strFicImage = strRepertoire + File.separator + "panovisu" + iNumPanoXML + strSuffixe + ".jpg";
    try {
        ReadWriteImage.writeJpeg(imgPano, strFicImage, 0.85f, true, 0.3f);

    } catch (IOException ex) {
        Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
    }
    int iNombreNiveaux = 0;
    if (imgPano != null) {
        double tailleImage = imgPano.getWidth();
        iNombreNiveaux = (int) (Math.log(tailleImage / tailleNiv0) / Math.log(2.d)) + 1;
        int nbNiv = iNombreNiveaux;
        for (int i = 0; i < iNombreNiveaux; i++) {
            try {
                int ii = i;
                Platform.runLater(() -> {
                    lblNiveaux.setText("Cration face : " + strFace + " niveau " + ii + "/" + (nbNiv - 1));
                });

                double tailleNiveau = tailleImage * Math.pow(2.d, i) / Math.pow(2.d, iNombreNiveaux);
                if (strExtension.equals("tif")) {
                    try {
                        imgPano = ReadWriteImage.readTiff(strFichierImage);
                        imgPano = ReadWriteImage.resizeImage(imgPano, (int) tailleNiveau, (int) tailleNiveau);

                    } catch (ImageReadException ex) {
                        Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else {
                    imgPano = new Image("file:" + strFichierImage, tailleNiveau, tailleNiveau, true, true);
                }

                String strRepNiveau = strRepertoire + File.separator + "niveau" + i;
                File fileRepert = new File(strRepNiveau);
                if (!fileRepert.exists()) {
                    fileRepert.mkdirs();
                }
                strNomPano = strFichierImage.substring(strFichierImage.lastIndexOf(File.separator) + 1,
                        strFichierImage.length());
                strFicImage = strRepNiveau + File.separator + "panovisu" + iNumPanoXML + strSuffixe + ".jpg";
                ReadWriteImage.writeJpeg(imgPano, strFicImage, 0.7f, true, 0.1f);

            } catch (IOException ex) {
                Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return iNombreNiveaux;
}

From source file:editeurpanovisu.EditeurPanovisu.java

/**
 *
 * @param listFichiers liste des fichiers  charger
 * @param iNb nombre de fichiers  charger
 * @return Task/*from w w w.  ja  va  2s .  c  o m*/
 */
public static Task tskChargeListeFichiers(final File[] listFichiers, int iNb) {
    return new Task() {
        @Override
        protected Object call() throws Exception {
            int i = 0;
            File[] fileLstFich1 = new File[listFichiers.length];
            String[] strTypeFich1 = new String[listFichiers.length];
            for (int jj = 0; jj < iNb; jj++) {
                File fileFichier = listFichiers[jj];
                String strNomfich = fileFichier.getAbsolutePath();
                String strExtension = strNomfich.substring(strNomfich.lastIndexOf(".") + 1, strNomfich.length())
                        .toLowerCase();
                if (strExtension.equals("jpg") || strExtension.equals("bmp") || strExtension.equals("tif")) {
                    Image imgPano = null;
                    if (strExtension.equals("tif")) {
                        try {
                            imgPano = ReadWriteImage.readTiff(fileFichier.getAbsolutePath());

                        } catch (ImageReadException | IOException ex) {
                            Logger.getLogger(EditeurPanovisu.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        imgPano = new Image("file:" + fileFichier.getAbsolutePath());
                    }
                    strTypeFich1[i] = "";
                    if (imgPano != null) {
                        if (imgPano.getWidth() == 2 * imgPano.getHeight()) {
                            fileLstFich1[i] = fileFichier;
                            strTypeFich1[i] = Panoramique.SPHERE;
                            i++;
                        }
                        if (imgPano.getWidth() == imgPano.getHeight()) {
                            String strNom = fileFichier.getAbsolutePath().substring(0,
                                    fileFichier.getAbsolutePath().length() - 6);
                            boolean bTrouveFichier = false;
                            for (int j = 0; j < i; j++) {
                                String strNom1 = "";
                                if (fileLstFich1[j].getAbsolutePath().length() == fileFichier.getAbsolutePath()
                                        .length()) {
                                    strNom1 = fileLstFich1[j].getAbsolutePath().substring(0,
                                            fileFichier.getAbsolutePath().length() - 6);
                                }
                                if (strNom.equals(strNom1)) {
                                    bTrouveFichier = true;
                                }
                            }
                            if (!bTrouveFichier) {
                                fileLstFich1[i] = fileFichier;
                                strTypeFich1[i] = Panoramique.CUBE;
                                i++;
                            }
                        }
                    }

                }
            }
            File[] fileLstFich = new File[i];
            System.arraycopy(fileLstFich1, 0, fileLstFich, 0, i);

            for (int ii = 0; ii < fileLstFich.length; ii++) {
                File fileFichier1 = fileLstFich[ii];
                int iNumP = ii + 1;
                Platform.runLater(() -> {
                    lblCharge.setText(
                            "pano " + iNumP + "/" + fileLstFich.length + " : " + fileFichier1.getPath());
                    lblNiveaux.setText("");
                    pbarAvanceChargement.setProgress((double) (iNumP - 1) / (double) fileLstFich.length);
                });

                setbDejaSauve(false);
                mniSauveProjet.setDisable(false);
                setStrCurrentDir(fileFichier1.getParent());
                File fileImageRepert = new File(getStrRepertTemp() + File.separator + "panos");

                if (!fileImageRepert.exists()) {

                    fileImageRepert.mkdirs();
                }
                setStrRepertPanos(fileImageRepert.getAbsolutePath());
                ajoutePanoramiqueProjet(fileFichier1.getPath(), strTypeFich1[ii], iNumP, fileLstFich.length);
            }
            return true;
        }

        @Override
        protected void succeeded() {
            getStPrincipal().setTitle(getStPrincipal().getTitle().replace(" *", "") + " *");
            super.succeeded();
            cbListeChoixPanoramique.getItems().clear();
            apVignettesPano.getChildren().clear();
            for (int i = 0; i < getiNombrePanoramiques(); i++) {
                String strFichierPano = getPanoramiquesProjet()[i].getStrNomFichier();
                String strNomPano = strFichierPano.substring(strFichierPano.lastIndexOf(File.separator) + 1,
                        strFichierPano.length());
                cbListeChoixPanoramique.getItems().add(strNomPano);
                String strExtension = getPanoramiquesProjet()[i].getStrNomFichier().substring(
                        getPanoramiquesProjet()[i].getStrNomFichier().length() - 3,
                        getPanoramiquesProjet()[i].getStrNomFichier().length());
                ImageView ivVignettePano = new ImageView(
                        getPanoramiquesProjet()[i].getImgVignettePanoramique());
                ivVignettePano.setPreserveRatio(true);
                ivVignettePano.setFitWidth(iLargeurVignettes);
                ivVignettePano.setLayoutX(5);
                ivVignettePano.setLayoutY((iLargeurVignettes / 2 + 10) * i + 10);
                ivVignettePano.setCursor(Cursor.HAND);
                int iNumero = i;
                ivVignettePano.setOnMouseClicked((e) -> {
                    affichePanoChoisit(iNumero);
                });
                ivVignettePano.setOnMouseDragEntered((e) -> {
                    ivVignettePano.setLayoutX(3);
                    ivVignettePano.setStyle("-fx-border-color : #fff;" + "-fx-border-width : 2px;"
                            + "-fx-border-style :solid;");
                });
                ivVignettePano.setOnMouseDragExited((e) -> {
                    ivVignettePano.setLayoutX(5);
                    ivVignettePano.setStyle("-fx-border-color : rgba(0,0,0,0);" + "-fx-border-width : 0px;"
                            + "-fx-border-style :none;");
                });

                apVignettesPano.getChildren().add(ivVignettePano);

            }
            apVignettesPano.getChildren().add(rectVignettePano);
            getVbChoixPanoramique().setVisible(true);
            ivImagePanoramique.setImage(getPanoramiquesProjet()[getiPanoActuel()].getImgPanoramique());
            ivImagePanoramique.setSmooth(true);
            retireAffichageLigne();
            dejaCharge = false;
            retireAffichageHotSpots();
            retireAffichagePointsHotSpots();
            setiNumPoints(0);
            ajouteAffichageLignes();
            cbListeChoixPanoramique.setValue(cbListeChoixPanoramique.getItems().get(getiPanoActuel()));
            affichePoV(getPanoramiquesProjet()[getiPanoActuel()].getRegardX(),
                    getPanoramiquesProjet()[getiPanoActuel()].getRegardY(),
                    getPanoramiquesProjet()[getiPanoActuel()].getChampVisuel());
            afficheNord(getPanoramiquesProjet()[getiPanoActuel()].getZeroNord());
            installeEvenements();
            ivVisiteGenere.setOpacity(1.0);
            ivVisiteGenere.setDisable(false);
            getGestionnaireInterface().rafraichit();
            affichePanoChoisit(getiPanoActuel());
            bPanoCharge = true;
            cbListeChoixPanoramique.setValue(cbListeChoixPanoramique.getItems().get(getiPanoActuel()));
            getApAttends().setVisible(false);
            mbarPrincipal.setDisable(false);
            bbarPrincipal.setDisable(false);
            hbBarreBouton.setDisable(false);
            tpEnvironnement.setDisable(false);

            ordPano.ajouteNouveauxPanos();
            apListePanoTriable = ordPano.getApListePanoramiques();
            apListePanoTriable.setMaxHeight(apListePanoTriable.getPrefHeight());
            apListePanoTriable.setMinHeight(apListePanoTriable.getPrefHeight());
            apListePanoTriable.setVisible(true);
            apParametresVisite.getChildren().remove(apListePanoTriable);
            apParametresVisite.getChildren().add(apListePanoTriable);
            apListePanoTriable.setLayoutX(40);
            apListePanoTriable.setLayoutY(130);
            apParametresVisite.setPrefHeight(120 + apListePanoTriable.getPrefHeight() + 20);
            if (apParametresVisite.isVisible()) {
                apParametresVisite.setMinHeight(120 + apListePanoTriable.getPrefHeight() + 20);
                apParametresVisite.setMaxHeight(120 + apListePanoTriable.getPrefHeight() + 20);
            }
            rafraichitListePano();

        }

    };
}