예제 #1
0
  public BPRadSprite(float rad) {
    super(null, null);

    int per = Math.max(24, (int) (2 * Math.PI * (double) rad / 11.0D));
    FloatBuffer pa = Utils.mkfbuf(per * 3 * 2);
    FloatBuffer na = Utils.mkfbuf(per * 3 * 2);
    ShortBuffer sa = Utils.mksbuf(per * 6);

    for (int i = 0; i < per; ++i) {
      float s = (float) Math.sin(2 * Math.PI * (double) i / (double) per);
      float c = (float) Math.cos(2 * Math.PI * (double) i / (double) per);
      pa.put(i * 3 + 0, c * rad).put(i * 3 + 1, s * rad).put(i * 3 + 2, 10.0F);
      pa.put((per + i) * 3 + 0, c * rad)
          .put((per + i) * 3 + 1, s * rad)
          .put((per + i) * 3 + 2, -10.0F);
      na.put(i * 3 + 0, c).put(i * 3 + 1, s).put(i * 3 + 2, 0.0F);
      na.put((per + i) * 3 + 0, c).put((per + i) * 3 + 1, s).put((per + i) * 3 + 2, 0.0F);
      int v = i * 6;
      sa.put(v + 0, (short) i).put(v + 1, (short) (i + per)).put(v + 2, (short) ((i + 1) % per));
      sa.put(v + 3, (short) (i + per))
          .put(v + 4, (short) ((i + 1) % per + per))
          .put(v + 5, (short) ((i + 1) % per));
    }

    this.posa = new VertexArray(pa);
    this.nrma = new NormalArray(na);
    this.sidx = sa;
  }
예제 #2
0
  @SuppressWarnings({"unchecked"})
  public SimulationPanel(final MainFrame frame, final PartitionDataList dataList) {

    this.frame = frame;
    this.dataList = dataList;

    optionPanel = new OptionsPanel(12, 12, SwingConstants.CENTER);

    simulationsNumberField = new WholeNumberField(1, Integer.MAX_VALUE);
    simulationsNumberField.setColumns(10);
    simulationsNumberField.setValue(dataList.simulationsCount);
    optionPanel.addComponentWithLabel("Number of simulations:", simulationsNumberField);

    setSeed = new JCheckBox();
    setSeed.addItemListener(new SetSeedCheckBoxListener());
    setSeed.setSelected(dataList.setSeed);
    optionPanel.addComponentWithLabel("Set seed:", setSeed);

    startingSeedNumberField = new WholeNumberField(1, Long.MAX_VALUE);
    startingSeedNumberField.setColumns(10);
    startingSeedNumberField.setValue(dataList.startingSeed);
    startingSeedNumberField.setEnabled(dataList.setSeed);
    optionPanel.addComponentWithLabel("Starting seed:", startingSeedNumberField);

    outputFormat = new JComboBox();
    optionPanel.addComponentWithLabel("Output format:", outputFormat);
    outputFormatModel = new DefaultComboBoxModel(SimpleAlignment.OutputType.values());
    outputFormat.setModel(outputFormatModel);

    outputAncestralSequences = new JCheckBox();
    outputAncestralSequences.addItemListener(new outputAncestralSequencesCheckBoxListener());
    outputAncestralSequences.setSelected(dataList.useParallel);
    optionPanel.addComponentWithLabel("Output ancestral sequences:", outputAncestralSequences);

    useParallel = new JCheckBox();
    useParallel.addItemListener(new UseParallelCheckBoxListener());
    useParallel.setSelected(dataList.useParallel);
    optionPanel.addComponentWithLabel("Use parallel implementation:", useParallel);

    // Buttons holder
    JPanel buttonsHolder = new JPanel();
    buttonsHolder.setOpaque(false);

    // simulate button
    simulate = new JButton("Simulate", Utils.createImageIcon(Utils.BIOHAZARD_ICON));
    simulate.addActionListener(new ListenSimulate());
    buttonsHolder.add(simulate);

    generateXML = new JButton("Generate XML", Utils.createImageIcon(Utils.HAMMER_ICON));
    generateXML.addActionListener(new ListenGenerateXML());
    buttonsHolder.add(generateXML);

    setOpaque(false);
    setLayout(new BorderLayout());
    add(optionPanel, BorderLayout.NORTH);
    add(buttonsHolder, BorderLayout.SOUTH);
  } // END: SimulationPanel
