@Override
    protected Product doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception {
      final TargetProductSelectorModel model = getTargetProductSelector().getModel();
      pm.beginTask("Writing...", model.isOpenInAppSelected() ? 100 : 95);
      ProgressMonitorList.instance().add(pm); // NESTMOD
      saveTime = 0L;
      Product product = null;
      try {
        // free cache	// NESTMOD
        JAI.getDefaultInstance().getTileCache().flush();
        System.gc();

        executeStartTime = Calendar.getInstance().getTime();
        long t0 = System.currentTimeMillis();
        Operator operator = null;
        if (targetProduct.getProductReader() instanceof OperatorProductReader) {
          final OperatorProductReader opReader =
              (OperatorProductReader) targetProduct.getProductReader();
          if (opReader.getOperatorContext().getOperator() instanceof Output) {
            operator = opReader.getOperatorContext().getOperator();
          }
        }
        if (operator == null) {
          WriteOp writeOp =
              new WriteOp(targetProduct, model.getProductFile(), model.getFormatName());
          writeOp.setDeleteOutputOnFailure(true);
          writeOp.setWriteEntireTileRows(true);
          writeOp.setClearCacheAfterRowWrite(false);
          operator = writeOp;
        }
        final OperatorExecutor executor = OperatorExecutor.create(operator);
        executor.execute(SubProgressMonitor.create(pm, 95));

        saveTime = System.currentTimeMillis() - t0;
        File targetFile = model.getProductFile();
        if (model.isOpenInAppSelected() && targetFile.exists()) {
          product = ProductIO.readProduct(targetFile);
          if (product == null) {
            product = targetProduct; // todo - check - this cannot be ok!!! (nf)
          }
          pm.worked(5);
        }
      } finally {
        // free cache
        JAI.getDefaultInstance().getTileCache().flush();
        System.gc();

        pm.done();
        ProgressMonitorList.instance().remove(pm); // NESTMOD
        if (product != targetProduct) {
          targetProduct.dispose();
        }
      }
      return product;
    }
 public void mouseClicked(MouseEvent e) {
   int x = e.getX();
   int y = e.getY();
   int currentTabIndex = -1;
   int tabCount = tabPane.getTabCount();
   for (int i = 0; i < tabCount; i++) {
     if (rects[i].contains(x, y)) {
       currentTabIndex = i;
       break;
     } // if contains
   } // for i
   if (currentTabIndex >= 0) {
     Rectangle tabRect = rects[currentTabIndex];
     x = x - tabRect.x;
     y = y - tabRect.y;
     if ((x >= 5) && (x <= 15) && (y >= 5) && (y <= 15)) {
       try {
         tabbedPane.remove(currentTabIndex);
       } catch (Exception ex) {
         ex.printStackTrace();
       }
     } // if
   } // if currentTabIndex >= 0
   System.gc();
 } // mouseClicked
  public static void printImage(final Image image) {

    ImageHandler imh = new ImageHandler();

    imh.printImage(image, null);

    System.gc();
  }
  public static void printComponent(final java.awt.print.Printable p) {

    ImageHandler imh = new ImageHandler();

    imh.printComponent(p, null);

    System.gc();
  }
 public static void assertTiming(
     String message, long expected, int attempts, @NotNull Runnable actionToMeasure) {
   while (true) {
     attempts--;
     long duration = measure(actionToMeasure);
     try {
       assertTiming(message, expected, duration);
       break;
     } catch (AssertionFailedError e) {
       if (attempts == 0) throw e;
       System.gc();
       System.gc();
       System.gc();
       String s = "Another epic fail (remaining attempts: " + attempts + "): " + e.getMessage();
       TeamCityLogger.warning(s, null);
       System.err.println(s);
     }
   }
 }
 public static void main(String[] args) {
   System.gc();
   // Schedule a job for the event-dispatching thread:
   // creating and showing this application's GUI.
   javax.swing.SwingUtilities.invokeLater(
       new Runnable() {
         public void run() {
           createAndShowGUI();
         }
       });
 } // end of main
Ejemplo n.º 7
0
 public void update(GameEvent e) {
   this.m_map = e.getMap();
   if (e.getState() == Snake.DEAD) {
     int respond = JOptionPane.showConfirmDialog(this, "Snake is DEAD!!\nPlay again?");
     if (respond == JOptionPane.OK_OPTION) {
       this.m_isBegin = true;
       this.m_body = new GameBody(this, this.m_map, 125);
       System.gc();
     } else if (respond == JOptionPane.CANCEL_OPTION || respond == JOptionPane.NO_OPTION) {
       System.exit(0);
     }
   }
   this.repaint();
 }
Ejemplo n.º 8
0
  // Static main program for executing a test of the class.
  public static void main(String args[]) {
    // Define int variables.
    int width = 0;
    int height = 0;

    // If arguments are greater than zero.
    if (args.length > 0) {

      // If arguments are two.
      if (args.length >= 2) {
        // Use try block to parse for an integer.
        try {
          // Verify first argument is an integer.
          width = Integer.parseInt(args[0]);
          height = Integer.parseInt(args[1]);

          // Define a default instance of JMessagingFrame.
          JMessagingFrame f = new JMessagingFrame(width, height);

        } // Catch parsing failure exception.
        catch (NumberFormatException e) {
          // Print default runtime message.
          System.out.println("If you are testing the override constructor,");
          System.out.println("then you need to provide two integer values.");
        } // End try-catch block on integer parse.

      } // End of if two arguments provided.
      else // When there are less than or more than two arguments.
      {
        // Print default runtime message.
        System.out.println("If you are testing the override constructor,");
        System.out.println("then you need to provide two integer values.");
      } // End of else when there are less than or more than two arguments.

    } // End of else when there are two arguments.
    else // No arguments provided.
    {
      // Define a default instance of JMessagingFrame.
      JMessagingFrame f = new JMessagingFrame();

      // Clean-up by signaling the garbage collector.
      System.gc();
    } // End of else when no arguments are provided.
  } // End of static main.
Ejemplo n.º 9
0
 /**
  * This method represents the application code that we'd like to run on a separate thread. It
  * simulates slowly computing a value, in this case just a string 'All Done'. It updates the
  * progress bar every half second to remind the user that we're still busy.
  */
 Object doWork() {
   try {
     if (Thread.interrupted()) {
       throw new InterruptedException();
     }
     while (!this.state.terminator.isTerminated(this.state.optimizer.getPopulation())) {
       if (Thread.interrupted()) {
         throw new InterruptedException();
       }
       this.state.optimizer.optimize();
     }
     System.gc();
   } catch (InterruptedException e) {
     updateStatus("Interrupted", 0);
     return "Interrupted";
   }
   updateStatus("All Done", 0);
   return "All Done";
 }
Ejemplo n.º 10
0
  /**
   * This method represents the application code that we'd like to run on a separate thread. It
   * simulates slowly computing a value, in this case just a string 'All Done'. It updates the
   * progress bar every half second to remind the user that we're still busy.
   */
  public Object doWork() {
    try {
      this.optimizationParameters.saveInstance();
      if (this.show) {
        this.statusField.setText("Optimizing...");
      }

      RNG.setRandomSeed(optimizationParameters.getRandomSeed());
      // opening output file...
      if (!this.outputFileName.equalsIgnoreCase("none")) {
        String name = "";
        SimpleDateFormat formatter = new SimpleDateFormat("E'_'yyyy.MM.dd'_'HH.mm.ss");
        String startDate = formatter.format(new Date());
        name =
            this.outputPath
                + this.outputFileName
                + "_"
                + this.experimentName
                + "_"
                + startDate
                + ".dat";
        try {
          this.outputFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name)));
        } catch (FileNotFoundException e) {
          System.out.println("Could not open output file! Filename: " + name);
        }
      } else {
        this.outputFile = null;
      }

      // initialize problem
      this.optimizationParameters.getProblem().initializeProblem();
      this.optimizationParameters
          .getOptimizer()
          .setProblem(this.optimizationParameters.getProblem());
      // int optimizer and population
      // this.optimizationParameters.getOptimizer().initialize();

      // initialize the log data
      ArrayList tmpMultiRun = new ArrayList();
      this.performedRuns.add(tmpMultiRun);

      // something to log file
      // if (outputFile != null)
      // this.writeToFile(this.optimizationParameters.getOptimizer().getStringRepresentation());
      // this.writeToFile("Here i'll write something characterizing the algorithm.");

      for (int j = 0; j < this.multiRuns; j++) {
        this.optimizationParameters
            .getProblem()
            .initializeProblem(); // in the loop as well, dynamic probs may need that (MK)
        this.tmpData = new ArrayList<>();
        this.currentRun = j;
        if (this.show) {
          this.statusField.setText(
              "Optimizing Run " + (j + 1) + " of " + this.multiRuns + " Multi Runs...");
        }
        if (Thread.interrupted()) {
          throw new InterruptedException();
        }
        // write header to file
        this.writeToFile(
            " FitnessCalls\t Best\t Mean\t Worst \t"
                + BeanInspector.toString(
                    this.optimizationParameters.getProblem().getAdditionalDataHeader(),
                    '\t',
                    false,
                    ""));
        if ((this.continueFlag) && (this.backupPopulation != null)) {
          this.recentFunctionCalls += this.backupPopulation.getFunctionCalls();
          this.optimizationParameters.getOptimizer().getProblem().initializeProblem();
          this.optimizationParameters.getOptimizer().addPopulationChangedEventListener(null);
          this.optimizationParameters.getOptimizer().setPopulation(this.backupPopulation);
          this.optimizationParameters
              .getOptimizer()
              .getProblem()
              .evaluate(this.optimizationParameters.getOptimizer().getPopulation());
          this.optimizationParameters
              .getOptimizer()
              .getProblem()
              .evaluate(this.optimizationParameters.getOptimizer().getPopulation().getArchive());
          this.optimizationParameters
              .getOptimizer()
              .initializeByPopulation(this.backupPopulation, false);
          this.optimizationParameters.getOptimizer().getPopulation().setFunctionCalls(0);
          this.optimizationParameters.addPopulationChangedEventListener(this);
        } else {
          this.recentFunctionCalls = 0;
          this.optimizationParameters.getOptimizer().initialize();
        }
        // while (this.optimizationParameters.getOptimizer().getPopulation().getFunctionCalls() <
        // this.functionCalls) {
        while (!this.optimizationParameters
            .getTerminator()
            .isTerminated(this.optimizationParameters.getOptimizer().getPopulation())) {
          // System.out.println("Simulated Function calls "+
          // this.optimizer.getPopulation().getFunctionCalls());
          if (Thread.interrupted()) {
            throw new InterruptedException();
          }
          optimizationParameters.getOptimizer().optimize();
        }
        System.gc();
        // @TODO if you want the final report include this
        // this.writeToFile(this.optimizationParameters.getProblem().getStringRepresentationForProblem(this.optimizationParameters.getOptimizer()));
        tmpMultiRun.add(this.tmpData);
      }
      if (this.show) {
        this.plot.setInfoString(this.currentExperiment, this.experimentName, 0.5f);
      }
      if (this.show) {
        this.draw();
      }
      this.experimentName =
          this.optimizationParameters.getOptimizer().getName() + "-" + this.performedRuns.size();
    } catch (InterruptedException e) {
      updateStatus(0);
      if (this.show) {
        this.statusField.setText("Interrupted...");
      }
      return "Interrupted";
    }
    if (this.outputFile != null) {
      try {
        this.outputFile.close();
      } catch (IOException e) {
        System.out.println("Failed to close output file!");
      }
    }
    if (this.show) {
      for (int i = 0; i < this.multiRuns; i++) {
        this.plot.clearGraph(1000 + i);
      }
    }
    updateStatus(0);
    if (this.show) {
      this.statusField.setText("Finished...");
    }
    return "All Done";
  }
  private void execute() {

    gResult.clear();

    String sCmd = null;

    if (4096 <= ifHuge.length()) {
      sCmd = ifHuge;
    } else {
      sCmd = txtCommand.getText();
    }

    if (sCmd.startsWith("-->>>TEST<<<--")) {
      testPerformance();

      return;
    }

    String g[] = new String[1];

    try {
      lTime = System.currentTimeMillis();

      sStatement.execute(sCmd);

      int r = sStatement.getUpdateCount();

      if (r == -1) {
        formatResultSet(sStatement.getResultSet());
      } else {
        g[0] = "update count";

        gResult.setHead(g);

        g[0] = "" + r;

        gResult.addRow(g);
      }

      lTime = System.currentTimeMillis() - lTime;

      addToRecent(txtCommand.getText());
      gResult.fireTableChanged(null);
    } catch (SQLException e) {
      lTime = System.currentTimeMillis() - lTime;
      g[0] = "SQL Error";

      gResult.setHead(g);

      String s = e.getMessage();

      s += " / Error Code: " + e.getErrorCode();
      s += " / State: " + e.getSQLState();
      g[0] = s;

      gResult.addRow(g);
      gResult.fireTableChanged(null);
    }

    updateResult();
    System.gc();
  }
