/** * Loads the drawing. By convention this method is invoked on a worker thread. * * @param progress A ProgressIndicator to inform the user about the progress of the operation. * @return The Drawing that was loaded. */ protected Drawing loadDrawing(ProgressIndicator progress) throws IOException { Drawing drawing = createDrawing(); if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); URLConnection uc = url.openConnection(); // Disable caching. This ensures that we always request the // newest version of the drawing from the server. // (Note: The server still needs to set the proper HTTP caching // properties to prevent proxies from caching the drawing). if (uc instanceof HttpURLConnection) { ((HttpURLConnection) uc).setUseCaches(false); } // Read the data into a buffer int contentLength = uc.getContentLength(); InputStream in = uc.getInputStream(); try { if (contentLength != -1) { in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); progress.setIndeterminate(false); } BufferedInputStream bin = new BufferedInputStream(in); bin.mark(512); // Read the data using all supported input formats // until we succeed IOException formatException = null; for (InputFormat format : drawing.getInputFormats()) { try { bin.reset(); } catch (IOException e) { uc = url.openConnection(); in = uc.getInputStream(); in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); bin = new BufferedInputStream(in); bin.mark(512); } try { bin.reset(); format.read(bin, drawing, true); formatException = null; break; } catch (IOException e) { formatException = e; } } if (formatException != null) { throw formatException; } } finally { in.close(); } } return drawing; }
@Override public void mouseMoved(MouseEvent evt) { Point point = evt.getPoint(); updateCursor(editor.findView((Container) evt.getSource()), point); DrawingView view = editor.findView((Container) evt.getSource()); updateCursor(view, point); if (view == null || editor.getActiveView() != view) { clearHoverHandles(); } else { // Search first, if one of the selected figures contains // the current mouse location. Only then search for other // figures. This search sequence is consistent with the // search sequence of the SelectionTool. Figure figure = null; Point2D.Double p = view.viewToDrawing(point); for (Figure f : view.getSelectedFigures()) { if (f.contains(p)) { figure = f; } } if (figure == null) { figure = view.findFigure(point); Drawing drawing = view.getDrawing(); while (figure != null && !figure.isSelectable()) { figure = drawing.findFigureBehind(p, figure); } } updateHoverHandles(view, figure); } }
/** Reads the view from the specified uri. */ @Override public void read(URI f, URIChooser chooser) throws IOException { try { final Drawing drawing = createDrawing(); InputFormat inputFormat = drawing.getInputFormats().get(0); inputFormat.read(f, drawing, true); SwingUtilities.invokeAndWait( new Runnable() { @Override public void run() { view.getDrawing().removeUndoableEditListener(undo); view.setDrawing(drawing); view.getDrawing().addUndoableEditListener(undo); undo.discardAllEdits(); } }); } catch (InterruptedException e) { InternalError error = new InternalError(); e.initCause(e); throw error; } catch (InvocationTargetException e) { InternalError error = new InternalError(); e.initCause(e); throw error; } }
public void executePress(Point p, Drawing dwg) { // Get the color we want the ellipse to have from the drawing Color c = dwg.getColor(); // Create the ellipse and store it in the instance variable s = new Ellipse(p.x, p.y, 0, 0, c); // Store the starting click point oP oP = p; // Add the ellipse to the drawing dwg.add(s); // Record history dwg.recordHistoryItem(new HistoryAction(s, dwg, false)); }
/** Load a Drawing from a file */ protected void loadDrawing(StorageFormat restoreFormat, String file) { try { Drawing restoredDrawing = restoreFormat.restore(file); if (restoredDrawing != null) { restoredDrawing.setTitle(file); newWindow(restoredDrawing); } else { showStatus("Unknown file type: could not open file '" + file + "'"); } } catch (IOException e) { showStatus("Error: " + e); } }
private void drawBalance(Graphics g) // POST: Draws the balance of the current player { Font font; // Font used to draw balance String message; // Message for balance Color oldColor; // Sets for color int x1; // Upper-left x coordinate int y1; // Upper-left y coordinate int x2; // Bottom-right x coordinate int y2; // Bottom-right y coordinate int width; // Width of the dialogue box int height; // Height of the dialogue box int offset; // Offset so the dialogue box is positioned int balance; // Offset so the dialogue box is positioned User player; // User value for the player player = usersArray[0]; balance = player.getBalance(); oldColor = g.getColor(); x1 = ScaledPoint.scalerToX(0.72); y1 = ScaledPoint.scalerToY(0.81); x2 = ScaledPoint.scalerToX(0.88); y2 = ScaledPoint.scalerToY(0.86); width = x2 - x1; height = y2 - y1; message = "Balance:"; font = Drawing.getFont(message, width, height, FONTNAME, FONTSTYLE); offset = (width - getFontMetrics(font).stringWidth(message)) / 2; g.setColor(Color.WHITE); g.drawString(message, x1 + offset, y2); x1 = ScaledPoint.scalerToX(0.72); y1 = ScaledPoint.scalerToY(0.865); x2 = ScaledPoint.scalerToX(0.88); y2 = ScaledPoint.scalerToY(0.915); width = x2 - x1; height = y2 - y1; message = "$" + Integer.toString(balance); font = Drawing.getFont(message, width, height, FONTNAME, FONTSTYLE); offset = (width - getFontMetrics(font).stringWidth(message)) / 2; g.drawString(message, x1 + offset, y2); g.setColor(oldColor); }
private void drawStoreMessage(Graphics g) // PRE: g must be initialized. // POST: Draws the store's dialogue box beneath the store image. { int x1; // Upper-left x coordinate. int y1; // Upper-left y coordinate. int x2; // Bottom-right x coordinate. int y2; // Bottom-right y coordinate. int width; // Width of dialogue box. int height; // Height of dialogue box. int numLines; // Number of lines in dialogue box. String message; // Message to be printed. x1 = ScaledPoint.scalerToX(storeMessagePos[0].getXScaler() + 0.01); y1 = ScaledPoint.scalerToY(storeMessagePos[0].getYScaler() + 0.01); x2 = ScaledPoint.scalerToX(storeMessagePos[1].getXScaler() - 0.01); y2 = ScaledPoint.scalerToY(storeMessagePos[1].getYScaler() - 0.01); width = x2 - x1; height = y2 - y1; Drawing.drawRoundedRect(g, storeMessagePos, Color.WHITE); switch (store) // change message based on value of store. { case 0: message = "If yer lookin' for a weapon, you've come to the right place."; break; case 1: message = "Welcome! You'll not find tougher steel elsewhere."; break; case 2: message = "Come! I guarantee you'll find something that catches your eye!"; break; case 3: message = "Some say that many of my goods are trash... They're right."; break; default: message = "I don't know how you got here..."; } numLines = 1; while (!(Drawing.drawWrappedString(g, message, numLines++, x1, y1, width, height))) ; // while we need more lines for the message }
private void showHelp(Graphics g) // PRE: g must be initialized. // POST: Displays the help image to the screen. { JOptionPane.showMessageDialog(this, "Once you are satisfied, click anywhere to continue!"); Drawing.drawImage(g, 0, 0, getWidth(), getHeight(), ".\\images\\help.jpg"); }
private Figure findConnectableFigure(Point2D.Double p, Drawing drawing) { for (Figure f : drawing.getFiguresFrontToBack()) { if (!f.includes(getOwner()) && f.canConnect() && f.contains(p)) { return f; } } return null; }
protected void loadDrawing(String param) { if (param == fgUntitled) { fDrawing.release(); initDrawing(); return; } String filename = getParameter(param); if (filename != null) { readDrawing(filename); } }
private Figure findConnectableFigure(int x, int y, Drawing drawing) { FigureEnumeration k = drawing.figuresReverse(); while (k.hasMoreElements()) { Figure figure = k.nextFigure(); if (!figure.includes(getConnection()) && figure.canConnect()) { if (figure.containsPoint(x, y)) { return figure; } } } return null; }
public void setData(String text) { if (text != null && text.length() > 0) { InputStream in = null; try { Object result = null; Drawing drawing = createDrawing(); // Try to read the data using all known input formats. for (InputFormat fmt : drawing.getInputFormats()) { try { fmt.read(in, drawing); in = new ByteArrayInputStream(text.getBytes("UTF8")); result = drawing; break; } catch (IOException e) { result = e; } } if (result instanceof IOException) { throw (IOException) result; } setDrawing(drawing); } catch (Throwable e) { getDrawing().removeAllChildren(); SVGTextFigure tf = new SVGTextFigure(); tf.setText(e.getMessage()); tf.setBounds(new Point2D.Double(10, 10), new Point2D.Double(100, 100)); getDrawing().add(tf); e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } }
private void drawStoreName(Graphics g) // PRE: g must be initialized. // POST: Draws the store name along with a rounded border at the top of the window. { int rectWidth; // The width of the drawing area. int rectHeight; // The height of the drawing area. String storeName; // The name of the store. Font font; // The font to be used. rectWidth = nameLocation[1].getScaledX() - nameLocation[0].getScaledX(); rectHeight = nameLocation[1].getScaledY() - nameLocation[0].getScaledY(); switch (store) // set message based on store value. { case 0: storeName = "Raneac's Crucible"; break; case 1: storeName = "The Iron Maiden"; break; case 2: storeName = "The Grand Bazaar"; break; default: storeName = "Miko's Wares"; } font = Drawing.getFont(storeName, rectWidth, rectHeight, FONTNAME, FONTSTYLE); g.setFont(font); g.setColor(Color.WHITE); g.drawString( storeName, nameLocation[0].getScaledX(), (int) (nameLocation[1].getScaledY() * .98)); Drawing.drawRoundedRect(g, nameLocation, Color.WHITE); }
private void readFromStorableInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); StorableInput input = new StorableInput(stream); fDrawing.release(); fDrawing = (Drawing) input.readStorable(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error:" + e); } }
private void readFromObjectInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); ObjectInput input = new ObjectInputStream(stream); fDrawing.release(); fDrawing = (Drawing) input.readObject(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error: " + e); } catch (ClassNotFoundException e) { initDrawing(); showStatus("Class not found: " + e); } }
private void drawStoreImage(Graphics g) // PRE: g must be initialized. // POST: Draws the image associated with the store at the storeImage location. // All images should be located in the \images\ directory. { String filePath; // the image file path int x; // x coordinate of upper-right corner of image. int y; // y coordinate of upper-right corner of image. int width; // width of image int height; // height of image x = storeImage[0].getScaledX(); y = storeImage[0].getScaledY(); width = storeImage[1].getScaledX() - storeImage[0].getScaledX(); height = storeImage[1].getScaledY() - storeImage[0].getScaledY(); switch (store) // initialize file path to image based on store { case 0: filePath = ".\\images\\weaponSmith.jpg"; break; case 1: filePath = ".\\images\\armorSmith.jpg"; break; case 2: filePath = ".\\images\\accessoryMerchant.jpg"; break; case 3: filePath = ".\\images\\generalMerchant.png"; break; default: filePath = ".\\images\\generalMerchant.png"; } Drawing.drawImage(g, x, y, width, height, filePath); }
private void drawStoreBG(Graphics g) // PRE: g must be initialized. // POST: Draws the background associated with store. { switch (store) // draw background based on value of store. { case 0: Drawing.drawGradient( g, new Color(180, 80, 80), new Color(20, 0, 0), 0, 0, getWidth(), getHeight() / 2); Drawing.drawGradient( g, new Color(20, 0, 0), new Color(180, 80, 80), 0, getHeight() / 2, getWidth(), getHeight() / 2 + 1); break; case 1: Drawing.drawGradient( g, new Color(80, 180, 80), new Color(0, 20, 0), 0, 0, getWidth(), getHeight()); break; case 2: Drawing.drawGradient( g, new Color(230, 170, 50), new Color(60, 20, 0), 0, 0, getWidth(), getHeight()); break; case 3: Drawing.drawGradient( g, new Color(120, 120, 120), new Color(20, 20, 20), 0, 0, getWidth(), getHeight()); break; default: Drawing.drawGradient( g, new Color(80, 80, 180), new Color(0, 0, 20), 0, 0, getWidth(), getHeight()); } }
/** * Writes the drawing to the specified output stream. * This method applies the specified drawingTransform to the drawing, and draws * it on an image of the specified getChildCount. */ public void write(OutputStream out, Drawing drawing, AffineTransform drawingTransform, Dimension imageSize) throws IOException { write(out, drawing.getChildren(), drawingTransform, imageSize); }
public void write(OutputStream out, Drawing drawing) throws IOException { write(out, drawing.getChildren()); }
public void setDrawing(Drawing d) { undoManager.discardAllEdits(); view.getDrawing().removeUndoableEditListener(undoManager); view.setDrawing(d); d.addUndoableEditListener(undoManager); }
/** * On click, if a shape has been clicked, change its color to the Drawing object's current set * color. */ public void executeClick(Point p, Drawing dwg) { Shape clickedShape = dwg.getFrontmostContainer(p); if (clickedShape != null) clickedShape.setColor(dwg.getColor()); }
private void drawInventory(Graphics g) // PRE: g must be initialized. // POST: Draws the inventory of the store if mode == 0, else draws the players inventory. // If an item is selected, its border is highlighted white. { Graphics2D g2; // Graphics 2D object to allow for different brush stroke widths. Color start; // The start color for the inventory window gradient. Color end; // The end color for the inventory window gradient. int x1; // Upper-left x coordinate. int y1; // Upper-left y coordinate. int x2; // Bottom-right x coordinate. int y2; // Bottom-right y coordinate. int width; // Width of the inventory box. int height; // Height of the inventory box. int itemHeight; // The height of an item box. int itemY; // The y coordinate of the item. Item currentItem; // Item to store the current item g2 = (Graphics2D) g; start = new Color(120, 120, 220); end = new Color(50, 50, 150); x1 = inventoryPos[0].getScaledX(); y1 = inventoryPos[0].getScaledY(); x2 = inventoryPos[1].getScaledX(); y2 = inventoryPos[1].getScaledY(); width = x2 - x1; height = y2 - y1; while (height % ITEMSPERPAGE != 0) // ensure that the item boxes do not fall short of the window { height = ++y2 - y1; } itemHeight = height / ITEMSPERPAGE; Drawing.drawGradient(g2, start, end, x1, y1, width, height / 2); Drawing.drawGradient(g2, end, start, x1, y1 + height / 2, width, height / 2); g2.setColor(Color.BLACK); g2.setStroke(new BasicStroke(3)); g2.drawRect(--x1, --y1, ++width, height); g2.setColor(Color.WHITE); switch (store) // Chooses the current store { case 0: connectItems(getUserItems("Weapon", orderToSort)); break; case 1: connectItems(getUserItems("ArmorSmith", orderToSort)); break; case 2: connectItems(getUserItems("Accessory", orderToSort)); break; case 3: connectItems(getUserItems("General", orderToSort)); break; } if (mode) // Sets mode to true for user inventory and displays { connectItems(getUserItems("Player", orderToSort)); } int count = 0; // count = currentPage * ITEMSPERPAGE ; try // Try loading 10 items per page { currentItem = null; count = currentPage * ITEMSPERPAGE; for (int i = 0; i < ITEMSPERPAGE; i++) // draw each item into the window { if (i > itemsArray.length - 1) // Check if i excceds the array size { return; } itemY = y1 + (itemHeight) * i; currentItem = itemsArray[count]; if (itemSelected == i) // if the item was selected, highlight it { g2.drawRect(x1, itemY, width, itemHeight); } drawItem(g2, i, currentItem); count++; } } catch (Exception e) // Catch generic exception and print it out { System.err.println(e.toString()); System.err.println("Oh no, not like this..."); } }
private void drawItem(Graphics g, int item, Item currentItem) { Font font; // The font to be used. int x1; // The first x coordinate of drawing area. int y1; // The first y coordinate of drawing area. int x2; // The second x coordinate of drawing area. int y2; // The second y coordinate of drawing area. int width; // Width of drawing area. int height; // Height of drawing area. int iconX; // x coordinate of the icon. int iconY; // y coordinate of the icon. int iconLength; // Length of the icon. int itemNameX; // The x coordinate of the item name. int itemNameLength; // The length of the item name. int itemPriceX; // The x coordinate of the item price. int itemPriceWidth; // The width of the item price. x1 = itemPositions[item][0].getScaledX(); x2 = itemPositions[item][1].getScaledX(); y1 = itemPositions[item][0].getScaledY(); y2 = itemPositions[item][1].getScaledY(); width = x2 - x1; height = y2 - y1; iconX = x1 + (int) (width * .01); iconY = y1 + (int) (height * .1); iconLength = (int) (height * .8); Drawing.drawImage(g, iconX, iconY, iconLength, iconLength, currentItem.getItemPath()); itemNameX = iconX + (int) (iconLength * 1.5); itemNameLength = (int) (width * 0.6); font = Drawing.getFont( currentItem.getItemName(), itemNameLength, (int) (iconLength * 0.8), FONTNAME, FONTSTYLE); g.setFont(font); g.setColor(Color.WHITE); g.drawString(currentItem.getItemName(), itemNameX, iconY + (int) (iconLength * 0.9)); itemPriceX = x1 + (int) (width * 0.8); itemPriceWidth = (int) (width * 0.15); font = Drawing.getFont( Integer.toString(currentItem.getPrice()), itemPriceWidth, iconLength, FONTNAME, FONTSTYLE); g.setFont(font); g.setColor(Color.WHITE); g.drawString( Integer.toString(currentItem.getPrice()), itemPriceX, iconY + (int) (iconLength * .9)); return; }
// Thread's run method aimed at creating a bitmap asynchronously public void run() { Drawing drawing = new Drawing(); PicText rawPicText = new PicText(); String s = ((PicText) element).getText(); rawPicText.setText(s); drawing.add( rawPicText); // bug fix: we must add a CLONE of the PicText, otherwise it loses it former // parent... (then pb with the view ) drawing.setNotparsedCommands( "\\newlength{\\jpicwidth}\\settowidth{\\jpicwidth}{" + s + "}" + CR_LF + "\\newlength{\\jpicheight}\\settoheight{\\jpicheight}{" + s + "}" + CR_LF + "\\newlength{\\jpicdepth}\\settodepth{\\jpicdepth}{" + s + "}" + CR_LF + "\\typeout{JPICEDT INFO: \\the\\jpicwidth, \\the\\jpicheight, \\the\\jpicdepth }" + CR_LF); RunExternalCommand.Command commandToRun = RunExternalCommand.Command.BITMAP_CREATION; // RunExternalCommand command = new RunExternalCommand(drawing, contentType,commandToRun); boolean isWriteTmpTeXfile = true; String bitmapExt = "png"; // [pending] preferences String cmdLine = "{i}/unix/tetex/create_bitmap.sh {p} {f} " + bitmapExt + " " + fileDPI; // [pending] preferences ContentType contentType = getContainer().getContentType(); RunExternalCommand.isGUI = false; // System.out, no dialog box // [pending] debug RunExternalCommand command = new RunExternalCommand(drawing, contentType, cmdLine, isWriteTmpTeXfile); command .run(); // synchronous in an async. thread => it's ok (anyway, we must way until the LaTeX // process has completed) if (wantToComputeLatexDimensions) { // load size of text: try { File logFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + ".log"); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(logFile)); } catch (FileNotFoundException fnfe) { System.out.println("Cannot find log file! " + fnfe.getMessage()); System.out.println(logFile); } catch (IOException ioex) { System.out.println("Log file IO exception"); ioex.printStackTrace(); } // utile ? System.out.println("Log file created! file=" + logFile); getDimensionsFromLogFile(reader, (PicText) element); syncStringLocation(); // update dimensions syncBounds(); syncFrame(); SwingUtilities.invokeLater( new Thread() { public void run() { repaint(null); } }); // repaint(null); // now that dimensions are available, we force a repaint() [pending] // smart-repaint ? } catch (Exception e) { e.printStackTrace(); } } if (wantToGetBitMap) { // load image: try { File bitmapFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + "." + bitmapExt); this.image = ImageIO.read(bitmapFile); System.out.println( "Bitmap created! file=" + bitmapFile + ", width=" + image.getWidth() + "pixels, height=" + image.getHeight() + "pixels"); if (image == null) return; syncStringLocation(); // sets strx, stry, and dimensions of text syncBounds(); // update the AffineTransform that will be applied to the bitmap before displaying on screen PicText te = (PicText) element; text2ModelTr.setToIdentity(); // reset PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf); text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR ! text2ModelTr.translate(te.getLeftX(), te.getTopY()); text2ModelTr.scale( te.getWidth() / image.getWidth(), -(te.getHeight() + te.getDepth()) / image.getHeight()); // [pending] should do something special to avoid dividing by 0 or setting a rescaling // factor to 0 [non invertible matrix] (java will throw an exception) syncFrame(); SwingUtilities.invokeLater( new Thread() { public void run() { repaint(null); } }); // repaint(null); // now that bitmap is available, we force a repaint() [pending] // smart-repaint ? } catch (Exception e) { e.printStackTrace(); } } }
/** Writes the view to the specified uri. */ @Override public void write(URI f, URIChooser chooser) throws IOException { Drawing drawing = view.getDrawing(); OutputFormat outputFormat = drawing.getOutputFormats().get(0); outputFormat.write(f, drawing); }
@Override public void mousePressed(MouseEvent evt) { if (getView() != null && getView().isEnabled()) { super.mousePressed(evt); DrawingView view = getView(); Handle handle = view.findHandle(anchor); Tool newTracker = null; if (handle != null) { newTracker = getHandleTracker(handle); } else { Figure figure; Drawing drawing = view.getDrawing(); Point2D.Double p = view.viewToDrawing(anchor); if (isSelectBehindEnabled() && (evt.getModifiersEx() & (InputEvent.ALT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK)) != 0) { // Select a figure behind the current selection figure = view.findFigure(anchor); while (figure != null && !figure.isSelectable()) { figure = drawing.findFigureBehind(p, figure); } HashSet<Figure> ignoredFigures = new HashSet<Figure>(view.getSelectedFigures()); ignoredFigures.add(figure); Figure figureBehind = view.getDrawing().findFigureBehind(view.viewToDrawing(anchor), ignoredFigures); if (figureBehind != null) { figure = figureBehind; } } else { // Note: The search sequence used here, must be // consistent with the search sequence used by the // DefaultHandleTracker, the DefaultSelectAreaTracker and DelegationSelectionTool. // If possible, continue to work with the current selection figure = null; if (isSelectBehindEnabled()) { for (Figure f : view.getSelectedFigures()) { if (f.contains(p)) { figure = f; break; } } } // If the point is not contained in the current selection, // search for a figure in the drawing. if (figure == null) { figure = view.findFigure(anchor); while (figure != null && !figure.isSelectable()) { figure = drawing.findFigureBehind(p, figure); } } } if (figure != null && figure.isSelectable()) { newTracker = getDragTracker(figure); } else { if (!evt.isShiftDown()) { view.clearSelection(); view.setHandleDetailLevel(0); } newTracker = getSelectAreaTracker(); } } if (newTracker != null) { setTracker(newTracker); } tracker.mousePressed(evt); } }