예제 #3
0
  public void actionPerformed(ActionEvent actionevent) {
    OResource selectedNode = ((OResourceNode) selectedNodes.get(0).getUserObject()).getResource();
    String ns = selectedNode.getONodeID().getNameSpace();
    if (gate.creole.ontology.Utils.hasSystemNameSpace(selectedNode.getONodeID().toString())) {
      ns = ontology.getDefaultNameSpace();
    }
    nameSpace.setText(ns);

    nameSpace.setText(
        ontology.getDefaultNameSpace() == null
            ? "http://gate.ac.uk/example#"
            : ontology.getDefaultNameSpace());
    JOptionPane pane =
        new JOptionPane(
            mainPanel,
            JOptionPane.QUESTION_MESSAGE,
            JOptionPane.OK_CANCEL_OPTION,
            MainFrame.getIcon("ontology-instance")) {
          public void selectInitialValue() {
            instanceName.requestFocusInWindow();
            instanceName.selectAll();
          }
        };
    pane.createDialog(MainFrame.getInstance(), "New Instance").setVisible(true);
    Object selectedValue = pane.getValue();
    if (selectedValue != null
        && selectedValue instanceof Integer
        && (Integer) selectedValue == JOptionPane.OK_OPTION) {
      String s = nameSpace.getText();
      if (!Utils.isValidNameSpace(s)) {
        JOptionPane.showMessageDialog(
            MainFrame.getInstance(),
            "Invalid Name Space: " + s + "\nExample: http://gate.ac.uk/example#");
        return;
      }
      if (!Utils.isValidOntologyResourceName(instanceName.getText())) {
        JOptionPane.showMessageDialog(
            MainFrame.getInstance(), "Invalid Instance: " + instanceName.getText());
        return;
      }
      if (Utils.getOResourceFromMap(ontology, s + instanceName.getText()) != null) {
        JOptionPane.showMessageDialog(
            MainFrame.getInstance(),
            "<html>" + "Resource <b>" + s + instanceName.getText() + "</b> already exists.");
        return;
      }

      for (int i = 0; i < selectedNodes.size(); i++) {
        Object obj = ((OResourceNode) selectedNodes.get(i).getUserObject()).getResource();
        if (obj instanceof OClass) {
          ontology.addOInstance(
              ontology.createOURI(nameSpace.getText() + instanceName.getText()), (OClass) obj);
        }
      }
    }
  }
예제 #4
0
 private void savewndstate() {
   if (prefs == null) {
     if (getExtendedState() == NORMAL)
     /* Apparent, getSize attempts to return the "outer
      * size" of the window, including WM decorations, even
      * though setSize sets the "inner size" of the
      * window. Therefore, use the Panel's size instead; it
      * ought to correspond to the inner size at all
      * times. */ {
       Dimension dim = p.getSize();
       Utils.setprefc("wndsz", new Coord(dim.width, dim.height));
     }
     Utils.setprefb("wndmax", (getExtendedState() & MAXIMIZED_BOTH) != 0);
   }
 }
예제 #5
0
 private static void main2(String[] args) {
   Config.cmdline(args);
   try {
     javabughack();
   } catch (InterruptedException e) {
     return;
   }
   setupres();
   MainFrame f = new MainFrame(null);
   if (Utils.getprefb("fullscreen", false)) f.setfs();
   f.mt.start();
   try {
     f.mt.join();
   } catch (InterruptedException e) {
     f.g.interrupt();
     return;
   }
   dumplist(Resource.remote().loadwaited(), Config.loadwaited);
   dumplist(Resource.remote().cached(), Config.allused);
   if (ResCache.global != null) {
     try {
       Writer w = new OutputStreamWriter(ResCache.global.store("tmp/allused"), "UTF-8");
       try {
         Resource.dumplist(Resource.remote().used(), w);
       } finally {
         w.close();
       }
     } catch (IOException e) {
     }
   }
   System.exit(0);
 }
예제 #6
0
  /** execute method之后,取返回的inputstream */
  private static ByteArrayInputStream execute4InputStream(HttpClient client) throws Exception {
    int statusCode = client.getResponseCode();
    if (statusCode != HttpURLConnection.HTTP_OK) {
      throw new EnvException("Method failed: " + statusCode);
    }
    InputStream in = client.getResponseStream();
    if (in == null) {
      return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      Utils.copyBinaryTo(in, out);

      // 看一下传过来的byte[]是不是DesignProcessor.INVALID,如果是的话,就抛Exception
      byte[] bytes = out.toByteArray();
      // carl:格式一致传中文
      String message = new String(bytes, EncodeConstants.ENCODING_UTF_8);
      if (ComparatorUtils.equals(message, RemoteDeziConstants.NO_SUCH_RESOURCE)) {
        return null;
      } else if (ComparatorUtils.equals(message, RemoteDeziConstants.INVALID_USER)) {
        throw new EnvException(RemoteDeziConstants.INVALID_USER);
      } else if (ComparatorUtils.equals(message, RemoteDeziConstants.FILE_LOCKED)) {
        JOptionPane.showMessageDialog(null, Inter.getLocText("FR-Designer_file-is-locked"));
        return null;
      } else if (message.startsWith(RemoteDeziConstants.RUNTIME_ERROR_PREFIX)) {
      }
      return new ByteArrayInputStream(bytes);
    } finally {
      in.close();
      out.close();
      client.release();
    }
  }
예제 #7
0
 /**
  * Retrieve the current busy cursor for a blocked modal component.
  *
  * <p>The following 3 steps are used to determine the current busy cursor:
  *
  * <ol>
  *   <li>The busy cursor set with {@link #setBusyCursor(java.awt.Cursor) setBusyCursor} if it is
  *       not null.
  *   <li>The default busy icon filed under the key <b>"swingx.busy.cursor"</b> in the UIManager.
  *   <li>The default one which is a STOP sign.
  * </ol>
  *
  * @return Current busy cursor.
  */
 public static Cursor getBusyCursor() {
   if (getInstance().busyCursor == null) {
     return Utils.getBusyCursor();
   } else {
     return getInstance().busyCursor;
   }
 }