Ejemplo n.º 12
0
  /**
   * This method is required if the AlgorithmPerformed interface is implemented. It is called by the
   * algorithms when it has completed or failed to to complete, so that the dialog can be display
   * the result image and/or clean up.
   *
   * @param algorithm Algorithm that caused the event.
   */
  public void algorithmPerformed(AlgorithmBase algorithm) {
    ViewJFrameImage imageFrame = null;

    if (algorithm instanceof AlgorithmMosaicToSlices) {

      if ((mathAlgo.isCompleted() == true) && (mathAlgo.getResultImage() != null)) {

        // The algorithm has completed and produced a new image to be displayed.
        if (displayLoc == NEW) {

          try {
            resultImage = mathAlgo.getResultImage();

            new ViewJFrameImage(resultImage, null, new Dimension(610, 200));
          } catch (OutOfMemoryError error) {
            System.gc();
            MipavUtil.displayError("Out of memory: unable to open new frame");
          }
        } else {

          // These next lines set the titles in all frames where the source image is displayed to
          // image name so as to indicate that the image is now unlocked!
          // The image frames are enabled and then registed to the userinterface.
          resultImage = mathAlgo.getResultImage();

          Vector<ViewImageUpdateInterface> imageFrames = image.getImageFrameVector();

          for (int i = 0; i < imageFrames.size(); i++) {
            ((Frame) (imageFrames.elementAt(i))).setTitle(titles[i]);
            ((Frame) (imageFrames.elementAt(i))).setEnabled(true);

            if ((((Frame) (imageFrames.elementAt(i))) != parentFrame) && (parentFrame != null)) {
              userInterface.registerFrame((Frame) (imageFrames.elementAt(i)));
            }
          }

          Point pt;

          if (parentFrame != null) {
            pt = ((ViewJFrameBase) parentFrame).getLocation();
          } else {
            pt =
                new Point(
                    Toolkit.getDefaultToolkit().getScreenSize().width / 2,
                    Toolkit.getDefaultToolkit().getScreenSize().height / 2);
          }

          imageFrame = new ViewJFrameImage(resultImage, null, new Dimension(pt.x, pt.y));

          if (parentFrame != null) {
            ((ViewJFrameBase) parentFrame).close();
          } else {
            ((ViewJFrameBase) image.getParentFrame()).close();
          }

          // Not so sure about this.
          if (image.getLightBoxFrame() != null) {

            try {
              pt = image.getLightBoxFrame().getLocation();
              image.getLightBoxFrame().close();
              new ViewJFrameLightBox(
                  imageFrame,
                  "LightBox",
                  resultImage,
                  imageFrame.getComponentImage().getLUTa(),
                  imageFrame.getComponentImage().getImageB(),
                  imageFrame.getComponentImage().getLUTb(),
                  imageFrame.getComponentImage().getResolutionX(),
                  imageFrame.getComponentImage().getResolutionY(),
                  new Dimension(pt.x, pt.y),
                  imageFrame.getControls(),
                  imageFrame.getVOIManager());
            } catch (OutOfMemoryError error) {
              MipavUtil.displayError("Out of memory: unable to open new frame");
            }
          }
        }
      } else if (resultImage == null) {

        // These next lines set the titles in all frames where the source image is displayed to
        // image name so as to indicate that the image is now unlocked!
        // The image frames are enabled and then registered to the userinterface.
        /*Vector imageFrames = imageA.getImageFrameVector();

        for (int i = 0; i < imageFrames.size(); i++) {
            ((Frame) (imageFrames.elementAt(i))).setTitle(titles[i]);
            ((Frame) (imageFrames.elementAt(i))).setEnabled(true);

            if (((Frame) (imageFrames.elementAt(i))) != parentFrame) {
                userInterface.registerFrame((Frame) (imageFrames.elementAt(i)));

            }
        }*/

        if (parentFrame != null) {
          userInterface.registerFrame(parentFrame);
        }

        image.notifyImageDisplayListeners(null, true);
      } else if (resultImage != null) {

        // algorithm failed but result image still has garbage
        resultImage.disposeLocal(); // clean up memory
        System.gc();
      }
    }

    if (algorithm.isCompleted()) {
      insertScriptLine();
    }

    mathAlgo.finalize();
    mathAlgo = null;
    dispose();
  }
  /**
   * Use the GUI results to set up the variables needed to run the algorithm.
   *
   * @return <code>true</code> if parameters set successfully, <code>false</code> otherwise.
   */
  private boolean setVariables() {
    String tmpStr;

    System.gc();

    if (replaceImage.isSelected()) {
      displayLoc = REPLACE;
    } else if (newImage.isSelected()) {
      displayLoc = NEW;
    }

    tmpStr = textSearchWindowSide.getText();

    if (testParameter(tmpStr, 5, 101)) {
      searchWindowSide = Integer.valueOf(tmpStr).intValue();
    } else {
      MipavUtil.displayError("Search window side must be between 5 and 101");
      textSearchWindowSide.requestFocus();
      textSearchWindowSide.selectAll();

      return false;
    }

    if ((searchWindowSide % 2) == 0) {
      MipavUtil.displayError("Search window side must be an odd number");
      textSearchWindowSide.requestFocus();
      textSearchWindowSide.selectAll();
      return false;
    }

    tmpStr = textSimilarityWindowSide.getText();

    if (testParameter(tmpStr, 3, 99)) {
      similarityWindowSide = Integer.valueOf(tmpStr).intValue();
    } else {
      MipavUtil.displayError("Similarity window side must be between 3 and 99");
      textSimilarityWindowSide.requestFocus();
      textSimilarityWindowSide.selectAll();

      return false;
    }

    if ((similarityWindowSide % 2) == 0) {
      MipavUtil.displayError("Similarity window side must be an odd number");
      textSimilarityWindowSide.requestFocus();
      textSimilarityWindowSide.selectAll();
      return false;
    }

    if (similarityWindowSide >= searchWindowSide) {
      MipavUtil.displayError("Similarity window side must be less than search window side");
      textSimilarityWindowSide.requestFocus();
      textSimilarityWindowSide.selectAll();
      return false;
    }

    tmpStr = textNoiseStandardDeviation.getText();

    if (testParameter(tmpStr, 0.001, 1000.0)) {
      noiseStandardDeviation = Float.valueOf(tmpStr).floatValue();
    } else {
      MipavUtil.displayError("Radius must be between 0.001 and 1000.0");
      textNoiseStandardDeviation.requestFocus();
      textNoiseStandardDeviation.selectAll();

      return false;
    }

    doRician = doRicianCheckBox.isSelected();

    if (doRician) {
      tmpStr = textDegree.getText();
      if (testParameter(tmpStr, 1.0, 10.0)) {
        degreeOfFiltering = Float.valueOf(tmpStr).floatValue();
      } else {
        MipavUtil.displayError("Degree of filtering must be between 1.0 and 10.0");
        textDegree.requestFocus();
        textDegree.selectAll();
      }
    }

    if (image.getNDims() > 2) {
      image25D = image25DCheckBox.isSelected();
    }

    return true;
  }
  /**
   * Initializes the GUI by creating the components, placing them in the dialog, and displaying
   * them.
   */
  private void init() {
    setForeground(Color.black);

    setTitle("Nonlocal Means Filter");

    JPanel mainPanel;
    mainPanel = new JPanel();
    mainPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
    mainPanel.setLayout(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.weightx = 1;
    gbc.insets = new Insets(3, 3, 3, 3);
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.HORIZONTAL;

    paramPanel = new JPanel(new GridBagLayout());
    paramPanel.setForeground(Color.black);
    paramPanel.setBorder(buildTitledBorder("Parameters"));
    mainPanel.add(paramPanel, gbc);

    GridBagConstraints gbc2 = new GridBagConstraints();
    gbc2.gridwidth = 1;
    gbc2.gridheight = 1;
    gbc2.anchor = GridBagConstraints.WEST;
    gbc2.weightx = 1;
    gbc2.insets = new Insets(3, 3, 3, 3);
    gbc2.gridx = 0;
    gbc2.gridy = 0;
    gbc2.fill = GridBagConstraints.HORIZONTAL;

    labelSearchWindowSide = createLabel("Search window side (odd)");

    paramPanel.add(labelSearchWindowSide, gbc2);

    gbc2.gridx = 1;
    textSearchWindowSide = createTextField("15");
    paramPanel.add(textSearchWindowSide, gbc2);

    gbc2.gridx = 0;
    gbc2.gridy = 1;
    labelSimilarityWindowSide = createLabel("Similarity window side (odd) ");
    paramPanel.add(labelSimilarityWindowSide, gbc2);

    gbc2.gridx = 1;
    textSimilarityWindowSide = createTextField("7");
    paramPanel.add(textSimilarityWindowSide, gbc2);

    gbc2.gridx = 0;
    gbc2.gridy = 2;
    labelNoiseStandardDeviation = createLabel("Noise standard deviation ");
    paramPanel.add(labelNoiseStandardDeviation, gbc2);

    gbc2.gridx = 1;
    textNoiseStandardDeviation = createTextField("10.0");
    paramPanel.add(textNoiseStandardDeviation, gbc2);

    gbc2.gridx = 0;
    gbc2.gridy = 3;
    labelDegree = createLabel("Degree of filtering ");
    labelDegree.setEnabled(doRician);
    paramPanel.add(labelDegree, gbc2);

    gbc2.gridx = 1;
    textDegree = createTextField("1.414");
    textDegree.setEnabled(doRician);
    paramPanel.add(textDegree, gbc2);

    gbc2.gridx = 0;
    gbc2.gridy = 4;
    doRicianCheckBox = new JCheckBox("Deal with Rician noise in MRI");
    doRicianCheckBox.setFont(serif12);
    doRicianCheckBox.setSelected(false);
    doRicianCheckBox.addActionListener(this);
    paramPanel.add(doRicianCheckBox, gbc2);

    if (image.getNDims() > 2) {
      gbc2.gridx = 0;
      gbc2.gridy = 5;
      gbc2.gridwidth = 2;

      image25DCheckBox = new JCheckBox("Process each slice independently (2.5D)");
      image25DCheckBox.setFont(serif12);
      paramPanel.add(image25DCheckBox, gbc2);
      image25DCheckBox.setSelected(false);
    } // if (image.getNDims > 2)

    JPanel outputOptPanel = new JPanel(new GridLayout(1, 2));
    destinationPanel = new JPanel(new BorderLayout());
    destinationPanel.setForeground(Color.black);
    destinationPanel.setBorder(buildTitledBorder("Destination"));
    outputOptPanel.add(destinationPanel);

    destinationGroup = new ButtonGroup();
    newImage = new JRadioButton("New image", true);
    newImage.setBounds(10, 16, 120, 25);
    newImage.setFont(serif12);
    destinationGroup.add(newImage);
    destinationPanel.add(newImage, BorderLayout.NORTH);

    replaceImage = new JRadioButton("Replace image", false);
    replaceImage.setFont(serif12);
    destinationGroup.add(replaceImage);
    destinationPanel.add(replaceImage, BorderLayout.CENTER);

    // Only if the image is unlocked can it be replaced.
    if (image.getLockStatus() == ModelStorageBase.UNLOCKED) {
      replaceImage.setEnabled(true);
    } else {
      replaceImage.setEnabled(false);
    }

    gbc.gridx = 0;
    gbc.gridy = 1;
    mainPanel.add(outputOptPanel, gbc);

    mainDialogPanel.add(mainPanel, BorderLayout.CENTER);
    mainDialogPanel.add(buildButtons(), BorderLayout.SOUTH);

    getContentPane().add(mainDialogPanel);

    pack();
    setResizable(true);
    // setVisible(true);

    System.gc();
  }
Ejemplo n.º 15
0
  /**
   * Once all the necessary variables are set, call the Concat algorithm based on what type of image
   * this is and whether or not there is a separate destination image.
   */
  protected void callAlgorithm() {
    int destExtents[] = new int[3];
    ModelImage destImage = null;

    destExtents[0] = subXDim;
    destExtents[1] = subYDim;
    destExtents[2] = numberOfImagesInMosaic;

    destImage =
        new ModelImage(
            image.getType(), destExtents, makeImageName(image.getImageName(), "_mosaic_to_slices"));

    try {

      // Make algorithm
      mathAlgo = new AlgorithmMosaicToSlices(image, destImage);

      // This is very important. Adding this object as a listener allows the algorithm to
      // notify this object when it has completed of failed. See algorithm performed event.
      // This is made possible by implementing AlgorithmedPerformed interface
      mathAlgo.addListener(this);

      createProgressBar(image.getImageName(), mathAlgo);

      // Hide dialog
      setVisible(false);

      if (displayLoc == REPLACE) {

        // These next lines set the titles in all frames where the source image is displayed to
        // "locked - " image name so as to indicate that the image is now read/write locked!
        // The image frames are disabled and then unregisted from the userinterface until the
        // algorithm has completed.
        Vector<ViewImageUpdateInterface> imageFrames = image.getImageFrameVector();
        titles = new String[imageFrames.size()];

        for (int i = 0; i < imageFrames.size(); i++) {
          titles[i] = ((Frame) (imageFrames.elementAt(i))).getTitle();
          ((Frame) (imageFrames.elementAt(i))).setTitle("Locked: " + titles[i]);
          ((Frame) (imageFrames.elementAt(i))).setEnabled(false);
          userInterface.unregisterFrame((Frame) (imageFrames.elementAt(i)));
        }
      }

      if (isRunInSeparateThread()) {

        // Start the thread as a low priority because we wish to still have user interface work
        // fast.
        if (mathAlgo.startMethod(Thread.MIN_PRIORITY) == false) {
          MipavUtil.displayError("A thread is already running on this object");
        }

      } else {

        mathAlgo.run();
      }
    } catch (OutOfMemoryError x) {
      System.gc();
      MipavUtil.displayError("Dialog Concatenation: unable to allocate enough memory");

      return;
    }
  }
Ejemplo n.º 16
0
  protected void process() {
    int i, j, len, ch, chunkLength;
    long progOff, progLen;
    float f1;

    // io
    AudioFile inF = null;
    AudioFile outF = null;
    AudioFileDescr inStream;
    AudioFileDescr outStream;
    FloatFile[] floatF = null;
    File tempFile[] = null;

    // buffers
    float[][] inBuf, outBuf;
    float[] win;
    float[] convBuf1, convBuf2;
    float[] tempFlt;

    int inChanNum, inLength, inputStep, outputStep, winSize;
    int transLen, skip, inputLen, outputLen, fltLen;
    int framesRead, framesWritten;
    float warp, a1, b0, b1, x0, x1, y0, y1, b0init;

    Param ampRef = new Param(1.0, Param.ABS_AMP); // transform-Referenz
    Param peakGain;
    float gain = 1.0f; // gain abs amp
    float maxAmp = 0.0f;

    PathField ggOutput;

    topLevel:
    try {

      // ---- open input, output ----

      // input
      inF = AudioFile.openAsRead(new File(pr.text[PR_INPUTFILE]));
      inStream = inF.getDescr();
      inChanNum = inStream.channels;
      inLength = (int) inStream.length;
      // this helps to prevent errors from empty files!
      if ((inLength * inChanNum) < 1) throw new EOFException(ERR_EMPTY);
      // .... check running ....
      if (!threadRunning) break topLevel;

      // output
      ggOutput = (PathField) gui.getItemObj(GG_OUTPUTFILE);
      if (ggOutput == null) throw new IOException(ERR_MISSINGPROP);
      outStream = new AudioFileDescr(inStream);
      ggOutput.fillStream(outStream);
      outF = AudioFile.openAsWrite(outStream);
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- parameter inits ----

      warp =
          Math.max(-0.98f, Math.min(0.98f, (float) (pr.para[PR_WARP].val / 100))); // DAFx2000 'b'
      f1 = (1.0f - warp) / (1.0f + warp); // DAFx2000 (25)
      winSize = 32 << pr.intg[PR_FRAMESIZE]; // DAFx2000 'N'
      j = winSize >> 1;
      transLen = (int) (f1 * winSize + 0.5f); // DAFx2000 'P' (26)
      i = pr.intg[PR_OVERLAP] + 1;
      while (((float) transLen / (float) i) > j) i++;
      inputStep = (int) (((float) transLen / (float) i) + 0.5f); // DAFx2000 'L'
      fltLen = Math.max(winSize, transLen);
      // System.out.println( "inputStep "+inputStep+"; winSize "+winSize+"; transLen "+transLen+";
      // fltLen "+fltLen+"; warp "+warp+"; � "+f1 );
      win = Filter.createFullWindow(winSize, Filter.WIN_HANNING); // DAFx2000 (27)
      outputStep = inputStep;

      b0init = (float) Math.sqrt(1.0f - warp * warp);

      progOff = 0;
      progLen = (long) inLength * (2 + inChanNum); // + winSize;

      tempFlt = new float[fltLen];
      inputLen = winSize + inputStep;
      inBuf = new float[inChanNum][inputLen];
      outputLen = transLen + outputStep;
      outBuf = new float[inChanNum][outputLen];

      // normalization requires temp files
      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        tempFile = new File[inChanNum];
        floatF = new FloatFile[inChanNum];
        for (ch = 0; ch < inChanNum; ch++) { // first zero them because an exception might be thrown
          tempFile[ch] = null;
          floatF[ch] = null;
        }
        for (ch = 0; ch < inChanNum; ch++) {
          tempFile[ch] = IOUtil.createTempFile();
          floatF[ch] = new FloatFile(tempFile[ch], GenericFile.MODE_OUTPUT);
        }
        progLen += (long) inLength;
      } else {
        gain = (float) ((Param.transform(pr.para[PR_GAIN], Param.ABS_AMP, ampRef, null)).val);
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ----==================== the real stuff ====================----

      framesRead = 0;
      framesWritten = 0;
      skip = 0;

      while (threadRunning && (framesWritten < inLength)) {

        chunkLength = Math.min(inputLen, inLength - framesRead + skip);
        // ---- read input chunk ----
        len = Math.max(0, chunkLength - skip);
        inF.readFrames(inBuf, skip, len);
        framesRead += len;
        progOff += len;
        //				off			+= len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
        // .... check running ....
        if (!threadRunning) break topLevel;

        // zero padding
        if (chunkLength < inputLen) {
          for (ch = 0; ch < inChanNum; ch++) {
            convBuf1 = inBuf[ch];
            for (i = chunkLength; i < convBuf1.length; i++) {
              convBuf1[i] = 0.0f;
            }
          }
        }

        for (ch = 0; threadRunning && (ch < inChanNum); ch++) {
          convBuf1 = inBuf[ch];
          convBuf2 = outBuf[ch];

          for (i = 0, j = fltLen; i < winSize; i++) {
            tempFlt[--j] = convBuf1[i] * win[i];
          }
          while (j > 0) {
            tempFlt[--j] = 0.0f;
          }

          a1 = -warp; // inital allpass
          b0 = b0init;
          b1 = 0.0f;
          for (j = 0; j < transLen; j++) {
            x1 = 0.0f;
            y1 = 0.0f;

            //						for( i = 0; i < transLen; i++ ) {		// DAFx2000 (2 resp. 3)
            for (i = 0; i < fltLen; i++) { // DAFx2000 (2 resp. 3)
              x0 = tempFlt[i];
              y0 = b0 * x0 + b1 * x1 - a1 * y1;
              tempFlt[i] = y0; // (work with double precision while computing cascades)
              y1 = y0;
              x1 = x0;
            }

            a1 = -warp; // cascaded allpasses
            b0 = -warp;
            b1 = 1.0f;

            convBuf2[j] += (float) y1;
          }
          // .... progress ....
          progOff += chunkLength - skip;
          setProgression((float) progOff / (float) progLen);
        } // for channels
        // .... check running ....
        if (!threadRunning) break topLevel;

        chunkLength = Math.min(outputStep, inLength - framesWritten);
        // ---- write output chunk ----
        if (floatF != null) {
          for (ch = 0; ch < inChanNum; ch++) {
            floatF[ch].writeFloats(outBuf[ch], 0, chunkLength);
          }
          progOff += chunkLength;
          //					off			  += len;
          framesWritten += chunkLength;
          // .... progress ....
          setProgression((float) progOff / (float) progLen);

        } else {
          for (ch = 0; ch < inChanNum; ch++) {
            Util.mult(outBuf[ch], 0, chunkLength, gain);
          }
          outF.writeFrames(outBuf, 0, chunkLength);
          progOff += chunkLength;
          //					off			  += len;
          framesWritten += chunkLength;
          // .... progress ....
          setProgression((float) progOff / (float) progLen);
        }
        // .... check running ....
        if (!threadRunning) break topLevel;

        // check max amp
        for (ch = 0; ch < inChanNum; ch++) {
          convBuf1 = outBuf[ch];
          for (i = 0; i < chunkLength; i++) {
            f1 = Math.abs(convBuf1[i]);
            if (f1 > maxAmp) {
              maxAmp = f1;
            }
          }
        }

        // overlaps
        skip = winSize;
        for (ch = 0; ch < inChanNum; ch++) {
          System.arraycopy(inBuf[ch], inputStep, inBuf[ch], 0, winSize);
          convBuf1 = outBuf[ch];
          System.arraycopy(convBuf1, outputStep, convBuf1, 0, transLen);
          for (i = transLen; i < outputLen; ) {
            convBuf1[i++] = 0.0f;
          }
        }
      } // until framesWritten == outLength
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ----==================== normalize output ====================----

      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        peakGain = new Param((double) maxAmp, Param.ABS_AMP);
        gain =
            (float)
                (Param.transform(
                        pr.para[PR_GAIN],
                        Param.ABS_AMP,
                        new Param(1.0 / peakGain.val, peakGain.unit),
                        null))
                    .val;
        normalizeAudioFile(floatF, outF, inBuf, gain, 1.0f);
        maxAmp *= gain;

        for (ch = 0; ch < inChanNum; ch++) {
          floatF[ch].cleanUp();
          floatF[ch] = null;
          tempFile[ch].delete();
          tempFile[ch] = null;
        }
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- Finish ----

      outF.close();
      outF = null;
      outStream = null;
      inF.close();
      inF = null;
      inStream = null;
      inBuf = null;

      // inform about clipping/ low level
      handleClipping(maxAmp);
    } catch (IOException e1) {
      setError(e1);
    } catch (OutOfMemoryError e2) {
      inStream = null;
      outStream = null;
      inBuf = null;
      convBuf1 = null;
      convBuf2 = null;
      System.gc();

      setError(new Exception(ERR_MEMORY));
      ;
    }

    // ---- cleanup (topLevel) ----
    if (inF != null) {
      inF.cleanUp();
      inF = null;
    }
    if (outF != null) {
      outF.cleanUp();
      outF = null;
    }
    if (floatF != null) {
      for (ch = 0; ch < floatF.length; ch++) {
        if (floatF[ch] != null) {
          floatF[ch].cleanUp();
          floatF[ch] = null;
        }
        if (tempFile[ch] != null) {
          tempFile[ch].delete();
          tempFile[ch] = null;
        }
      }
    }
  } // process()
  /** Sets up the GUI (panels, buttons, etc) and displays it on the screen. */
  private void init() {
    DecimalFormat df;
    int xUnits;
    String unitStr;
    String distStr;
    setForeground(Color.black);
    setTitle("Center Distances version 2  07/14/08");

    df = new DecimalFormat("0.000E0");

    GridBagConstraints gbc = new GridBagConstraints();
    int yPos = 0;
    gbc.gridwidth = 1;
    gbc.gridheight = 1;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.weightx = 1;
    gbc.insets = new Insets(3, 3, 3, 3);
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.gridx = 0;
    gbc.gridy = yPos++;

    JPanel mainPanel = new JPanel(new GridBagLayout());
    mainPanel.setForeground(Color.black);
    mainPanel.setBorder(buildTitledBorder("Input parameters"));

    blueMinLabel = new JLabel("Minimum number of blue pixels per nucleus");
    blueMinLabel.setForeground(Color.black);
    blueMinLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(blueMinLabel, gbc);

    blueMinText = new JTextField(5);
    if (image.getNDims() == 2) {
      blueMinText.setText("1000");
    } else {
      blueMinText.setText("20000");
    }
    blueMinText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(blueMinText, gbc);

    redMinLabel = new JLabel("Minimum red pixel count");
    redMinLabel.setForeground(Color.black);
    redMinLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(redMinLabel, gbc);

    redMinText = new JTextField(5);
    redMinText.setText("50");
    redMinText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(redMinText, gbc);

    redFractionLabel = new JLabel("Fraction of red pixels to consider");
    redFractionLabel.setForeground(Color.black);
    redFractionLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(redFractionLabel, gbc);

    redFractionText = new JTextField(5);
    redFractionText.setText("0.15");
    redFractionText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(redFractionText, gbc);

    xUnits = image.getFileInfo(0).getUnitsOfMeasure()[0];
    if (xUnits != Unit.UNKNOWN_MEASURE.getLegacyNum()) {
      unitStr = (Unit.getUnitFromLegacyNum(xUnits)).toString();
      greenMergingLabel = new JLabel("Green merging radius around peak (" + unitStr + ")");
    } else {
      greenMergingLabel = new JLabel("Green merging radius around peak");
    }
    greenMergingLabel.setForeground(Color.black);
    greenMergingLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(greenMergingLabel, gbc);

    if (image.getNDims() == 2) {
      // mergingDistance = 8.0f * image.getFileInfo(0).getResolutions()[0];
      mergingDistance = 0.0f;
    } else {
      // mergingDistance = 4.0f * image.getFileInfo(0).getResolutions()[0];
      mergingDistance = 0.0f;
    }
    distStr = df.format(mergingDistance);
    greenMergingText = new JTextField(10);
    greenMergingText.setText(distStr);
    greenMergingText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(greenMergingText, gbc);

    greenMinLabel = new JLabel("Minimum green pixel count");
    greenMinLabel.setForeground(Color.black);
    greenMinLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(greenMinLabel, gbc);

    greenMinText = new JTextField(5);
    greenMinText.setText("10");
    greenMinText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(greenMinText, gbc);

    greenFractionLabel = new JLabel("Fraction of green pixels to consider");
    greenFractionLabel.setForeground(Color.black);
    greenFractionLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(greenFractionLabel, gbc);

    greenFractionText = new JTextField(5);
    greenFractionText.setText("0.01");
    greenFractionText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(greenFractionText, gbc);

    greenRegionsLabel = new JLabel("Green regions per cell");
    greenRegionsLabel.setForeground(Color.black);
    greenRegionsLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(greenRegionsLabel, gbc);

    JPanel buttonPanel = new JPanel(new GridBagLayout());

    greenGroup = new ButtonGroup();

    oneButton = new JRadioButton("1", false);
    oneButton.setForeground(Color.black);
    oneButton.setFont(serif12);
    greenGroup.add(oneButton);
    gbc.gridx = 0;
    gbc.gridy = 0;
    buttonPanel.add(oneButton, gbc);

    twoButton = new JRadioButton("2", true);
    twoButton.setForeground(Color.black);
    twoButton.setFont(serif12);
    greenGroup.add(twoButton);
    gbc.gridx = 1;
    gbc.gridy = 0;
    buttonPanel.add(twoButton, gbc);

    threeButton = new JRadioButton("3", false);
    threeButton.setForeground(Color.black);
    threeButton.setFont(serif12);
    greenGroup.add(threeButton);
    gbc.gridx = 2;
    gbc.gridy = 0;
    buttonPanel.add(threeButton, gbc);

    fourButton = new JRadioButton("4", false);
    fourButton.setForeground(Color.black);
    fourButton.setFont(serif12);
    greenGroup.add(fourButton);
    gbc.gridx = 3;
    gbc.gridy = 0;
    buttonPanel.add(fourButton, gbc);

    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(buttonPanel, gbc);

    twoBox = new JCheckBox("Use 2 top gray levels in green segmentation", true);
    twoBox.setForeground(Color.black);
    twoBox.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos++;
    mainPanel.add(twoBox, gbc);

    blueValueLabel =
        new JLabel("Fraction of blue transition from image min to max at nucleus boundary");
    blueValueLabel.setForeground(Color.black);
    blueValueLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(blueValueLabel, gbc);

    blueValueText = new JTextField(5);
    blueValueText.setText("0.15");
    blueValueText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(blueValueText, gbc);

    blueSmoothBox = new JCheckBox("Smooth blue VOI contours with AlgorithmBSmooth", true);
    blueSmoothBox.setForeground(Color.black);
    blueSmoothBox.setFont(serif12);
    blueSmoothBox.addActionListener(this);
    gbc.gridx = 0;
    gbc.gridy = yPos++;
    mainPanel.add(blueSmoothBox, gbc);

    interpolationLabel = new JLabel("Number of interpolation points determined by divisor (> 1.0)");
    interpolationLabel.setForeground(Color.black);
    interpolationLabel.setFont(serif12);
    gbc.gridx = 0;
    gbc.gridy = yPos;
    mainPanel.add(interpolationLabel, gbc);

    interpolationText = new JTextField(5);
    interpolationText.setText("24.0");
    interpolationText.setFont(serif12);
    gbc.gridx = 1;
    gbc.gridy = yPos++;
    mainPanel.add(interpolationText, gbc);

    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(buildButtons(), BorderLayout.SOUTH);

    pack();
    setVisible(true);
    setResizable(false);
    System.gc();
  } // end init()
Ejemplo n.º 18
0
  protected void process() {
    int i, j, ch, len, off, chunkLength;
    long progOff, progLen;
    float f1, f2;
    double d1;
    boolean extraAudioFile;

    // io
    AudioFile inF = null;
    AudioFile outF = null;
    AudioFile envInF = null;
    AudioFile envOutF = null;
    AudioFileDescr inStream = null;
    AudioFileDescr outStream = null;
    AudioFileDescr envInStream = null;
    AudioFileDescr envOutStream = null;
    FloatFile[] outFloatF = null;
    FloatFile[] envFloatF = null;
    File outTempFile[] = null;
    File envTempFile[] = null;
    int inChanNum, outChanNum, envInChanNum, envOutChanNum, shapeChanNum;

    int[][] shapeChan = null;
    int[][] inChan = null;
    float[][] shapeChanWeight = null;
    float[][] inChanWeight = null;

    // buffers
    float[][] inBuf = null; // Sound-In
    float[][] outBuf = null; // Sound-Out
    float[][] inEnvBuf = null; // Envelope of Input
    float[][] shapeEnvBuf = null; // Envelope of Shaper
    float[][] envInBuf = null; // Direct-In of Shaper-File
    float[] convBuf1, convBuf2;

    int inLength, outLength, envInLength, envOutLength;
    int framesRead, framesWritten; // re sound-files
    int framesRead2, framesWritten2; // re env-files

    Param ampRef = new Param(1.0, Param.ABS_AMP); // transform-Referenz
    Param peakGain;
    float gain = 1.0f; // gain abs amp
    float envGain = 1.0f; // gain abs amp
    float maxAmp = 0.0f;
    float envMaxAmp = 0.0f;

    float maxChange;
    int average, avrOff;

    double[] inEnergy, envInEnergy;

    PathField ggOutput;

    topLevel:
    try {

      // ---- open input, output; init ----

      // input
      inF = AudioFile.openAsRead(new File(pr.text[PR_INPUTFILE]));
      inStream = inF.getDescr();
      inChanNum = inStream.channels;
      inLength = (int) inStream.length;
      // this helps to prevent errors from empty files!
      if ((inLength < 1) || (inChanNum < 1)) throw new EOFException(ERR_EMPTY);
      // .... check running ....
      if (!threadRunning) break topLevel;

      envInLength = 0;
      envInChanNum = inChanNum;
      shapeChanNum = 0;

      // shape input
      switch (pr.intg[PR_ENVSOURCE]) {
        case SRC_SOUNDFILE:
        case SRC_ENVFILE:
          envInF = AudioFile.openAsRead(new File(pr.text[PR_ENVINFILE]));
          envInStream = envInF.getDescr();
          envInChanNum = envInStream.channels;
          shapeChanNum = envInChanNum;
          envInLength = (int) envInStream.length;
          // this helps to prevent errors from empty files!
          if ((envInLength < 1) || (envInChanNum < 1)) throw new EOFException(ERR_EMPTY);

          i = Math.min(inLength, envInLength);
          inLength = i;
          envInLength = i;
          break;

        case SRC_ENV:
          if (pr.bool[PR_RIGHTCHAN]) {
            shapeChanNum = 2;
            envInChanNum = Math.max(envInChanNum, shapeChanNum); // ggf. mono => stereo
          } else {
            shapeChanNum = 1;
          }
          break;

        case SRC_INPUT:
          shapeChanNum = inChanNum;
          break;
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      outChanNum = Math.max(inChanNum, envInChanNum);
      outLength = inLength;

      shapeChan = new int[outChanNum][2];
      shapeChanWeight = new float[outChanNum][2];
      inChan = new int[outChanNum][2];
      inChanWeight = new float[outChanNum][2];
      extraAudioFile =
          (envInF != null) && (pr.intg[PR_ENVSOURCE] == SRC_SOUNDFILE); // not if SRC_ENVFILE!!!

      // calc weights
      for (ch = 0; ch < outChanNum; ch++) {
        if (shapeChanNum == 1) {
          shapeChan[ch][0] = 0;
          shapeChan[ch][1] = 0;
          shapeChanWeight[ch][0] = 1.0f;
          shapeChanWeight[ch][1] = 0.0f;
        } else {
          f1 = ((float) ch / (float) (outChanNum - 1)) * (float) (shapeChanNum - 1);
          shapeChan[ch][0] = (int) f1; // Math.max verhindert ArrayIndex-Fehler
          shapeChan[ch][1] = Math.min((int) f1 + 1, shapeChanNum - 1); // (Weight ist dabei eh Null)
          f1 %= 1.0f;
          shapeChanWeight[ch][0] = 1.0f - f1;
          shapeChanWeight[ch][1] = f1;
        }
        if (inChanNum == 1) {
          inChan[ch][0] = 0;
          inChan[ch][1] = 0;
          inChanWeight[ch][0] = 1.0f;
          inChanWeight[ch][1] = 0.0f;
        } else {
          f1 = ((float) ch / (float) (outChanNum - 1)) * (float) (inChanNum - 1);
          inChan[ch][0] = (int) f1;
          inChan[ch][1] = Math.min((int) f1 + 1, inChanNum - 1);
          f1 %= 1.0f;
          inChanWeight[ch][0] = 1.0f - f1;
          inChanWeight[ch][1] = f1;
        }
        /*
        for( i = 0; i < 2; i++ ) {
        	System.out.println( "shapeChan["+ch+"]["+i+"] = "+shapeChan[ch][i] );
        	System.out.println( "shapeWeig["+ch+"]["+i+"] = "+shapeChanWeight[ch][i] );
        	System.out.println( "inputChan["+ch+"]["+i+"] = "+inChan[ch][i] );
        	System.out.println( "inputWeig["+ch+"]["+i+"] = "+inChanWeight[ch][i] );
        }
        */
      }

      // output
      ggOutput = (PathField) gui.getItemObj(GG_OUTPUTFILE);
      if (ggOutput == null) throw new IOException(ERR_MISSINGPROP);
      outStream = new AudioFileDescr(inStream);
      ggOutput.fillStream(outStream);
      outStream.channels = outChanNum;
      outF = AudioFile.openAsWrite(outStream);
      // .... check running ....
      if (!threadRunning) break topLevel;

      envOutLength = 0;
      envOutChanNum = 0;

      // envelope output
      if (pr.bool[PR_ENVOUTPUT]) {
        ggOutput = (PathField) gui.getItemObj(GG_ENVOUTFILE);
        if (ggOutput == null) throw new IOException(ERR_MISSINGPROP);
        envOutStream = new AudioFileDescr(inStream);
        ggOutput.fillStream(envOutStream);
        envOutStream.file = new File(pr.text[PR_ENVOUTFILE]);
        envOutF = AudioFile.openAsWrite(envOutStream);
        envOutLength = inLength;
        envOutChanNum = inChanNum;
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // average buffer size
      d1 =
          Param.transform(
                  pr.para[PR_AVERAGE],
                  Param.ABS_MS,
                  new Param(AudioFileDescr.samplesToMillis(inStream, inLength), Param.ABS_MS),
                  null)
              .val; // average in millis
      average = ((int) (AudioFileDescr.millisToSamples(inStream, d1) + 0.5) & ~1) + 1; // always odd
      avrOff = (average >> 1) + 1; // first element needed for subtraction (see calcEnv())

      progOff = 0;
      progLen =
          (long) Math.max(average - avrOff, inLength)
              + (long) (extraAudioFile ? Math.max(average - avrOff, envInLength) : envInLength)
              + (long) outLength
              + (long) envOutLength;

      // normalization requires temp files
      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        outTempFile = new File[outChanNum];
        outFloatF = new FloatFile[outChanNum];
        for (ch = 0;
            ch < outChanNum;
            ch++) { // first zero them because an exception might be thrown
          outTempFile[ch] = null;
          outFloatF[ch] = null;
        }
        for (ch = 0; ch < outChanNum; ch++) {
          outTempFile[ch] = IOUtil.createTempFile();
          outFloatF[ch] = new FloatFile(outTempFile[ch], GenericFile.MODE_OUTPUT);
        }
        progLen += (long) outLength;
      } else {
        gain = (float) (Param.transform(pr.para[PR_GAIN], Param.ABS_AMP, ampRef, null)).val;
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // normalization requires temp files
      if (pr.intg[PR_ENVGAINTYPE] == GAIN_UNITY) {
        envTempFile = new File[envOutChanNum];
        envFloatF = new FloatFile[envOutChanNum];
        for (ch = 0;
            ch < envOutChanNum;
            ch++) { // first zero them because an exception might be thrown
          envTempFile[ch] = null;
          envFloatF[ch] = null;
        }
        for (ch = 0; ch < envOutChanNum; ch++) {
          envTempFile[ch] = IOUtil.createTempFile();
          envFloatF[ch] = new FloatFile(envTempFile[ch], GenericFile.MODE_OUTPUT);
        }
        progLen += (long) envOutLength;
      } else {
        envGain = (float) (Param.transform(pr.para[PR_ENVGAIN], Param.ABS_AMP, ampRef, null)).val;
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- further inits ----
      maxChange = (float) (Param.transform(pr.para[PR_MAXCHANGE], Param.ABS_AMP, ampRef, null)).val;

      inBuf = new float[inChanNum][8192 + average];
      Util.clear(inBuf);
      outBuf = new float[outChanNum][8192];
      Util.clear(outBuf);
      if (extraAudioFile) {
        envInBuf = new float[envInChanNum][8192 + average];
        Util.clear(envInBuf);
      }
      inEnvBuf = new float[inChanNum][8192]; // = envOutBuf
      Util.clear(inEnvBuf);
      shapeEnvBuf = new float[envInChanNum][8192];
      Util.clear(shapeEnvBuf);

      inEnergy = new double[inChanNum];
      for (ch = 0; ch < inChanNum; ch++) {
        inEnergy[ch] = 0.0;
      }
      envInEnergy = new double[envInChanNum];
      for (ch = 0; ch < envInChanNum; ch++) {
        envInEnergy[ch] = 0.0;
      }

      // System.out.println( "inLength "+inLength+"; envInLength "+envInLength+"; envOutLength
      // "+envOutLength+"; outLength "+outLength );
      // System.out.println( "average "+average+"; avrOff "+avrOff );

      // ----==================== buffer init ====================----

      framesRead = 0; // re inF
      framesRead2 = 0; // re envInF

      // ---- init buffers ----
      for (off = avrOff; threadRunning && (off < average); ) {
        len = Math.min(inLength - framesRead, Math.min(8192, average - off));
        if (len == 0) break;

        inF.readFrames(inBuf, off, len);
        // calc initial energy per channel (see calcEnv())
        for (ch = 0; ch < inChanNum; ch++) {
          convBuf1 = inBuf[ch];
          d1 = 0.0;
          for (i = 0, j = off; i < len; i++) {
            f1 = convBuf1[j++];
            d1 += f1 * f1;
          }
          inEnergy[ch] += d1;
        }
        framesRead += len;
        off += len;
        progOff += len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
      }
      // zero padding bereits durch initialisierung mit Util.clear() passiert!

      if (extraAudioFile) {
        for (off = avrOff; threadRunning && (off < average); ) {
          len = Math.min(envInLength - framesRead2, Math.min(8192, average - off));
          if (len == 0) break;

          envInF.readFrames(envInBuf, off, len);
          // calc initial energy per channel (see calcEnv())
          for (ch = 0; ch < envInChanNum; ch++) {
            convBuf1 = envInBuf[ch];
            d1 = 0.0;
            for (i = 0, j = off; i < len; i++) {
              f1 = convBuf1[j++];
              d1 += f1 * f1;
            }
            envInEnergy[ch] += d1;
          }
          framesRead2 += len;
          off += len;
          progOff += len;
          // .... progress ....
          setProgression((float) progOff / (float) progLen);
        }
        // zero padding bereits durch initialisierung mit Util.clear() passiert!
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ----==================== the real stuff ====================----

      framesWritten = 0; // re OutF
      framesWritten2 = 0; // re envOutF

      while (threadRunning && (framesWritten < outLength)) {

        chunkLength = Math.min(8192, outLength - framesWritten);
        // ---- read input chunk ----
        len = Math.min(inLength - framesRead, chunkLength);
        inF.readFrames(inBuf, average, len);
        // zero padding
        for (ch = 0; ch < inChanNum; ch++) {
          convBuf1 = inBuf[ch];
          for (i = len, j = len + average; i < chunkLength; i++) {
            convBuf1[j++] = 0.0f;
          }
        }
        framesRead += len;
        progOff += len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
        // .... check running ....
        if (!threadRunning) break topLevel;

        // ---- read input env chunk ----
        if (envInF != null) {
          len = Math.min(envInLength - framesRead2, chunkLength);
          if (extraAudioFile) { // ........ needs averaging ........
            envInF.readFrames(envInBuf, average, len);
            // zero padding
            for (ch = 0; ch < envInChanNum; ch++) {
              convBuf1 = envInBuf[ch];
              for (i = len, j = len + average; i < chunkLength; i++) {
                convBuf1[j++] = 0.0f;
              }
            }
          } else { // ........ is already env ........
            envInF.readFrames(shapeEnvBuf, 0, len);
            // zero padding
            for (ch = 0; ch < envInChanNum; ch++) {
              convBuf1 = shapeEnvBuf[ch];
              for (i = len; i < chunkLength; i++) {
                convBuf1[i] = 0.0f;
              }
            }
          }
          framesRead2 += len;
          progOff += len;
          // .... progress ....
          setProgression((float) progOff / (float) progLen);
        }
        // .... check running ....
        if (!threadRunning) break topLevel;

        // ---- calc input envelope ----
        for (ch = 0; ch < inChanNum; ch++) {
          inEnergy[ch] = calcEnv(inBuf[ch], inEnvBuf[ch], average, chunkLength, inEnergy[ch]);
        }

        // ---- write output env file ----
        if (pr.bool[PR_ENVOUTPUT]) {
          if (envFloatF != null) { // i.e. unity gain
            for (ch = 0; ch < envOutChanNum; ch++) {
              convBuf1 = inEnvBuf[ch];
              for (i = 0; i < chunkLength; i++) { // measure max amp
                f1 = Math.abs(convBuf1[i]);
                if (f1 > envMaxAmp) {
                  envMaxAmp = f1;
                }
              }
              envFloatF[ch].writeFloats(convBuf1, 0, chunkLength);
            }
          } else { // i.e. abs gain
            for (ch = 0; ch < envOutChanNum; ch++) {
              convBuf1 = inEnvBuf[ch];
              for (i = 0; i < chunkLength; i++) { // measure max amp + adjust gain
                f1 = Math.abs(convBuf1[i]);
                convBuf1[i] *= envGain;
                if (f1 > envMaxAmp) {
                  envMaxAmp = f1;
                }
              }
            }
            envOutF.writeFrames(inEnvBuf, 0, chunkLength);
          }
          framesWritten2 += chunkLength;
          progOff += chunkLength;
          // .... progress ....
          setProgression((float) progOff / (float) progLen);
        }
        // .... check running ....
        if (!threadRunning) break topLevel;

        // ---- calc shape envelope ----
        switch (pr.intg[PR_ENVSOURCE]) {
          case SRC_INPUT: // shape env = input env
            for (ch = 0; ch < inChanNum; ch++) {
              System.arraycopy(inEnvBuf[ch], 0, shapeEnvBuf[ch], 0, chunkLength);
            }
            break;
          case SRC_SOUNDFILE: // calc shape env from envInBuf
            for (ch = 0; ch < envInChanNum; ch++) {
              envInEnergy[ch] =
                  calcEnv(envInBuf[ch], shapeEnvBuf[ch], average, chunkLength, envInEnergy[ch]);
            }
            break;
          case SRC_ENVFILE: // nothing to do, we have already loaded the env
            break; //    in the correct buffer
          case SRC_ENV:
            throw new IOException("Graphic env not yet supported");
        }

        // ---- calc output ----
        // first generate output envelope
        switch (pr.intg[PR_MODE]) {
          case MODE_SUPERPOSE:
            if (!pr.bool[PR_INVERT]) { // multiply by shape
              for (ch = 0; ch < outChanNum; ch++) {
                convBuf1 = outBuf[ch];
                for (i = 0; i < chunkLength; i++) {
                  f1 =
                      shapeEnvBuf[shapeChan[ch][0]][i] * shapeChanWeight[ch][0]
                          + shapeEnvBuf[shapeChan[ch][1]][i] * shapeChanWeight[ch][1];
                  convBuf1[i] = Math.min(maxChange, f1);
                }
              }

            } else { // divide by shape
              for (ch = 0; ch < outChanNum; ch++) {
                convBuf1 = outBuf[ch];
                for (i = 0; i < chunkLength; i++) {
                  f1 =
                      shapeEnvBuf[shapeChan[ch][0]][i] * shapeChanWeight[ch][0]
                          + shapeEnvBuf[shapeChan[ch][1]][i] * shapeChanWeight[ch][1];
                  if (f1 > 0.0f) {
                    convBuf1[i] = Math.min(maxChange, 1.0f / f1);
                  } else {
                    convBuf1[i] = maxChange;
                  }
                }
              }
            }
            break;

          case MODE_REPLACE:
            if (!pr.bool[PR_INVERT]) { // shape / input
              for (ch = 0; ch < outChanNum; ch++) {
                convBuf1 = outBuf[ch];
                for (i = 0; i < chunkLength; i++) {
                  f1 =
                      shapeEnvBuf[shapeChan[ch][0]][i] * shapeChanWeight[ch][0]
                          + shapeEnvBuf[shapeChan[ch][1]][i] * shapeChanWeight[ch][1];
                  f2 =
                      inEnvBuf[inChan[ch][0]][i] * inChanWeight[ch][0]
                          + inEnvBuf[inChan[ch][1]][i] * inChanWeight[ch][1];
                  if (f2 > 0.0f) {
                    convBuf1[i] = Math.min(maxChange, f1 / f2);
                  } else {
                    convBuf1[i] = 0.0f; // input ist eh ueberall null, somit unveraenderlich
                  }
                }
              }

            } else { // 1 / (shape * input)
              for (ch = 0; ch < outChanNum; ch++) {
                convBuf1 = outBuf[ch];
                for (i = 0; i < chunkLength; i++) {
                  f1 =
                      shapeEnvBuf[shapeChan[ch][0]][i] * shapeChanWeight[ch][0]
                          + shapeEnvBuf[shapeChan[ch][1]][i] * shapeChanWeight[ch][1];
                  f1 *=
                      inEnvBuf[inChan[ch][0]][i] * inChanWeight[ch][0]
                          + inEnvBuf[inChan[ch][1]][i] * inChanWeight[ch][1];
                  if (f1 > 0.0f) {
                    convBuf1[i] = Math.min(maxChange, 1.0f / f1);
                  } else {
                    convBuf1[i] = maxChange;
                  }
                }
              }
            }
            break;
        }
        // then multiply input bites
        if (inChanNum == outChanNum) { // no weighting - use faster routine
          for (ch = 0; ch < outChanNum; ch++) {
            convBuf1 = outBuf[ch];
            convBuf2 = inBuf[ch];
            for (i = 0, j = avrOff; i < chunkLength; i++, j++) {
              convBuf1[i] *= convBuf2[j];
            }
          }
        } else {
          for (ch = 0; ch < outChanNum; ch++) {
            convBuf1 = outBuf[ch];
            for (i = 0, j = avrOff; i < chunkLength; i++, j++) {
              f1 =
                  inBuf[inChan[ch][0]][j] * inChanWeight[ch][0]
                      + inBuf[inChan[ch][1]][j] * inChanWeight[ch][1];
              convBuf1[i] *= f1;
            }
          }
        }

        // ---- write output sound file ----
        if (outFloatF != null) { // i.e. unity gain
          for (ch = 0; ch < outChanNum; ch++) {
            convBuf1 = outBuf[ch];
            for (i = 0; i < chunkLength; i++) { // measure max amp
              f1 = Math.abs(convBuf1[i]);
              if (f1 > maxAmp) {
                maxAmp = f1;
              }
            }
            outFloatF[ch].writeFloats(convBuf1, 0, chunkLength);
          }
        } else { // i.e. abs gain
          for (ch = 0; ch < outChanNum; ch++) {
            convBuf1 = outBuf[ch];
            for (i = 0; i < chunkLength; i++) { // measure max amp + adjust gain
              f1 = Math.abs(convBuf1[i]);
              convBuf1[i] *= gain;
              if (f1 > maxAmp) {
                maxAmp = f1;
              }
            }
          }
          outF.writeFrames(outBuf, 0, chunkLength);
        }
        framesWritten += chunkLength;
        progOff += chunkLength;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);

        // ---- shift buffers ----
        for (ch = 0;
            ch < inChanNum;
            ch++) { // zero padding is performed after AudioFile.readFrames()!
          System.arraycopy(inBuf[ch], chunkLength, inBuf[ch], 0, average);
        }
        if (extraAudioFile) {
          for (ch = 0;
              ch < envInChanNum;
              ch++) { // zero padding is performed after AudioFile.readFrames()!
            System.arraycopy(envInBuf[ch], chunkLength, envInBuf[ch], 0, average);
          }
        }
      } // until framesWritten == outLength
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- normalize output ----

      // sound file
      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        peakGain = new Param((double) maxAmp, Param.ABS_AMP);
        gain =
            (float)
                (Param.transform(
                        pr.para[PR_GAIN],
                        Param.ABS_AMP,
                        new Param(1.0 / peakGain.val, peakGain.unit),
                        null))
                    .val;
        f1 = 1.0f;
        if ((envOutF != null) && (pr.intg[PR_ENVGAINTYPE] == GAIN_UNITY)) { // leave prog space
          f1 = (1.0f + getProgression()) / 2;
        }
        normalizeAudioFile(outFloatF, outF, outBuf, gain, f1);
        for (ch = 0; ch < outChanNum; ch++) {
          outFloatF[ch].cleanUp();
          outFloatF[ch] = null;
          outTempFile[ch].delete();
          outTempFile[ch] = null;
        }
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // envelope file
      if ((envOutF != null) && (pr.intg[PR_ENVGAINTYPE] == GAIN_UNITY)) {
        peakGain = new Param((double) envMaxAmp, Param.ABS_AMP);
        envGain =
            (float)
                (Param.transform(
                        pr.para[PR_ENVGAIN],
                        Param.ABS_AMP,
                        new Param(1.0 / peakGain.val, peakGain.unit),
                        null))
                    .val;

        normalizeAudioFile(envFloatF, envOutF, inEnvBuf, envGain, 1.0f);
        for (ch = 0; ch < envOutChanNum; ch++) {
          envFloatF[ch].cleanUp();
          envFloatF[ch] = null;
          envTempFile[ch].delete();
          envTempFile[ch] = null;
        }
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- Finish ----

      outF.close();
      outF = null;
      outStream = null;
      if (envOutF != null) {
        envOutF.close();
        envOutF = null;
        envOutStream = null;
      }
      if (envInF != null) {
        envInF.close();
        envInF = null;
        envInStream = null;
      }
      inF.close();
      inF = null;
      inStream = null;
      outBuf = null;
      inBuf = null;
      inEnvBuf = null;
      envInBuf = null;
      shapeEnvBuf = null;

      // inform about clipping/ low level
      maxAmp *= gain;
      handleClipping(maxAmp);
      envMaxAmp *= envGain;
      //			handleClipping( envMaxAmp );	// ;( routine nicht flexibel genug!

    } catch (IOException e1) {
      setError(e1);
    } catch (OutOfMemoryError e2) {
      inStream = null;
      outStream = null;
      envInStream = null;
      envOutStream = null;
      inBuf = null;
      outBuf = null;
      inEnvBuf = null;
      envInBuf = null;
      shapeEnvBuf = null;
      convBuf1 = null;
      convBuf2 = null;
      System.gc();

      setError(new Exception(ERR_MEMORY));
      ;
    }

    // ---- cleanup (topLevel) ----
    if (inF != null) {
      inF.cleanUp();
      inF = null;
    }
    if (outF != null) {
      outF.cleanUp();
      outF = null;
    }
    if (envInF != null) {
      envInF.cleanUp();
      envInF = null;
    }
    if (envOutF != null) {
      envOutF.cleanUp();
      envOutF = null;
    }
    if (outFloatF != null) {
      for (ch = 0; ch < outFloatF.length; ch++) {
        if (outFloatF[ch] != null) outFloatF[ch].cleanUp();
        if (outTempFile[ch] != null) outTempFile[ch].delete();
      }
    }
    if (envFloatF != null) {
      for (ch = 0; ch < envFloatF.length; ch++) {
        if (envFloatF[ch] != null) envFloatF[ch].cleanUp();
        if (envTempFile[ch] != null) envTempFile[ch].delete();
      }
    }
  } // process()
    public void assertTiming() {
      assert expectedMs != 0 : "Must call .expect() before run test";
      if (COVERAGE_ENABLED_BUILD) return;

      while (true) {
        attempts--;
        long start;
        try {
          if (setup != null) setup.run();
          start = System.currentTimeMillis();
          test.run();
        } catch (Throwable throwable) {
          throw new RuntimeException(throwable);
        }
        long finish = System.currentTimeMillis();
        long duration = finish - start;

        int expectedOnMyMachine = expectedMs;
        if (adjustForCPU) {
          expectedOnMyMachine =
              adjust(expectedOnMyMachine, Timings.CPU_TIMING, Timings.ETALON_CPU_TIMING);

          expectedOnMyMachine =
              usesAllCPUCores
                  ? expectedOnMyMachine * 8 / JobSchedulerImpl.CORES_COUNT
                  : expectedOnMyMachine;
        }
        if (adjustForIO) {
          expectedOnMyMachine =
              adjust(expectedOnMyMachine, Timings.IO_TIMING, Timings.ETALON_IO_TIMING);
        }

        // Allow 10% more in case of test machine is busy.
        String logMessage = message;
        if (duration > expectedOnMyMachine) {
          int percentage = (int) (100.0 * (duration - expectedOnMyMachine) / expectedOnMyMachine);
          logMessage += ": " + percentage + "% longer";
        }
        logMessage +=
            ". Expected: "
                + formatTime(expectedOnMyMachine)
                + ". Actual: "
                + formatTime(duration)
                + "."
                + Timings.getStatistics();
        final double acceptableChangeFactor = 1.1;
        if (duration < expectedOnMyMachine) {
          int percentage = (int) (100.0 * (expectedOnMyMachine - duration) / expectedOnMyMachine);
          logMessage = percentage + "% faster. " + logMessage;

          TeamCityLogger.info(logMessage);
          System.out.println("SUCCESS: " + logMessage);
        } else if (duration < expectedOnMyMachine * acceptableChangeFactor) {
          TeamCityLogger.warning(logMessage, null);
          System.out.println("WARNING: " + logMessage);
        } else {
          // try one more time
          if (attempts == 0) {
            // try {
            //  Object result =
            // Class.forName("com.intellij.util.ProfilingUtil").getMethod("captureCPUSnapshot").invoke(null);
            //  System.err.println("CPU snapshot captured in '"+result+"'");
            // }
            // catch (Exception e) {
            // }

            throw new AssertionFailedError(logMessage);
          }
          System.gc();
          System.gc();
          System.gc();
          String s = "Another epic fail (remaining attempts: " + attempts + "): " + logMessage;
          TeamCityLogger.warning(s, null);
          System.err.println(s);
          // if (attempts == 1) {
          //  try {
          //
          // Class.forName("com.intellij.util.ProfilingUtil").getMethod("startCPUProfiling").invoke(null);
          //  }
          //  catch (Exception e) {
          //  }
          // }
          continue;
        }
        break;
      }
    }
    public int print(java.awt.Graphics pg, java.awt.print.PageFormat pageFormat, int pageIndex)
        throws java.awt.print.PrinterException {

      if (pageIndex >= m_maxNumPage || m_bi == null) {
        return NO_SUCH_PAGE;
      }

      pg.translate((int) pageFormat.getImageableX() + 1, (int) pageFormat.getImageableY() + 1);

      int wPage = (int) pageFormat.getImageableWidth() + 1;

      int hPage = (int) pageFormat.getImageableHeight() + 1;

      double scale = percentSize / 100.0;

      wPage = (int) (wPage / scale);

      hPage = (int) (hPage / scale);

      /*

      int wPage = (int)pageFormat.getImageableWidth();

      int hPage = (int)pageFormat.getImageableHeight();



      int w = m_bi.getWidth(this);

      int h = m_bi.getHeight(this);

      if (w == 0 || h == 0)

      return NO_SUCH_PAGE;

      int nCol = Math.max((int)Math.ceil((double)w/wPage), 1);

      int nRow = Math.max((int)Math.ceil((double)h/hPage), 1);

      m_maxNumPage = nCol*nRow;



      int iCol = pageIndex % nCol;

      int iRow = pageIndex / nCol;

      int x = iCol*wPage;

      int y = iRow*hPage;

      int wImage = Math.min(wPage, w-x);

      int hImage = Math.min(hPage, h-y);

      */

      int w = m_bi.getWidth(this);

      int h = m_bi.getHeight(this);

      // int resizedw = (int)(w*(percentSize/100.0));

      // int resizedh = (int)(h*(percentSize/100.0));

      java.awt.Graphics2D g2d = (java.awt.Graphics2D) pg;

      g2d.scale(percentSize / 100.0, percentSize / 100.0);

      if (w == 0 || h == 0) {
        return NO_SUCH_PAGE;
      }

      int nCol = Math.max((int) Math.ceil((double) w / wPage), 1);

      int nRow = Math.max((int) Math.ceil((double) h / hPage), 1);

      m_maxNumPage = nCol * nRow;

      int iCol = pageIndex % nCol;

      int iRow = pageIndex / nCol;

      int x = iCol * wPage;

      int y = iRow * hPage;

      int wImage = Math.min(wPage, w - x);

      int hImage = Math.min(hPage, h - y);

      g2d.drawImage(m_bi, 0, 0, wImage, hImage, x, y, x + wImage, y + hImage, this);

      // pg.drawImage(m_bi, 0, 0, 40, 40,  x, y, x+wImage, y+hImage, this);

      System.gc();

      return PAGE_EXISTS;
    }
Ejemplo n.º 21
0
  /** Translation durchfuehren */
  public void process() {
    int i, j, k;
    int ch, len;
    float f1;
    double d1, d2, d3, d4, d5;
    long progOff, progLen, lo;

    // io
    AudioFile reInF = null;
    AudioFile imInF = null;
    AudioFile reOutF = null;
    AudioFile imOutF = null;
    AudioFileDescr reInStream = null;
    AudioFileDescr imInStream = null;
    AudioFileDescr reOutStream = null;
    AudioFileDescr imOutStream = null;
    FloatFile reFloatF[] = null;
    FloatFile imFloatF[] = null;
    File reTempFile[] = null;
    File imTempFile[] = null;
    int outChanNum;

    float[][] reInBuf; // [ch][i]
    float[][] imInBuf; // [ch][i]
    float[][] reOutBuf = null; // [ch][i]
    float[][] imOutBuf = null; // [ch][i]
    float[] convBuf1, convBuf2;
    boolean complex;

    PathField ggOutput;

    // Synthesize
    Param ampRef = new Param(1.0, Param.ABS_AMP); // transform-Referenz
    float gain; // gain abs amp
    float dryGain, wetGain;
    float inGain;
    float maxAmp = 0.0f;
    Param peakGain;

    int inLength, inOff;
    int pre;
    int post;
    int length;
    int framesRead, framesWritten, outLength;
    boolean polarIn, polarOut;

    // phase unwrapping
    double[] phi;
    int[] wrap;
    double[] carry;

    Param lenRef;

    topLevel:
    try {

      complex = pr.bool[PR_HASIMINPUT] || pr.bool[PR_HASIMOUTPUT];
      polarIn = pr.intg[PR_OPERATOR] == OP_POLAR2RECT;
      polarOut = pr.intg[PR_OPERATOR] == OP_RECT2POLAR;
      if ((polarIn || polarOut) && !complex) throw new IOException(ERR_NOTCOMPLEX);

      // ---- open input ----

      reInF = AudioFile.openAsRead(new File(pr.text[PR_REINPUTFILE]));
      reInStream = reInF.getDescr();
      inLength = (int) reInStream.length;
      reInBuf = new float[reInStream.channels][8192];
      imInBuf = new float[reInStream.channels][8192];

      if (pr.bool[PR_HASIMINPUT]) {
        imInF = AudioFile.openAsRead(new File(pr.text[PR_IMINPUTFILE]));
        imInStream = imInF.getDescr();
        if (imInStream.channels != reInStream.channels) throw new IOException(ERR_COMPLEX);
        inLength = (int) Math.min(inLength, imInStream.length);
      }

      lenRef = new Param(AudioFileDescr.samplesToMillis(reInStream, inLength), Param.ABS_MS);
      d1 =
          AudioFileDescr.millisToSamples(
              reInStream, (Param.transform(pr.para[PR_OFFSET], Param.ABS_MS, lenRef, null).value));
      j = (int) (d1 >= 0.0 ? (d1 + 0.5) : (d1 - 0.5)); // correct rounding for negative values!
      length =
          (int)
              (AudioFileDescr.millisToSamples(
                      reInStream,
                      (Param.transform(pr.para[PR_LENGTH], Param.ABS_MS, lenRef, null)).value)
                  + 0.5);

      // System.err.println( "offset = "+j );

      if (j >= 0) {
        inOff = Math.min(j, inLength);
        if (!pr.bool[PR_REVERSE]) {
          reInF.seekFrame(inOff);
          if (pr.bool[PR_HASIMINPUT]) {
            imInF.seekFrame(inOff);
          }
        }
        inLength -= inOff;
        pre = 0;
      } else {
        inOff = 0;
        pre = Math.min(-j, length);
      }
      inLength = Math.min(inLength, length - pre);
      post = length - pre - inLength;

      if (pr.bool[PR_REVERSE]) {
        i = pre;
        pre = post;
        post = i;
        inOff += inLength;
      }

      // .... check running ....
      if (!threadRunning) break topLevel;

      // for( op = 0; op < 2; op++ ) {
      // 	System.out.println( op +": pre "+pre[op]+" / len "+inLength[op]+" / post "+post[op] );
      // }
      // System.out.println( "tot "+length[0]);

      outLength = length;
      outChanNum = reInStream.channels;

      // ---- open output ----

      ggOutput = (PathField) gui.getItemObj(GG_REOUTPUTFILE);
      if (ggOutput == null) throw new IOException(ERR_MISSINGPROP);
      reOutStream = new AudioFileDescr(reInStream);
      ggOutput.fillStream(reOutStream);
      reOutStream.channels = outChanNum;
      // well, more sophisticated code would
      // move and truncate the markers...
      if ((pre == 0) /* && (post == 0) */) {
        reInF.readMarkers();
        reOutStream.setProperty(
            AudioFileDescr.KEY_MARKERS, reInStream.getProperty(AudioFileDescr.KEY_MARKERS));
      }
      reOutF = AudioFile.openAsWrite(reOutStream);
      reOutBuf = new float[outChanNum][8192];
      imOutBuf = new float[outChanNum][8192];

      if (pr.bool[PR_HASIMOUTPUT]) {
        imOutStream = new AudioFileDescr(reInStream);
        ggOutput.fillStream(imOutStream);
        imOutStream.channels = outChanNum;
        imOutStream.file = new File(pr.text[PR_IMOUTPUTFILE]);
        imOutF = AudioFile.openAsWrite(imOutStream);
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- Further inits ----

      phi = new double[outChanNum];
      wrap = new int[outChanNum];
      carry = new double[outChanNum];
      for (ch = 0; ch < outChanNum; ch++) {
        phi[ch] = 0.0;
        wrap[ch] = 0;
        carry[ch] = Double.NEGATIVE_INFINITY;
      }

      progOff = 0; // read, transform, write
      progLen = (long) outLength * 3;

      wetGain = (float) (Param.transform(pr.para[PR_WETMIX], Param.ABS_AMP, ampRef, null)).value;
      dryGain = (float) (Param.transform(pr.para[PR_DRYMIX], Param.ABS_AMP, ampRef, null)).value;
      if (pr.bool[PR_DRYINVERT]) {
        dryGain = -dryGain;
      }
      inGain = (float) (Param.transform(pr.para[PR_INPUTGAIN], Param.ABS_AMP, ampRef, null)).value;
      if (pr.bool[PR_INVERT]) {
        inGain = -inGain;
      }

      // normalization requires temp files
      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        reTempFile = new File[outChanNum];
        reFloatF = new FloatFile[outChanNum];
        for (ch = 0;
            ch < outChanNum;
            ch++) { // first zero them because an exception might be thrown
          reTempFile[ch] = null;
          reFloatF[ch] = null;
        }
        for (ch = 0; ch < outChanNum; ch++) {
          reTempFile[ch] = IOUtil.createTempFile();
          reFloatF[ch] = new FloatFile(reTempFile[ch], GenericFile.MODE_OUTPUT);
        }
        if (pr.bool[PR_HASIMOUTPUT]) {
          imTempFile = new File[outChanNum];
          imFloatF = new FloatFile[outChanNum];
          for (ch = 0;
              ch < outChanNum;
              ch++) { // first zero them because an exception might be thrown
            imTempFile[ch] = null;
            imFloatF[ch] = null;
          }
          for (ch = 0; ch < outChanNum; ch++) {
            imTempFile[ch] = IOUtil.createTempFile();
            imFloatF[ch] = new FloatFile(imTempFile[ch], GenericFile.MODE_OUTPUT);
          }
        }
        progLen += outLength;
      } else {
        gain = (float) (Param.transform(pr.para[PR_GAIN], Param.ABS_AMP, ampRef, null)).value;
        wetGain *= gain;
        dryGain *= gain;
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ----==================== the real stuff ====================----

      framesRead = 0;
      framesWritten = 0;

      while (threadRunning && (framesWritten < outLength)) {
        // ---- choose chunk len ----
        len = Math.min(8192, outLength - framesWritten);
        if (pre > 0) {
          len = Math.min(len, pre);
        } else if (inLength > 0) {
          len = Math.min(len, inLength);
        } else {
          len = Math.min(len, post);
        }

        // ---- read input chunks ----
        if (pre > 0) {
          Util.clear(reInBuf);
          if (complex) {
            Util.clear(imInBuf);
          }
          pre -= len;
        } else if (inLength > 0) {
          if (pr.bool[PR_REVERSE]) { // ---- read reversed ----
            reInF.seekFrame(inOff - framesRead - len);
            reInF.readFrames(reInBuf, 0, len);
            for (ch = 0; ch < reInStream.channels; ch++) {
              convBuf1 = reInBuf[ch];
              for (i = 0, j = len - 1; i < j; i++, j--) {
                f1 = convBuf1[j];
                convBuf1[j] = convBuf1[i];
                convBuf1[i] = f1;
              }
            }
            if (pr.bool[PR_HASIMINPUT]) {
              imInF.seekFrame(inOff - framesRead - len);
              imInF.readFrames(imInBuf, 0, len);
              for (ch = 0; ch < imInStream.channels; ch++) {
                convBuf1 = imInBuf[ch];
                for (i = 0, j = len - 1; i < j; i++, j--) {
                  f1 = convBuf1[j];
                  convBuf1[j] = convBuf1[i];
                  convBuf1[i] = f1;
                }
              }
            } else if (complex) {
              Util.clear(imInBuf);
            }
          } else { // ---- read normal ----
            reInF.readFrames(reInBuf, 0, len);
            if (pr.bool[PR_HASIMINPUT]) {
              imInF.readFrames(imInBuf, 0, len);
            } else if (complex) {
              Util.clear(imInBuf);
            }
          }
          inLength -= len;
          framesRead += len;
        } else {
          Util.clear(reInBuf);
          if (complex) {
            Util.clear(imInBuf);
          }
          post -= len;
        }
        progOff += len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
        // .... check running ....
        if (!threadRunning) break topLevel;

        // ---- save dry signal ----
        for (ch = 0; ch < outChanNum; ch++) {
          convBuf1 = reInBuf[ch];
          convBuf2 = reOutBuf[ch];
          for (i = 0; i < len; i++) {
            convBuf2[i] = convBuf1[i] * dryGain;
          }
          if (complex) {
            convBuf1 = imInBuf[ch];
            convBuf2 = imOutBuf[ch];
            for (i = 0; i < len; i++) {
              convBuf2[i] = convBuf1[i] * dryGain;
            }
          }
        }

        // ---- rectify + apply input gain ----
        for (ch = 0; ch < reInStream.channels; ch++) {
          convBuf1 = reInBuf[ch];
          convBuf2 = imInBuf[ch];
          // ---- rectify ----
          if (pr.bool[PR_RECTIFY]) {
            if (complex) {
              if (polarIn) {
                for (i = 0; i < len; i++) {
                  convBuf2[i] = 0.0f;
                }
              } else {
                for (i = 0; i < len; i++) {
                  d1 = convBuf1[i];
                  d2 = convBuf2[i];
                  convBuf1[i] = (float) Math.sqrt(d1 * d1 + d2 * d2);
                  convBuf2[i] = 0.0f;
                }
              }
            } else {
              for (i = 0; i < len; i++) {
                convBuf1[i] = Math.abs(convBuf1[i]);
              }
            }
          }
          // ---- apply input gain ----
          Util.mult(convBuf1, 0, len, inGain);
          if (complex & !polarIn) {
            Util.mult(convBuf2, 0, len, inGain);
          }
        }

        // ---- heart of the dragon ----
        for (ch = 0; ch < outChanNum; ch++) {
          convBuf1 = reInBuf[ch];
          convBuf2 = imInBuf[ch];

          switch (pr.intg[PR_OPERATOR]) {
            case OP_NONE: // ================ None ================
              for (i = 0; i < len; i++) {
                reOutBuf[ch][i] += wetGain * convBuf1[i];
              }
              if (complex) {
                for (i = 0; i < len; i++) {
                  imOutBuf[ch][i] += wetGain * convBuf2[i];
                }
              }
              break;

            case OP_SIN: // ================ Cosinus ================
              if (complex) {
                for (i = 0; i < len; i++) {
                  reOutBuf[ch][i] += wetGain * (float) Math.sin(convBuf1[i] * Math.PI);
                  imOutBuf[ch][i] += wetGain * (float) Math.sin(convBuf2[i] * Math.PI);
                }
              } else {
                for (i = 0; i < len; i++) {
                  reOutBuf[ch][i] += wetGain * (float) Math.sin(convBuf1[i] * Math.PI);
                }
              }
              break;

            case OP_SQR: // ================ Square ================
              if (complex) {
                for (i = 0; i < len; i++) {
                  reOutBuf[ch][i] +=
                      wetGain * (convBuf1[i] * convBuf1[i] - convBuf2[i] * convBuf2[i]);
                  imOutBuf[ch][i] -= wetGain * (convBuf1[i] * convBuf2[i] * 2);
                }
              } else {
                for (i = 0; i < len; i++) {
                  reOutBuf[ch][i] += wetGain * (convBuf1[i] * convBuf1[i]);
                }
              }
              break;

            case OP_SQRT: // ================ Square root ================
              if (complex) {
                d3 = phi[ch];
                k = wrap[ch];
                d4 = k * Constants.PI2;
                for (i = 0; i < len; i++) {
                  d1 =
                      wetGain
                          * Math.pow(convBuf1[i] * convBuf1[i] + convBuf2[i] * convBuf2[i], 0.25);
                  d2 = Math.atan2(convBuf2[i], convBuf1[i]);
                  if (d2 - d3 > Math.PI) {
                    k--;
                    d4 = k * Constants.PI2;
                  } else if (d3 - d2 > Math.PI) {
                    k++;
                    d4 = k * Constants.PI2;
                  }
                  d2 += d4;
                  d3 = d2;
                  d2 /= 2;
                  reOutBuf[ch][i] += (float) (d1 * Math.cos(d2));
                  imOutBuf[ch][i] += (float) (d1 * Math.sin(d2));
                }
                phi[ch] = d3;
                wrap[ch] = k;

              } else {
                for (i = 0; i < len; i++) {
                  f1 = convBuf1[i];
                  if (f1 > 0) {
                    reOutBuf[ch][i] += wetGain * (float) Math.sqrt(f1);
                  } // else undefiniert
                }
              }
              break;

            case OP_RECT2POLARW: // ================ Rect->Polar (wrapped) ================
              for (i = 0; i < len; i++) {
                d1 = wetGain * Math.sqrt(convBuf1[i] * convBuf1[i] + convBuf2[i] * convBuf2[i]);
                d2 = Math.atan2(convBuf2[i], convBuf1[i]);
                reOutBuf[ch][i] += (float) d1;
                imOutBuf[ch][i] += (float) d2;
              }
              break;

            case OP_RECT2POLAR: // ================ Rect->Polar ================
              d3 = phi[ch];
              k = wrap[ch];
              d4 = k * Constants.PI2;
              for (i = 0; i < len; i++) {
                d1 = wetGain * Math.sqrt(convBuf1[i] * convBuf1[i] + convBuf2[i] * convBuf2[i]);
                d2 = Math.atan2(convBuf2[i], convBuf1[i]);
                if (d2 - d3 > Math.PI) {
                  k--;
                  d4 = k * Constants.PI2;
                } else if (d3 - d2 > Math.PI) {
                  k++;
                  d4 = k * Constants.PI2;
                }
                d2 += d4;
                reOutBuf[ch][i] += (float) d1;
                imOutBuf[ch][i] += (float) d2;
                d3 = d2;
              }
              phi[ch] = d3;
              wrap[ch] = k;
              break;

            case OP_POLAR2RECT: // ================ Polar->Rect ================
              for (i = 0; i < len; i++) {
                f1 = wetGain * convBuf1[i];
                reOutBuf[ch][i] += f1 * (float) Math.cos(convBuf2[i]);
                imOutBuf[ch][i] += f1 * (float) Math.sin(convBuf2[i]);
              }
              break;

            case OP_LOG: // ================ Log ================
              if (complex) {
                d3 = phi[ch];
                k = wrap[ch];
                d4 = k * Constants.PI2;
                d5 = carry[ch];
                for (i = 0; i < len; i++) {
                  d1 = Math.sqrt(convBuf1[i] * convBuf1[i] + convBuf2[i] * convBuf2[i]);
                  d2 = Math.atan2(convBuf2[i], convBuf1[i]);
                  if (d2 - d3 > Math.PI) {
                    k--;
                    d4 = k * Constants.PI2;
                  } else if (d3 - d2 > Math.PI) {
                    k++;
                    d4 = k * Constants.PI2;
                  }
                  if (d1 > 0.0) {
                    d5 = Math.log(d1);
                  }
                  d2 += d4;
                  reOutBuf[ch][i] += (float) d5;
                  imOutBuf[ch][i] += (float) d2;
                  d3 = d2;
                }
                phi[ch] = d3;
                wrap[ch] = k;
                carry[ch] = d5;

              } else {
                for (i = 0; i < len; i++) {
                  f1 = convBuf1[i];
                  if (f1 > 0) {
                    reOutBuf[ch][i] += wetGain * (float) Math.log(f1);
                  } // else undefiniert
                }
              }
              break;

            case OP_EXP: // ================ Exp ================
              if (complex) {
                for (i = 0; i < len; i++) {
                  d1 = wetGain * Math.exp(convBuf1[i]);
                  reOutBuf[ch][i] += (float) (d1 * Math.cos(convBuf2[i]));
                  imOutBuf[ch][i] += (float) (d1 * Math.sin(convBuf2[i]));
                }
              } else {
                for (i = 0; i < len; i++) {
                  reOutBuf[ch][i] += wetGain * (float) Math.exp(convBuf1[i]);
                }
              }
              break;

            case OP_NOT: // ================ NOT ================
              for (i = 0; i < len; i++) {
                lo = ~((long) (convBuf1[i] * 2147483647.0));
                reOutBuf[ch][i] += wetGain * (float) ((lo & 0xFFFFFFFFL) / 2147483647.0);
              }
              if (complex) {
                for (i = 0; i < len; i++) {
                  lo = ~((long) (convBuf2[i] * 2147483647.0));
                  imOutBuf[ch][i] += wetGain * (float) ((lo & 0xFFFFFFFFL) / 2147483647.0);
                }
              }
              break;
          }
        } // for outChan
        progOff += len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
        // .... check running ....
        if (!threadRunning) break topLevel;

        // ---- write output chunk ----
        if (reFloatF != null) {
          for (ch = 0; ch < outChanNum; ch++) {
            reFloatF[ch].writeFloats(reOutBuf[ch], 0, len);
            if (pr.bool[PR_HASIMOUTPUT]) {
              imFloatF[ch].writeFloats(imOutBuf[ch], 0, len);
            }
          }
        } else {
          reOutF.writeFrames(reOutBuf, 0, len);
          if (pr.bool[PR_HASIMOUTPUT]) {
            imOutF.writeFrames(imOutBuf, 0, len);
          }
        }
        // check max amp
        for (ch = 0; ch < outChanNum; ch++) {
          convBuf1 = reOutBuf[ch];
          for (i = 0; i < len; i++) {
            f1 = Math.abs(convBuf1[i]);
            if (f1 > maxAmp) {
              maxAmp = f1;
            }
          }
          if (pr.bool[PR_HASIMOUTPUT]) {
            convBuf1 = imOutBuf[ch];
            for (i = 0; i < len; i++) {
              f1 = Math.abs(convBuf1[i]);
              if (f1 > maxAmp) {
                maxAmp = f1;
              }
            }
          }
        }

        progOff += len;
        framesWritten += len;
        // .... progress ....
        setProgression((float) progOff / (float) progLen);
      } // while not framesWritten

      // ----==================== normalize output ====================----

      if (pr.intg[PR_GAINTYPE] == GAIN_UNITY) {
        peakGain = new Param(maxAmp, Param.ABS_AMP);
        gain =
            (float)
                (Param.transform(
                        pr.para[PR_GAIN],
                        Param.ABS_AMP,
                        new Param(1.0 / peakGain.value, peakGain.unit),
                        null))
                    .value;
        f1 = pr.bool[PR_HASIMOUTPUT] ? ((1.0f + getProgression()) / 2) : 1.0f;
        normalizeAudioFile(reFloatF, reOutF, reOutBuf, gain, f1);
        if (pr.bool[PR_HASIMOUTPUT]) {
          normalizeAudioFile(imFloatF, imOutF, imOutBuf, gain, 1.0f);
        }
        maxAmp *= gain;

        for (ch = 0; ch < outChanNum; ch++) {
          reFloatF[ch].cleanUp();
          reFloatF[ch] = null;
          reTempFile[ch].delete();
          reTempFile[ch] = null;
          if (pr.bool[PR_HASIMOUTPUT]) {
            imFloatF[ch].cleanUp();
            imFloatF[ch] = null;
            imTempFile[ch].delete();
            imTempFile[ch] = null;
          }
        }
      }
      // .... check running ....
      if (!threadRunning) break topLevel;

      // ---- Finish ----

      reOutF.close();
      reOutF = null;
      reOutStream = null;
      if (imOutF != null) {
        imOutF.close();
        imOutF = null;
        imOutStream = null;
      }
      reInF.close();
      reInF = null;
      reInStream = null;
      if (pr.bool[PR_HASIMINPUT]) {
        imInF.close();
        imInF = null;
        imInStream = null;
      }
      reOutBuf = null;
      imOutBuf = null;
      reInBuf = null;
      imInBuf = null;

      // inform about clipping/ low level
      handleClipping(maxAmp);
    } catch (IOException e1) {
      setError(e1);
    } catch (OutOfMemoryError e2) {
      reOutBuf = null;
      imOutBuf = null;
      reInBuf = null;
      imInBuf = null;
      convBuf1 = null;
      convBuf2 = null;
      System.gc();

      setError(new Exception(ERR_MEMORY));
    }

    // ---- cleanup (topLevel) ----
    convBuf1 = null;
    convBuf2 = null;

    if (reInF != null) {
      reInF.cleanUp();
      reInF = null;
    }
    if (imInF != null) {
      imInF.cleanUp();
      imInF = null;
    }
    if (reOutF != null) {
      reOutF.cleanUp();
      reOutF = null;
    }
    if (imOutF != null) {
      imOutF.cleanUp();
      imOutF = null;
    }
    if (reFloatF != null) {
      for (ch = 0; ch < reFloatF.length; ch++) {
        if (reFloatF[ch] != null) {
          reFloatF[ch].cleanUp();
          reFloatF[ch] = null;
        }
        if (reTempFile[ch] != null) {
          reTempFile[ch].delete();
          reTempFile[ch] = null;
        }
      }
    }
    if (imFloatF != null) {
      for (ch = 0; ch < imFloatF.length; ch++) {
        if (imFloatF[ch] != null) {
          imFloatF[ch].cleanUp();
          imFloatF[ch] = null;
        }
        if (imTempFile[ch] != null) {
          imTempFile[ch].delete();
          imTempFile[ch] = null;
        }
      }
    }
  } // process()
Ejemplo n.º 22
0
  // create a new profile: read the script and possibly execute the queries,
  // save the stats (if 'import' == true, we assume the profile already exists
  // and don't run the queries)
  public void createWkld(String name, String scriptFile, boolean runQueries) {
    System.gc();
    Workload wkld = new Workload(name);

    if (showCmdsItem.getState()) {
      consoleFrame.echoCmd((!runQueries ? "importprof " : "newwkld ") + name + " " + scriptFile);
    }

    // construct the Workload object from the script;
    // first, check if the file exists
    try {
      FileReader reader = new FileReader(scriptFile);
      reader.close();
    } catch (FileNotFoundException e) {
      System.out.println("couldn't open " + scriptFile);
      return;
    } catch (IOException e) {
      System.out.println("couldn't close " + scriptFile);
    }

    // now, check if it contains only queries
    int scriptId = 0;
    try {
      scriptId = Libgist.openScript(scriptFile);
    } catch (LibgistException e) {
      System.out.println("couldn't open (C) " + scriptFile);
      return;
    }
    char[] arg1 = new char[64 * 1024];
    StringBuffer arg1Buf = new StringBuffer();
    char[] arg2 = new char[64 * 1024];
    StringBuffer arg2Buf = new StringBuffer();
    // for (;;) {
    // int cmd = Libgist.getCommand(scriptId, arg1, arg2);
    // if (cmd == Libgist.EOF) break;
    // if (cmd != Libgist.FETCH) {
    // there should only be queries
    // System.out.println("Script file contains non-SELECT command");
    // return;
    // }
    // }

    if (runQueries) {
      // turn profiling on and execute queries
      // Libgist.setProfilingEnabled(true);
      Libgist.disableBps(true); // we don't want to stop at breakpoints

      // rescan queries
      try {
        scriptId = Libgist.openScript(scriptFile);
      } catch (LibgistException e) {
        System.out.println("couldn't open (C) " + scriptFile);
        return;
      }
      int cnt = 1;
      // for (;;) {
      // int cmd = Libgist.getCommand(scriptId, arg1, arg2);
      // if (cmd == Libgist.EOF) break;
      // arg1Buf.setLength(0);
      // arg1Buf.append(arg1, 0, strlen(arg1));
      // arg2Buf.setLength(0);
      // arg2Buf.append(arg2, 0, strlen(arg2));
      // OpThread.execCmd(LibgistCommand.FETCH, arg1Buf.toString(),
      // arg2Buf.toString(), false);
      // System.out.print(cnt + " ");
      // System.out.println(cnt + ": execute " + arg2Buf.toString() + " "
      // + arg1Buf.toString());
      // cnt++;
      // }
      System.out.println();

      Libgist.disableBps(false);
      // compute optimal clustering and some more statistics
      // Libgist.computeMetrics(wkld.filename);
    }

    // save profile
    try {
      // we're saving Java and C++ data in separate files (filename and filename.prof)
      // the profile object only contains the filename, the queries will be
      // read in from the file when the profile is opened (faster that way)
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(wkld.filename));
      out.writeObject(wkld);
      out.close();
      System.out.println("copy query file");
      Runtime.getRuntime().exec("cp " + scriptFile + " " + wkld.filename + ".queries");
      System.out.println("saving tree and profile");
      Libgist.saveToFile(wkld.filename + ".idx");
      if (runQueries) {
        // Libgist.saveProfile(wkld.filename + ".prof");
      }
    } catch (Exception e) {
      System.out.println("Error saving profile: " + e);
      return;
    }

    if (runQueries) {
      // turn profiling off (after the metrics were computed and
      // the profile saved)
      // Libgist.setProfilingEnabled(false);
    }
  }
Ejemplo n.º 23
0
  @Override
  public void run() {
    this.cardIndex = 0;

    File base = new File(Constants.IO.imageBaseDir);
    if (!base.exists()) {
      base.mkdir();
    }

    Connection.ProxyType configProxyType =
        Connection.ProxyType.valueByText(
            PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_TYPE, "None"));

    Proxy.Type type = Proxy.Type.DIRECT;
    switch (configProxyType) {
      case HTTP:
        type = Proxy.Type.HTTP;
        break;
      case SOCKS:
        type = Proxy.Type.SOCKS;
        break;
      case NONE:
      default:
        p = Proxy.NO_PROXY;
        break;
    }

    if (type != Proxy.Type.DIRECT) {
      try {
        String address = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_ADDRESS, "");
        Integer port =
            Integer.parseInt(
                PreferencesDialog.getCachedValue(PreferencesDialog.KEY_PROXY_PORT, "80"));
        p = new Proxy(type, new InetSocketAddress(address, port));
      } catch (Exception ex) {
        throw new RuntimeException("Gui_DownloadPictures : error 1 - " + ex);
      }
    }

    if (p != null) {
      HashSet<String> ignoreUrls = SettingsManager.getIntance().getIgnoreUrls();

      ArrayList<CardDownloadData> cardsToDownload = this.checkBox.isSelected() ? type2cards : cards;

      update(0, cardsToDownload.size());

      for (int i = 0; i < cardsToDownload.size() && !cancel; i++) {
        try {

          CardDownloadData card = cardsToDownload.get(i);

          log.info("Downloading card: " + card.getName() + " (" + card.getSet() + ")");

          String url;
          if (ignoreUrls.contains(card.getSet()) || card.isToken()) {
            if (card.getCollectorId() != 0) {
              continue;
            }
            url = cardImageSource.generateTokenUrl(card);
          } else {
            url = cardImageSource.generateURL(card);
          }

          if (url != null) {
            Logger.getLogger(this.getClass()).info(url);
            Runnable task = new DownloadTask(card, new URL(url), cardsToDownload.size());
            executor.execute(task);
          } else {
            synchronized (sync) {
              update(cardIndex + 1, cardsToDownload.size());
            }
          }

        } catch (Exception ex) {
          log.error(ex, ex);
        }
      }
      executor.shutdown();
      while (!executor.isTerminated()) {
        try {
          Thread.sleep(1000);
        } catch (InterruptedException ie) {
        }
      }
    }
    try {
      TVFS.umount();
    } catch (FsSyncException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null, "Couldn't unmount zip files", "Error", JOptionPane.ERROR_MESSAGE);
    } finally {
      System.gc();
    }
    closeButton.setText("Close");
  }
Ejemplo n.º 24
0
 private void closeFile() {
   upperTabbedPane.remove(upperTabbedPane.getSelectedComponent());
   menuBar.setFileOpen(upperTabbedPane.getComponentCount() > 0);
   System.gc();
 }
Ejemplo n.º 25
0
 private void refreshTableWithData(ArrayList<PasswordModel> models) {
   currentTableSelect = 0; // 重新默认选择第0行
   currentListContent = models; // 设置最新的数据
   listTable.setModel(new MainTableDataModel(models)); // 模型转换
   System.gc();
 }