List of usage examples for javax.swing SwingWorker isDone
public final boolean isDone()
From source file:com.marginallyclever.makelangelo.MainGUI.java
public boolean LoadImage(String filename) { // where to save temp output file? final String sourceFile = filename; final String destinationFile = GetTempDestinationFile(); LoadImageConverters();/*from w w w .ja v a 2s . c om*/ if (ChooseImageConversionOptions(false) == false) return false; final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100); pm.setProgress(0); pm.setMillisToPopup(0); final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() { @Override public Void doInBackground() { // read in image BufferedImage img; try { Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n"); // convert with style img = ImageIO.read(new File(sourceFile)); int style = GetDrawStyle(); Filter f = image_converters.get(style); TabToLog(); f.SetParent(this); f.SetProgressMonitor(pm); f.SetDestinationFile(destinationFile); f.Convert(img); TabToDraw(); previewPane.ZoomToFitPaper(); } catch (IOException e) { Log("<font color='red'>" + translator.get("Failed") + e.getLocalizedMessage() + "</font>\n"); recentFiles.remove(sourceFile); updateMenuBar(); } pm.setProgress(100); return null; } @Override public void done() { pm.close(); Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); PlayConversionFinishedSound(); LoadGCode(destinationFile); } }; s.addPropertyChangeListener(new PropertyChangeListener() { // Invoked when task's progress property changes. public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); pm.setProgress(progress); String message = String.format("%d%%.\n", progress); pm.setNote(message); if (s.isDone()) { Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); } else if (s.isCancelled() || pm.isCanceled()) { if (pm.isCanceled()) { s.cancel(true); } Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n"); } } } }); s.execute(); return true; }
From source file:com.marginallyclever.makelangelo.MainGUI.java
protected boolean LoadDXF(String filename) { if (ChooseImageConversionOptions(true) == false) return false; // where to save temp output file? final String destinationFile = GetTempDestinationFile(); final String srcFile = filename; TabToLog();/*from w w w. j a v a2 s.c o m*/ final ProgressMonitor pm = new ProgressMonitor(null, translator.get("Converting"), "", 0, 100); pm.setProgress(0); pm.setMillisToPopup(0); final SwingWorker<Void, Void> s = new SwingWorker<Void, Void>() { public boolean ok = false; @SuppressWarnings("unchecked") @Override public Void doInBackground() { Log("<font color='green'>" + translator.get("Converting") + " " + destinationFile + "</font>\n"); Parser parser = ParserBuilder.createDefaultParser(); double dxf_x2 = 0; double dxf_y2 = 0; OutputStreamWriter out = null; try { out = new OutputStreamWriter(new FileOutputStream(destinationFile), "UTF-8"); DrawingTool tool = machineConfiguration.GetCurrentTool(); out.write(machineConfiguration.GetConfigLine() + ";\n"); out.write(machineConfiguration.GetBobbinLine() + ";\n"); out.write("G00 G90;\n"); tool.WriteChangeTo(out); tool.WriteOff(out); parser.parse(srcFile, DXFParser.DEFAULT_ENCODING); DXFDocument doc = parser.getDocument(); Bounds b = doc.getBounds(); double width = b.getMaximumX() - b.getMinimumX(); double height = b.getMaximumY() - b.getMinimumY(); double cx = (b.getMaximumX() + b.getMinimumX()) / 2.0f; double cy = (b.getMaximumY() + b.getMinimumY()) / 2.0f; double sy = machineConfiguration.GetPaperHeight() * 10 / height; double sx = machineConfiguration.GetPaperWidth() * 10 / width; double scale = (sx < sy ? sx : sy) * machineConfiguration.paper_margin; sx = scale * (machineConfiguration.reverseForGlass ? -1 : 1); // count all entities in all layers Iterator<DXFLayer> layer_iter = (Iterator<DXFLayer>) doc.getDXFLayerIterator(); int entity_total = 0; int entity_count = 0; while (layer_iter.hasNext()) { DXFLayer layer = (DXFLayer) layer_iter.next(); Log("<font color='yellow'>Found layer " + layer.getName() + "</font>\n"); Iterator<String> entity_iter = (Iterator<String>) layer.getDXFEntityTypeIterator(); while (entity_iter.hasNext()) { String entity_type = (String) entity_iter.next(); List<DXFEntity> entity_list = (List<DXFEntity>) layer.getDXFEntities(entity_type); Log("<font color='yellow'>+ Found " + entity_list.size() + " of type " + entity_type + "</font>\n"); entity_total += entity_list.size(); } } // set the progress meter pm.setMinimum(0); pm.setMaximum(entity_total); // convert each entity layer_iter = doc.getDXFLayerIterator(); while (layer_iter.hasNext()) { DXFLayer layer = (DXFLayer) layer_iter.next(); Iterator<String> entity_type_iter = (Iterator<String>) layer.getDXFEntityTypeIterator(); while (entity_type_iter.hasNext()) { String entity_type = (String) entity_type_iter.next(); List<DXFEntity> entity_list = layer.getDXFEntities(entity_type); if (entity_type.equals(DXFConstants.ENTITY_TYPE_LINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFLine entity = (DXFLine) entity_list.get(i); Point start = entity.getStartPoint(); Point end = entity.getEndPoint(); double x = (start.getX() - cx) * sx; double y = (start.getY() - cy) * sy; double x2 = (end.getX() - cx) * sx; double y2 = (end.getY() - cy) * sy; // is it worth drawing this line? double dx = x2 - x; double dy = y2 - y; if (dx * dx + dy * dy < tool.GetDiameter() / 2.0) { continue; } dx = dxf_x2 - x; dy = dxf_y2 - y; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } if (tool.DrawIsOff()) { tool.WriteOn(out); } tool.WriteMoveTo(out, (float) x2, (float) y2); dxf_x2 = x2; dxf_y2 = y2; } } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_SPLINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFSpline entity = (DXFSpline) entity_list.get(i); entity.setLineWeight(30); DXFPolyline polyLine = DXFSplineConverter.toDXFPolyline(entity); boolean first = true; for (int j = 0; j < polyLine.getVertexCount(); ++j) { DXFVertex v = polyLine.getVertex(j); double x = (v.getX() - cx) * sx; double y = (v.getY() - cy) * sy; double dx = dxf_x2 - x; double dy = dxf_y2 - y; if (first == true) { first = false; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { // line does not start at last tool location, lift and move. if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } // else line starts right here, do nothing. } else { // not the first point, draw. if (tool.DrawIsOff()) tool.WriteOn(out); if (j < polyLine.getVertexCount() - 1 && dx * dx + dy * dy < tool.GetDiameter() / 2.0) continue; // less than 1mm movement? Skip it. tool.WriteMoveTo(out, (float) x, (float) y); } dxf_x2 = x; dxf_y2 = y; } } } else if (entity_type.equals(DXFConstants.ENTITY_TYPE_POLYLINE)) { for (int i = 0; i < entity_list.size(); ++i) { pm.setProgress(entity_count++); DXFPolyline entity = (DXFPolyline) entity_list.get(i); boolean first = true; for (int j = 0; j < entity.getVertexCount(); ++j) { DXFVertex v = entity.getVertex(j); double x = (v.getX() - cx) * sx; double y = (v.getY() - cy) * sy; double dx = dxf_x2 - x; double dy = dxf_y2 - y; if (first == true) { first = false; if (dx * dx + dy * dy > tool.GetDiameter() / 2.0) { // line does not start at last tool location, lift and move. if (tool.DrawIsOn()) { tool.WriteOff(out); } tool.WriteMoveTo(out, (float) x, (float) y); } // else line starts right here, do nothing. } else { // not the first point, draw. if (tool.DrawIsOff()) tool.WriteOn(out); if (j < entity.getVertexCount() - 1 && dx * dx + dy * dy < tool.GetDiameter() / 2.0) continue; // less than 1mm movement? Skip it. tool.WriteMoveTo(out, (float) x, (float) y); } dxf_x2 = x; dxf_y2 = y; } } } } } // entities finished. Close up file. tool.WriteOff(out); tool.WriteMoveTo(out, 0, 0); ok = true; } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } pm.setProgress(100); return null; } @Override public void done() { pm.close(); Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); PlayConversionFinishedSound(); if (ok) { LoadGCode(destinationFile); TabToDraw(); } Halt(); } }; s.addPropertyChangeListener(new PropertyChangeListener() { // Invoked when task's progress property changes. public void propertyChange(PropertyChangeEvent evt) { if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); pm.setProgress(progress); String message = String.format("%d%%\n", progress); pm.setNote(message); if (s.isDone()) { Log("<font color='green'>" + translator.get("Finished") + "</font>\n"); } else if (s.isCancelled() || pm.isCanceled()) { if (pm.isCanceled()) { s.cancel(true); } Log("<font color='green'>" + translator.get("Cancelled") + "</font>\n"); } } } }); s.execute(); return true; }
From source file:tauargus.model.batch.java
/** * Read the <SUPPRESS> command in a batch file with all its parameters * and calls the required suppression method * @throws ArgusException /* w w w . j a v a2 s.com*/ */ static void suppressBatch() throws ArgusException { String SuppressType, token; int i; boolean linked; String[] tail = new String[1]; String hs; final TableSet tableset; SuppressType = tokenizer.nextField("(").toUpperCase(); tail[0] = tokenizer.getLine(); tokenizer.clearLine(); token = nextToken(tail); int n = Integer.parseInt(token); if (n < 0 || n > TableService.numberOfTables()) { throw new ArgusException("Wrong table number in Suppression"); } linked = (n == 0); if (linked) { if (!SuppressType.equals("GH") && !SuppressType.equals("MOD")) { throw new ArgusException("Linked tables is only possible for Modular or Hypercube"); } for (i = 0; i < TableService.numberOfTables(); i++) { TableService.undoSuppress(i); } tableset = tauargus.service.TableService.getTable(0); } else { tableset = tauargus.service.TableService.getTable(n - 1); TableService.undoSuppress(n - 1); } switch (SuppressType) { case "GH": {//TabNo, A priori Bounds Percentage, ModelSize, ApplySingleton) token = nextChar(tail); if (token.equals(",")) { token = nextToken(tail); tableset.ghMiterAprioryPercentage = Integer.parseInt(token); token = nextChar(tail); } if (token.equals(",")) { token = nextToken(tail); tableset.ghMiterSize = Integer.parseInt(token); token = nextChar(tail); } if (token.equals(",")) { token = nextToken(tail); tableset.ghMiterApplySingleton = token.equals("1"); token = nextChar(tail); } if (linked) { LinkedTables.buildCoverTable(); LinkedTables.runLinkedGHMiter(); hs = ""; TableSet ts; for (i = 0; i < TableService.numberOfTables(); i++) { ts = tauargus.service.TableService.getTable(i); hs = hs + ts.CountSecondaries() + " cells have been suppressed in table " + (i + 1) + "\n"; } hs = hs.substring(0, hs.length() - 1); } else { GHMiter.RunGHMiter(tableset); hs = tableset.CountSecondaries() + " cells have been suppressed"; } reportProgress("The hypercube procedure has been applied\n" + hs); break; } case "MOD": {//TabNo, MaxTimePerSubtable token = nextChar(tail); if (token.equals(",")) { token = nextToken(tail); tableset.maxHitasTime = Integer.parseInt(token); Application.generalMaxHitasTime = tableset.maxHitasTime; // The generalMAxHitasTime is used in the runModular procedure. token = nextChar(tail); } i = 0; while (token.equals(",") && (i < 3)) { i++; token = nextToken(tail); switch (i) { case 1: tableset.singletonSingletonCheck = token.equals("1"); break; case 2: tableset.singletonMultipleCheck = token.equals("1"); break; case 3: tableset.minFreqCheck = token.equals("1"); break; } token = nextChar(tail); } if (linked) { LinkedTables.buildCoverTable(); LinkedTables.runLinkedModular(null); } else { // single table if (token.equals(",")) { //MSC specified token = nextToken(tail); tableset.maxScaleCost = StrUtils.toDouble(token); if (tableset.maxScaleCost <= 0) { throw new ArgusException("Illegal Max Scaling Cost: " + token); } } try { // Make sure that PropertyChanges are not processed in batch-mode by overriding propertyChange to do nothing if (Application.batchType() == Application.BATCH_COMMANDLINE) { OptiSuppress.runModular(tableset, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { } }); reportProgressInfo("The modular procedure has been applied\n" + tableset.CountSecondaries() + " cells have been suppressed"); } else { final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>( ProgressSwingWorker.DOUBLE, "Modular approach") { @Override protected Integer doInBackground() throws ArgusException, Exception { super.doInBackground(); OptiSuppress.runModular(tableset, getPropertyChangeListener()); reportProgressInfo("The modular procedure has been applied\n" + tableset.CountSecondaries() + " cells have been suppressed"); return null; } @Override protected void done() { super.done(); try { get(); tableset.undoAudit(); // Wat doet dit? Hoeft niet. Alleen voor GUI // ((AbstractTableModel)table.getModel()).fireTableDataChanged(); } catch (InterruptedException ex) { logger.log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { JOptionPane.showMessageDialog(null, ex.getCause().getMessage()); } } }; worker.execute(); while (!worker.isDone()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } } } } catch (IOException ex) { throw new ArgusException("Modular failed\n" + ex.getMessage()); } } break; } case "OPT": {//TabNo, MaxComputingTime if (n == 0) { throw new ArgusException("Linked tables is not possible for Optimal"); } token = nextChar(tail); if (token.equals(",")) { token = nextToken(tail); tableset.maxHitasTime = Integer.parseInt(token); token = nextChar(tail); } if (Application.batchType() == Application.BATCH_COMMANDLINE) { try { OptiSuppress.runOptimal(tableset, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { } }, false, false, 1); } catch (IOException ex) { } } else { // From menu with swingworker final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>( ProgressSwingWorker.DOUBLE, "Modular approach") { @Override protected Integer doInBackground() throws ArgusException, Exception { super.doInBackground(); try { OptiSuppress.runOptimal(tableset, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { } }, false, false, 1); } catch (IOException ex) { } return null; } @Override protected void done() { super.done(); try { get(); } catch (InterruptedException ex) { logger.log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { JOptionPane.showMessageDialog(null, ex.getCause().getMessage()); } } }; worker.execute(); while (!worker.isDone()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } } } //TODO reportProgressInfo("The optimal procedure has been applied\n" + tableset.CountSecondaries() + " cells have been suppressed"); break; } case "RND": {//TabNo, RoundingBase, Steps, Time, Partitions, StopRule // OK after Roundbase: Default Step = 0 (no step), time = 10, Nopartitions part = 0, stoprule = 2(optimal) if (n == 0) { throw new ArgusException("Linked tables is not possible for Rounding"); } if (Application.solverSelected == Application.SOLVER_CPLEX) //{throw new ArgusException("Controlled rounding cannot be used when Cplex is selected as solver");} { reportProgressInfo( "Whether controlled rounding can be used when Cplex is selected as solver, depends on your specific license.\n Incorrect license may cause errors."); } token = nextChar(tail); if (!token.equals(",")) { throw new ArgusException("a komma(,) expected"); } token = nextToken(tail); tableset.roundBase = Integer.parseInt(token); long mrb = TableSet.computeMinRoundBase(tableset); if (tableset.roundBase < mrb) { throw new ArgusException( "The rounding base is too small\n" + "A minimum of " + mrb + " is required"); } //set the defaults tableset.roundMaxStep = 0; tableset.roundMaxTime = 10; tableset.roundPartitions = 0; tableset.roundStoppingRule = 2; token = nextChar(tail); if (token.equals(",")) { //steps token = nextToken(tail); tableset.roundMaxStep = StrUtils.toInteger(token); token = nextChar(tail); } else { if (!token.equals(")")) throw new ArgusException("a komma(,) or \")\" expected"); } if (token.equals(",")) { //max time token = nextToken(tail); tableset.roundMaxTime = Integer.parseInt(token); if (tableset.roundMaxTime <= 0) { throw new ArgusException("Illegal value for max time: " + tableset.roundMaxTime); } token = nextChar(tail); } else { if (!token.equals(")")) throw new ArgusException("a komma(,) or \")\" expected"); } if (token.equals(",")) { //partitions token = nextToken(tail); tableset.roundPartitions = Integer.parseInt(token); if (tableset.roundPartitions < 0 || tableset.roundPartitions > 1) { throw new ArgusException("Illegal value for partitions: " + tableset.roundPartitions); } token = nextChar(tail); } else { if (!token.equals(")")) throw new ArgusException("a komma(,) or \")\" expected"); } if (token.equals(",")) { //Stop rule token = nextToken(tail); tableset.roundStoppingRule = Integer.parseInt(token); if (tableset.roundStoppingRule <= 0 || tableset.roundStoppingRule > 2) { throw new ArgusException("Illegal value for max time: " + tableset.roundStoppingRule); } token = nextChar(tail); } else { if (!token.equals(")")) throw new ArgusException("a komma(,) or \")\" expected"); } if (token.equals(",")) { //Unit cost function token = nextToken(tail); if (token.equals("1")) { tableset.roundUnitCost = true; } else if (token.equals("0")) { tableset.roundUnitCost = false; } else { throw new ArgusException("Illegal value UnitCost parameter: only 0 or 1 allowed"); } token = nextChar(tail); } else { if (!token.equals(")")) throw new ArgusException("a komma(,) or \")\" expected"); } // all parameters have been handeled. Run the rounder. if (Application.batchType() == Application.BATCH_COMMANDLINE) { try { OptiSuppress.runRounder(tableset, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { } }); } catch (IOException ex) { throw new ArgusException(ex.getMessage()); } } else //batch run from menu { final SwingWorker<Integer, Void> worker = new ProgressSwingWorker<Integer, Void>( ProgressSwingWorker.ROUNDER, "Rounding") { @Override protected Integer doInBackground() throws ArgusException, Exception { super.doInBackground(); try { OptiSuppress.runRounder(tableset, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { } }); } catch (IOException ex) { } return null; } @Override protected void done() { super.done(); try { get(); } catch (InterruptedException ex) { logger.log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { JOptionPane.showMessageDialog(null, ex.getCause().getMessage()); } } }; worker.execute(); while (!worker.isDone()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } } } reportProgressInfo("The table has been rounded\n" + "Number of steps: " + tableset.roundMaxStep + "\n" + "Max step: " + StrUtils.formatDouble(tableset.roundMaxJump, tableset.respVar.nDecimals)); break; } case "CTA": { try { OptiSuppress.RunCTA(tableset, false); reportProgress("CTA run completed"); } catch (IOException ex) { throw new ArgusException(ex.getMessage()); } break; } case "NET": { OptiSuppress.TestNetwork(tableset); OptiSuppress.RunNetwork(tableset); break; } default: throw new ArgusException("Unknown suppression method (" + SuppressType + ") found"); } }