예제 #8
0
  public MainFrame(Coord isz) {
    super("Haven and Hearth");
    version = "1.6 (12.22.2015)";
    Coord sz;
    if (isz == null) {
      sz = Utils.getprefc("wndsz", new Coord(800, 600));
      if (sz.x < 640) sz.x = 640;
      if (sz.y < 480) sz.y = 480;
    } else {
      sz = isz;
    }
    this.g = new ThreadGroup(HackThread.tg(), "Haven client");
    this.mt = new HackThread(this.g, this, "Haven main thread");
    p = new HavenPanel(sz.x, sz.y);
    if (fsmode == null) {
      Coord pfm = Utils.getprefc("fsmode", null);
      if (pfm != null) fsmode = findmode(pfm.x, pfm.y);
    }
    if (fsmode == null) {
      DisplayMode cm = getGraphicsConfiguration().getDevice().getDisplayMode();
      fsmode = findmode(cm.getWidth(), cm.getHeight());
    }
    if (fsmode == null) fsmode = findmode(800, 600);
    add(p);
    pack();
    setResizable(!Utils.getprefb("wndlock", false));
    p.requestFocusInWindow();
    seticon();
    setVisible(true);
    p.init();
    addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            g.interrupt();
          }

          public void windowActivated(WindowEvent e) {
            p.bgmode = false;
          }

          public void windowDeactivated(WindowEvent e) {
            p.bgmode = true;
          }
        });
    if ((isz == null) && Utils.getprefb("wndmax", false))
      setExtendedState(getExtendedState() | MAXIMIZED_BOTH);
  }
예제 #9
0
  // -------------------------------- main -------------------------------
  public static void main(String[] args) {
    String fileName;
    if (args.length > 0) fileName = args[0];
    else fileName = Utils.getFileName("Choose a flow field metadata file");
    Properties metaData = new Properties();
    try {
      metaData.load(new FileInputStream(fileName));
    } catch (IOException fnf) {
      System.err.println("Can't find file: " + fileName);
      System.exit(-1);
    }
    // ----- get all the properties from the prpoerty file and
    //
    VectorField.xData = new File(metaData.getProperty("xfile"));
    VectorField.yData = new File(metaData.getProperty("yfile"));
    VectorField.width = Utils.toInt(metaData.getProperty("xsize"), 128);
    VectorField.height = Utils.toInt(metaData.getProperty("ysize"), 128);
    VectorField.displayScale = Utils.toInt(metaData.getProperty("displayScale"), 6);
    VectorField.vectorScale = Utils.toDouble(metaData.getProperty("vectorScale"), 10.75);

    VectorField.numParticles = Utils.toInt(metaData.getProperty("numParticles"), 200);
    VectorField.timerDelay = Utils.toInt(metaData.getProperty("delay"), 30);

    FlowQuad vectorField = new FlowQuad("Static Vector Field");
  }
예제 #10
0
  /**
   * 访问服务器环境
   *
   * @param names 参数名字
   * @param values 参数值
   */
  public static void visitEnvServerByParameters(String[] names, String[] values) {
    int len = Math.min(ArrayUtils.getLength(names), ArrayUtils.getLength(values));
    String[] segs = new String[len];
    for (int i = 0; i < len; i++) {
      try {
        // 设计器里面据说为了改什么界面统一, 把分隔符统一用File.separator, 意味着在windows里面报表路径变成了\
        // 以前的超链, 以及预览url什么的都是/, 产品组的意思就是用到的地方替换下, 真恶心.
        String value = values[i].replaceAll("\\\\", "/");
        segs[i] =
            URLEncoder.encode(CodeUtils.cjkEncode(names[i]), EncodeConstants.ENCODING_UTF_8)
                + "="
                + URLEncoder.encode(CodeUtils.cjkEncode(value), "UTF-8");
      } catch (UnsupportedEncodingException e) {
        FRContext.getLogger().error(e.getMessage(), e);
      }
    }
    String postfixOfUri = (segs.length > 0 ? "?" + StableUtils.join(segs, "&") : StringUtils.EMPTY);

    if (FRContext.getCurrentEnv() instanceof RemoteEnv) {
      try {
        if (Utils.isEmbeddedParameter(postfixOfUri)) {
          String time = Calendar.getInstance().getTime().toString().replaceAll(" ", "");
          boolean isUserPrivilege =
              ((RemoteEnv) FRContext.getCurrentEnv()).writePrivilegeMap(time, postfixOfUri);
          postfixOfUri =
              isUserPrivilege
                  ? postfixOfUri
                      + "&fr_check_url="
                      + time
                      + "&id="
                      + FRContext.getCurrentEnv().getUserID()
                  : postfixOfUri;
        }

        String urlPath = getWebBrowserPath();
        Desktop.getDesktop().browse(new URI(urlPath + postfixOfUri));
      } catch (Exception e) {
        FRContext.getLogger().error("cannot open the url Successful", e);
      }
    } else {
      try {
        String web = GeneralContext.getCurrentAppNameOfEnv();
        String url =
            "http://localhost:"
                + DesignerEnvManager.getEnvManager().getJettyServerPort()
                + "/"
                + web
                + "/"
                + ConfigManager.getProviderInstance().getServletMapping()
                + postfixOfUri;
        StartServer.browerURLWithLocalEnv(url);
      } catch (Throwable e) {
        //
      }
    }
  }
  protected void updateByOpTree(javax.swing.text.DocumentFilter.FilterBypass fb) {
    String oldStr = JMathTextField.this.getText();
    String newStr = operatorTree.toString();
    int commonStart = Utils.equalStartLen(oldStr, newStr);
    int commonEnd = Utils.equalEndLen(oldStr, newStr);
    if (commonEnd + commonStart >= Math.min(oldStr.length(), newStr.length()))
      commonEnd = Math.min(oldStr.length(), newStr.length()) - commonStart;

    try {
      fb.replace(
          commonStart,
          oldStr.length() - commonEnd - commonStart,
          newStr.substring(commonStart, newStr.length() - commonEnd),
          null);
    } catch (BadLocationException e) {
      // this should not happen. we should have checked this. this whole function should be safe
      throw new AssertionError(e);
    }
  }
  private static void applyTiePointGeoCoding(
      TiffFileInfo info, double[] tiePoints, Product product) {
    final SortedSet<Double> xSet = new TreeSet<>();
    final SortedSet<Double> ySet = new TreeSet<>();
    for (int i = 0; i < tiePoints.length; i += 6) {
      xSet.add(tiePoints[i]);
      ySet.add(tiePoints[i + 1]);
    }
    final double xMin = xSet.first();
    final double xMax = xSet.last();
    final double xDiff = (xMax - xMin) / (xSet.size() - 1);
    final double yMin = ySet.first();
    final double yMax = ySet.last();
    final double yDiff = (yMax - yMin) / (ySet.size() - 1);

    final int width = xSet.size();
    final int height = ySet.size();

    int idx = 0;
    final Map<Double, Integer> xIdx = new HashMap<>();
    for (Double val : xSet) {
      xIdx.put(val, idx);
      idx++;
    }
    idx = 0;
    final Map<Double, Integer> yIdx = new HashMap<>();
    for (Double val : ySet) {
      yIdx.put(val, idx);
      idx++;
    }

    final float[] lats = new float[width * height];
    final float[] lons = new float[width * height];

    for (int i = 0; i < tiePoints.length; i += 6) {
      final int idxX = xIdx.get(tiePoints[i + 0]);
      final int idxY = yIdx.get(tiePoints[i + 1]);
      final int arrayIdx = idxY * width + idxX;
      lons[arrayIdx] = (float) tiePoints[i + 3];
      lats[arrayIdx] = (float) tiePoints[i + 4];
    }

    String[] names = Utils.findSuitableLatLonNames(product);
    final TiePointGrid latGrid =
        new TiePointGrid(names[0], width, height, xMin, yMin, xDiff, yDiff, lats);
    final TiePointGrid lonGrid =
        new TiePointGrid(names[1], width, height, xMin, yMin, xDiff, yDiff, lons);

    product.addTiePointGrid(latGrid);
    product.addTiePointGrid(lonGrid);
    final SortedMap<Integer, GeoKeyEntry> geoKeyEntries = info.getGeoKeyEntries();
    final Datum datum = getDatum(geoKeyEntries);
    product.setGeoCoding(new TiePointGeoCoding(latGrid, lonGrid, datum));
  }
예제 #13
0
  private void updateFontPreview() {
    SikuliIDE ide = SikuliIDE.getInstance();
    Font font =
        new Font(
            (String) _cmbFontName.getSelectedItem(), Font.PLAIN, (Integer) _spnFontSize.getValue());

    SikuliCodePane codePane = SikuliIDE.getInstance().getCurrentCodePane();
    if (Utils.typeOfCodePane(codePane) == Utils.SikuliCodePaneType.SIKULI_PANE_TYPE_TEXT) {
      // preview only supported on text code panes
      SikuliTextPane textPane = (SikuliTextPane) (codePane.getComponent());
      textPane.setFont(font);
    }
  }
예제 #14
0
 public Line render(String text, Color c) {
   text = Translate.get(text);
   Coord sz = strsize(text);
   if (sz.x < 1) sz = sz.add(1, 0);
   BufferedImage img = TexI.mkbuf(sz);
   Graphics g = img.createGraphics();
   if (aa) Utils.AA(g);
   g.setFont(font);
   g.setColor(c);
   FontMetrics m = g.getFontMetrics();
   g.drawString(text, 0, m.getAscent());
   g.dispose();
   return (new Line(text, img, m));
 }
예제 #15
0
  /**
   * Centers the given component on the user's screen.
   *
   * @param component a component (usually a frame.)
   */
  public static void centerOnScreen(Component component) {
    Toolkit toolkit = java.awt.Toolkit.getDefaultToolkit();
    Dimension screenSize = toolkit.getScreenSize();
    int screenWidth = (int) screenSize.getWidth();
    int screenHeight = (int) screenSize.getHeight();

    int componentWidth = component.getWidth();
    int componentHeight = component.getHeight();

    int top = (screenHeight - componentHeight) / 2;
    int left = (screenWidth - componentWidth) / 2;

    Utils.changeFrameLocation(component, left, top);
  }
예제 #16
0
  /**
   * Utility method to put the given panel in a JDialog. You'll have to show it on your own.
   *
   * @param panel the panel to put in a dialog
   * @param owner the JFrame that owns the dialog. You can pass null.
   * @param dialogTitle the title for the dialog
   * @param iconPath the path to the dialog's icon, such as foo.png
   * @param width the dialog's width. Pass -1 to pack().
   * @param height the dialog's height. Pass -1 to pack().
   * @return the JDialog the panel is in
   */
  public static JDialog putPanelInDialog(
      JPanel panel, JFrame owner, String dialogTitle, String iconPath, int width, int height) {
    JDialog dialog = new JDialog(owner, dialogTitle, true); // boolean means modality

    dialog.add(panel);
    dialog.setIconImage(ImageManager.createImageIcon(iconPath).getImage());
    if (width < 0 && height < 0) dialog.pack();
    else dialog.setSize(width, height);
    dialog.setResizable(false);
    if (owner != null) Utils.centerComponent(dialog, owner);
    else dialog.setLocationRelativeTo(null);

    return dialog;
  }
예제 #17
0
파일: Text.java 프로젝트: TuGu/hnh_union
 public Line render(String text, Color c) {
   Line t = new Line(text);
   Coord sz = strsize(text);
   if (sz.x < 1) sz = sz.add(1, 0);
   t.img = TexI.mkbuf(sz);
   Graphics g = t.img.createGraphics();
   if (aa) Utils.AA(g);
   g.setFont(font);
   g.setColor(c);
   t.m = g.getFontMetrics();
   g.drawString(text, 0, t.m.getAscent());
   g.dispose();
   return (t);
 }
예제 #18
0
  /**
   * Retrieve the optional internal frame icon.
   *
   * <p>The following 2 steps are used to determine the optional internal frame icon:
   *
   * <ol>
   *   <li>The internal frame icon set with {@link #setOptionalIFrameIcon(javax.swing.Icon)
   *       setOptionalIFrameIcon} if it is not null.
   *   <li>The optional internal frame icon filed under the key <b>"swingx.iframe.icon"</b> in the
   *       UIManager.
   * </ol>
   *
   * @return Image An optional internal frame icon.
   */
  public static Icon getOptionalIFrameIcon() {
    Icon optionalIFrameIcon = getInstance().optionalIFrameIcon;

    if (optionalIFrameIcon != null) {
      return optionalIFrameIcon;
    }

    String uiOptionalIFrameIcon = UIManager.getString("swingx.iframe.icon");

    if (uiOptionalIFrameIcon != null) {
      return Utils.getIcon(uiOptionalIFrameIcon);
    }

    return null;
  }
예제 #19
0
  /**
   * Centers the given component in relation to its owner.
   *
   * @param component the component to center
   * @param owner the parent frame
   */
  public static void centerComponent(Component component, Component owner) {
    // find the difference in width to see the offsets
    int widthDifference = owner.getWidth() - component.getWidth();
    int heightDifference = owner.getHeight() - component.getHeight();

    // we can divide the differences by 2 and add that to the owner's top left
    // and then make that the top left of the component
    // to center the frame
    int leftOffset = widthDifference / 2;
    int topOffset = heightDifference / 2;

    // these are the new locations
    int left = owner.getX() + leftOffset;
    int top = owner.getY() + topOffset;

    Utils.changeFrameLocation(component, left, top);
  }
예제 #20
0
 public void showHistory(final boolean byClickingToolbarButton, JTextComponent textField) {
   FeatureUsageTracker.getInstance().triggerFeatureUsed("find.recent.search");
   FindSettings settings = FindSettings.getInstance();
   String[] recent =
       textField == mySearchTextComponent
           ? settings.getRecentFindStrings()
           : settings.getRecentReplaceStrings();
   final boolean toShowAd =
       textField == mySearchTextComponent
           && textField.getText().isEmpty()
           && FindManager.getInstance(myProject).getPreviousFindModel() != null;
   Utils.showCompletionPopup(
       byClickingToolbarButton ? mySearchActionsToolbar1 : null,
       new JBList((Object[]) ArrayUtil.reverseArray(recent)),
       "Recent " + (textField == mySearchTextComponent ? "Searches" : "Replaces"),
       textField,
       toShowAd ? RestorePreviousSettingsAction.getAd() : null);
 }
    // ===============================================================
    // ===============================================================
    public TangoRenderer() {
      Utils utils = Utils.getInstance();
      tango_icon = utils.getIcon("TangoClass.gif", 0.33);
      class_icon = utils.getIcon("class.gif");
      cmd_icon = utils.getIcon("attleaf.gif");
      dd_cursor = utils.getCursor("drg-drp.gif");

      fonts = new Font[3];
      fonts[TITLE] = new Font("Dialog", Font.BOLD, 18);
      //	width fixed font
      fonts[THREAD] = new Font("Dialog", Font.BOLD, 12);
      fonts[DEVICE] = new Font("Dialog", Font.PLAIN, 12);
    }
예제 #22
0
  public static void main(final String[] args) {

    File logdir = new File(LOG_DIR);
    if (!logdir.exists()) logdir.mkdirs();
    File log = new File(logdir, "client.log");
    // redirect all console output to the file
    try {
      PrintStream out = new PrintStream(new FileOutputStream(log, true), true);
      out.format("[%s] ===== Client started =====%n", timestampf.format(new Date()));
      System.setOut(out);
      System.setErr(out);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    /* Set up the error handler as early as humanly possible. */
    ThreadGroup g = new ThreadGroup("Haven main group");
    String ed;
    if (!(ed = Utils.getprop("haven.errorurl", "")).equals("")) {
      try {
        final haven.error.ErrorHandler hg = new haven.error.ErrorHandler(new java.net.URL(ed));
        hg.sethandler(
            new haven.error.ErrorGui(null) {
              public void errorsent() {
                hg.interrupt();
              }
            });
        g = hg;
      } catch (java.net.MalformedURLException e) {
      }
    }
    Thread main =
        new HackThread(
            g,
            new Runnable() {
              public void run() {
                main2(args);
              }
            },
            "Haven main thread");
    main.start();
  }
예제 #23
0
  /**
   * Uses a JEditorPane to open the given URL in a dialog
   *
   * @param url the url to load
   * @param title the title of the dialog
   * @param frame the parent frame
   * @param visible true if you want the dialog to be visible, false if you want it to be invisible
   *     to user
   * @param iconPath the path to the image icon for the dialog.
   */
  public static void openURLinDialog(
      String url, String title, String iconPath, JFrame frame, boolean visible) {
    // create panel with page in it
    final int WIDTH = 400;
    final int HEIGHT = 300;
    JPanel webView = createEditorPane(url, WIDTH, HEIGHT);

    // put it in a dialog
    JDialog dialog = new JDialog(frame);
    dialog.setTitle(title);
    dialog.setIconImage(GUI.createImageIcon(iconPath).getImage());
    dialog.setContentPane(webView);
    dialog.pack();
    dialog.setResizable(false);
    dialog.setModal(true);
    Utils.centerComponent(dialog, frame);

    // open it
    dialog.setVisible(visible);
  }
예제 #24
0
  public XTextField(
      Object value,
      Class<?> expectedClass,
      int colWidth,
      boolean isCallable,
      JButton button,
      XOperations operation) {
    super(new BorderLayout());
    this.button = button;
    this.operation = operation;
    add(textField = new JTextField(value.toString(), colWidth), BorderLayout.CENTER);
    if (isCallable) textField.addActionListener(this);

    boolean fieldEditable = Utils.isEditableType(expectedClass.getName());
    if (fieldEditable && isCallable) {
      textField.setEditable(true);
    } else {
      textField.setEditable(false);
    }
  }
예제 #25
0
  protected void init(Object value, Class<?> expectedClass) {
    boolean fieldEditable = Utils.isEditableType(expectedClass.getName());
    clearObject();
    if (value != null) {
      textField.setText(value.toString());
    } else {
      // null String value for the moment
      textField.setText("");
    }
    textField.setToolTipText(null);
    if (fieldEditable) {
      if (!textField.isEditable()) {
        textField.setEditable(true);
      }

    } else {
      if (textField.isEditable()) {
        textField.setEditable(false);
      }
    }
  }
  // ===============================================================
  // ===============================================================
  void removeThread() {
    DefaultMutableTreeNode node = getSelectedNode();

    if (node != null) {
      Object obj = node.getUserObject();
      if (obj instanceof PollThread) {
        //	Check if device(s) associated.
        if (node.getChildCount() == 0) {
          //	get future selected node
          DefaultMutableTreeNode next_node = getFutureSelectedNode(node);
          //	Remove selected one
          treeModel.removeNodeFromParent(node);
          PollThread pt = (PollThread) obj;
          threadsInfo.remove(pt);
          //	And select the found node
          TreeNode[] tree_node = next_node.getPath();
          TreePath path = new TreePath(tree_node);
          setSelectionPath(path);
          scrollPathToVisible(path);
        } else Utils.popupError(parent, "Cannot remove a not empty thread !");
      }
    }
  }
예제 #27
0
  private void initReplaceToolBars() {
    DefaultActionGroup actionGroup1 = new DefaultActionGroup("replace bar 1", false);
    myReplaceActionsToolbar1 =
        (ActionToolbarImpl)
            ActionManager.getInstance()
                .createActionToolbar(ActionPlaces.EDITOR_TOOLBAR, actionGroup1, true);
    myReplaceActionsToolbar1.setForceMinimumSize(true);
    final JButton myReplaceButton = new JButton("Replace");
    myReplaceButton.setFocusable(false);
    myReplaceButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent actionEvent) {
            replaceCurrent();
          }
        });

    final JButton myReplaceAllButton = new JButton("Replace all");
    myReplaceAllButton.setFocusable(false);
    myReplaceAllButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent actionEvent) {
            myLivePreviewController.performReplaceAll();
          }
        });

    final JButton myExcludeButton = new JButton("");
    myExcludeButton.setFocusable(false);
    myExcludeButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent actionEvent) {
            myLivePreviewController.exclude();
            moveCursor(SearchResults.Direction.DOWN);
          }
        });

    if (!UISettings.getInstance().DISABLE_MNEMONICS_IN_CONTROLS) {
      myReplaceButton.setMnemonic('p');
      myReplaceAllButton.setMnemonic('a');
      myExcludeButton.setMnemonic('l');
    }

    actionGroup1.addAction(
        new DefaultCustomComponentAction(myReplaceButton) {
          @Override
          public void update(AnActionEvent e) {
            myReplaceButton.setEnabled(canReplaceCurrent());
          }
        });
    actionGroup1.addAction(
        new DefaultCustomComponentAction(myReplaceAllButton) {
          @Override
          public void update(AnActionEvent e) {
            myReplaceAllButton.setEnabled(mySearchResults != null && mySearchResults.hasMatches());
          }
        });
    actionGroup1.addAction(
        new DefaultCustomComponentAction(myExcludeButton) {
          @Override
          public void update(AnActionEvent e) {
            FindResult cursor = mySearchResults != null ? mySearchResults.getCursor() : null;
            myExcludeButton.setEnabled(cursor != null);
            myExcludeButton.setText(
                cursor != null && mySearchResults.isExcluded(cursor) ? "Include" : "Exclude");
          }
        });

    myReplaceActionsToolbar1.setLayoutPolicy(ActionToolbar.AUTO_LAYOUT_POLICY);
    myReplaceActionsToolbar1.setBorder(null);
    myReplaceActionsToolbar1.setOpaque(false);
    DefaultActionGroup actionGroup2 = new DefaultActionGroup("replace bar 2", false);
    myReplaceActionsToolbar2 =
        (ActionToolbarImpl)
            ActionManager.getInstance()
                .createActionToolbar(ActionPlaces.EDITOR_TOOLBAR, actionGroup2, true);
    actionGroup2.addAction(new TogglePreserveCaseAction(this));
    actionGroup2.addAction(new ToggleSelectionOnlyAction(this));
    myReplaceActionsToolbar2.setLayoutPolicy(ActionToolbar.AUTO_LAYOUT_POLICY);
    myReplaceActionsToolbar2.setBorder(null);
    myReplaceActionsToolbar2.setOpaque(false);
    Utils.setSmallerFontForChildren(myReplaceActionsToolbar1);
    Utils.setSmallerFontForChildren(myReplaceActionsToolbar2);
  }
예제 #28
0
파일: Text.java 프로젝트: TuGu/hnh_union
 public Coord sz() {
   return (Utils.imgsz(img));
 }
예제 #29
0
  private boolean updateTextComponent(final boolean search) {
    JTextComponent oldComponent = search ? mySearchTextComponent : myReplaceTextComponent;
    Color oldBackground = oldComponent != null ? oldComponent.getBackground() : null;
    Wrapper wrapper = search ? mySearchFieldWrapper : myReplaceFieldWrapper;
    boolean multiline = myFindModel.isMultiline();
    if (multiline && oldComponent instanceof JTextArea) return false;
    if (!multiline && oldComponent instanceof JTextField) return false;

    final JTextComponent textComponent;
    if (multiline) {
      textComponent = new JTextArea();
      ((JTextArea) textComponent).setColumns(25);
      ((JTextArea) textComponent).setRows(2);
      wrapper.setContent(
          new SearchWrapper(textComponent, new ShowHistoryAction(textComponent, this)));
    } else {
      SearchTextField searchTextField = new SearchTextField(true);
      searchTextField.setOpaque(false);
      textComponent = searchTextField.getTextEditor();
      searchTextField.getTextEditor().setColumns(25);
      if (UIUtil.isUnderGTKLookAndFeel()) {
        textComponent.setOpaque(false);
      }
      setupHistoryToSearchField(
          searchTextField,
          search
              ? FindSettings.getInstance().getRecentFindStrings()
              : FindSettings.getInstance().getRecentReplaceStrings());
      textComponent.registerKeyboardAction(
          new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
              final String text = textComponent.getText();
              myFindModel.setMultiline(true);
              ApplicationManager.getApplication()
                  .invokeLater(
                      new Runnable() {
                        @Override
                        public void run() {
                          if (search) {
                            mySearchTextComponent.setText(text + "\n");
                          } else {
                            myReplaceTextComponent.setText(text + "\n");
                          }
                        }
                      });
            }
          },
          KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.ALT_DOWN_MASK),
          JComponent.WHEN_FOCUSED);
      wrapper.setContent(searchTextField);
    }

    if (search) {
      mySearchTextComponent = textComponent;
    } else {
      myReplaceTextComponent = textComponent;
    }

    UIUtil.addUndoRedoActions(textComponent);
    Utils.setSmallerFont(textComponent);

    textComponent.putClientProperty("AuxEditorComponent", Boolean.TRUE);
    if (oldBackground != null) {
      textComponent.setBackground(oldBackground);
    }
    textComponent.addFocusListener(
        new FocusListener() {
          @Override
          public void focusGained(final FocusEvent e) {
            textComponent.repaint();
          }

          @Override
          public void focusLost(final FocusEvent e) {
            textComponent.repaint();
          }
        });
    new CloseOnESCAction(this, textComponent);
    return true;
  }
예제 #30
0
  public SQLiteDataBrowser() {
    SQLiteDbManager dbManager = new SQLiteDbManager();

    setLayout(new BorderLayout());

    showTablesList = new JList();
    showTablesList.setLayoutOrientation(JList.VERTICAL_WRAP);
    showTablesList.setSelectedIndex(ListSelectionModel.SINGLE_SELECTION);
    showTablesList.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    showTablesList.setFont(new Font("Times New Roman", Font.PLAIN, 13));
    showTablesList.setDragEnabled(false);
    showTablesList.setFixedCellWidth(150);
    showTablesList.setVisibleRowCount(-1);
    showTablesList.setEnabled(false);

    showTablesListScroller = new JScrollPane(showTablesList);
    showTablesListScroller.setBorder(
        BorderFactory.createTitledBorder(new LineBorder(Color.BLACK), "List of Tables"));
    showTablesListScroller.setPreferredSize(new Dimension(160, this.getHeight()));

    add(showTablesListScroller, BorderLayout.EAST);

    loadDbPanel = new JPanel(new FlowLayout());
    loadDbPanel.setBackground(new Color(0xe8e8e8));
    loadDbPanel.setPreferredSize(new Dimension(getWidth(), 40));

    loadDbLabel = new JLabel("Load SQLite Database: ");
    loadDbLabel.setToolTipText("Possible extensions being .sqlite|.sqlite3|.db|.db3");

    loadedDbPath = new JTextField("Click browse to choose the database file.", 60);
    loadedDbPath.setForeground(Color.GRAY);
    loadedDbPath.setFont(new Font("Times New Roman", Font.ITALIC, 13));
    loadedDbPath.setEditable(false);

    lastFolderLocation = new File(Utils.getUserHome());
    fc = new JFileChooser(lastFolderLocation);

    browseDb = new JButton("Browse");
    browseDb.addActionListener(
        actionEvent -> {
          int retVal = fc.showOpenDialog(SQLiteDataBrowser.this);
          if (retVal == JFileChooser.APPROVE_OPTION) {
            File dbPath = fc.getSelectedFile();
            if (Utils.checkIfSQLiteDb(dbPath)) {
              loadedDbPath.setText(dbPath.toString());
              lastFolderLocation = fc.getCurrentDirectory();
              new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                  try {
                    dbManager.setDbPath(dbPath.toString());
                    dbManager.initialize();
                    showTablesList.setListData(dbManager.getTables().toArray());
                    showTablesList.setEnabled(true);
                  } catch (SQLException e) {
                    e.printStackTrace();
                  }
                  return null;
                }
              }.execute();
            } else {
              JOptionPane.showMessageDialog(
                  SQLiteDataBrowser.this,
                  "The Selected file is not in SQLite Format",
                  "File Format Error",
                  JOptionPane.ERROR_MESSAGE);
              loadedDbPath.setText("Click browse to choose the database file.");
            }
          }
        });

    loadDbPanel.add(loadDbLabel);
    loadDbPanel.add(loadedDbPath);
    loadDbPanel.add(browseDb);

    loadDbRecords = new JLabel("Records Fetched (Rows x Cols): ");
    loadDbRecords.setFont(new Font("Times New Roman", Font.ITALIC, 12));
    loadDbPanel.add(loadDbRecords);

    loadDbRecordsCount = new JLabel();
    loadDbRecordsCount.setFont(new Font("Times New Roman", Font.ITALIC, 12));
    loadDbPanel.add(loadDbRecordsCount);

    final class DataBrowserTableModal extends DefaultTableModel {

      public DataBrowserTableModal() {}

      public DataBrowserTableModal(Object[][] tableData, Object[] colNames) {
        super(tableData, colNames);
      }

      @Override
      public void setDataVector(Object[][] tableData, Object[] colNames) {
        super.setDataVector(tableData, colNames);
      }

      @Override
      public boolean isCellEditable(int row, int column) {
        return false;
      }
    }

    DataBrowserTableModal tableModal = new DataBrowserTableModal();
    defaultTableModel = tableModal;

    table = new JTable();
    table.setModel(defaultTableModel);

    showTablesList.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent evt) {
            JList list = (JList) evt.getSource();
            if (evt.getClickCount() == 2) {
              String tableName = list.getSelectedValue().toString();

              new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                  try {
                    ResultSet rs = dbManager.executeQuery("SELECT * from " + tableName);
                    Vector<String> columnNames = dbManager.getColumnNames(rs);
                    Vector<Vector<Object>> tableData = new Vector<>();
                    while (rs.next()) {
                      Vector<Object> vector = new Vector<>();

                      for (int i = 1; i <= columnNames.size(); i++) {
                        vector.add(rs.getObject(i));
                      }
                      tableData.add(vector);
                    }
                    defaultTableModel.setDataVector(tableData, columnNames);
                  } catch (SQLException e) {
                    e.printStackTrace();
                  }

                  loadDbRecordsCount.setText(
                      defaultTableModel.getRowCount() + " x " + defaultTableModel.getColumnCount());

                  if (defaultTableModel.getColumnCount() < 5) {
                    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                  } else {
                    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                  }

                  return null;
                }
              }.execute();
            }
          }
        });

    tableScrollPane = new JScrollPane(table);
    tableScrollPane.setHorizontalScrollBarPolicy(
        ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    tableScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    tableScrollPane.setPreferredSize(new Dimension(getWidth(), getHeight()));
    add(tableScrollPane, BorderLayout.CENTER);

    add(loadDbPanel, BorderLayout.NORTH);
  }