Пример #1
0
  private void confirmNewKey(final Contact contact, final PGPUtils.PGPCoderKey key) {
    WebPanel panel = new GroupPanel(GAP_DEFAULT, false);
    panel.setOpaque(false);

    panel.add(new WebLabel(Tr.tr("Received new key for contact")).setBoldFont());
    panel.add(new WebSeparator(true, true));

    panel.add(new WebLabel(Tr.tr("Contact:")));
    String contactText = Utils.name(contact) + " " + Utils.jid(contact.getJID(), 30, true);
    panel.add(new WebLabel(contactText).setBoldFont());

    panel.add(new WebLabel(Tr.tr("Key fingerprint:")));
    WebTextArea fpArea = Utils.createFingerprintArea();
    fpArea.setText(Utils.fingerprint(key.fingerprint));
    panel.add(fpArea);

    String expl =
        Tr.tr(
            "When declining the key further communication to and from this contact will be blocked.");
    WebTextArea explArea = new WebTextArea(expl, 3, 30);
    explArea.setEditable(false);
    explArea.setLineWrap(true);
    explArea.setWrapStyleWord(true);
    panel.add(explArea);

    WebNotificationPopup popup =
        NotificationManager.showNotification(
            panel,
            NotificationOption.accept,
            NotificationOption.decline,
            NotificationOption.cancel);
    popup.setClickToClose(false);
    popup.addNotificationListener(
        new NotificationListener() {
          @Override
          public void optionSelected(NotificationOption option) {
            switch (option) {
              case accept:
                mControl.acceptKey(contact, key);
                break;
              case decline:
                mControl.declineKey(contact);
            }
          }

          @Override
          public void accepted() {}

          @Override
          public void closed() {}
        });
  }
Пример #2
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);
   }
 }
Пример #3
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);
 }
Пример #4
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);
  }
Пример #5
0
 private void showException(KonException ex) {
   if (ex.getError() == KonException.Error.LOAD_KEY_DECRYPT) {
     this.showPasswordDialog(true);
     return;
   }
   String errorText = Utils.getErrorText(ex);
   Icon icon = NotificationIcon.error.getIcon();
   NotificationManager.showNotification(mContent, errorText, icon);
 }
  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);
    }
  }
 /** if this line can not be current => stepOver & return true. return false on the other hand. */
 boolean resolveCanBeCurrent(ThreadReference tr) {
   try {
     Location l = tr.frame(0).location();
     if (l == null) return false;
     return resolveCanBeCurrent(
         tr, Utils.getLineForSource(l.declaringType().name(), l.sourceName(), l.lineNumber()));
   } catch (Exception e) {
   }
   return false;
 }
  /** Executes breakpoint hit event. */
  public void exec(com.sun.jdi.event.Event ev) {
    // S ystem.out.println ("exec "); // NOI18N
    removeStepRequest();
    StepEvent event = (StepEvent) ev;
    ThreadReference tr = event.thread();
    Location loc = event.location();
    int ln = -1;
    String methodName = "?"; // NOI18N
    String className = "?"; // NOI18N
    String lineNumber = "?"; // NOI18N
    String threadName = tr.name();
    Line l = null;

    if (loc != null) {
      if (loc.method() != null) methodName = loc.method().name();
      className = loc.declaringType().name();
      ln = loc.lineNumber();
      if (ln >= 0) lineNumber = "" + loc.lineNumber();
    }

    if (ln != -1)
      try {
        l = Utils.getLineForSource(className, loc.sourceName(), ln);
      } catch (AbsentInformationException e) {
        l = Utils.getLine(className, ln);
      }

    if (resolveCanBeCurrent(tr, l))
      // if this line can not be current resolveCanBeCurrent () calls stepOver
      return;
    // line can be current

    if ((l == null) && (getLastAction() == ACTION_TRACE_INTO))
      // try to find another "intelligent" line of code
      traceToSourceCode(tr);
    // you know - intelligent means that one with source code
    else {
      makeCurrent(threadName, className, methodName, lineNumber, l != null, tr);
      operator.stopRequest();
    }
  }
Пример #9
0
 /** Try to create a Java object using a one-string-param constructor. */
 public static Object newStringConstructor(String type, String param) throws Exception {
   Constructor c = Utils.getClass(type).getConstructor(String.class);
   try {
     return c.newInstance(param);
   } catch (InvocationTargetException e) {
     Throwable t = e.getTargetException();
     if (t instanceof Exception) {
       throw (Exception) t;
     } else {
       throw e;
     }
   }
 }
Пример #10
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);
    }
  }
Пример #11
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);
 }
Пример #12
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();
  }
Пример #13
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);
    }
  }
Пример #14
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);
      }
    }
  }
Пример #15
0
 /**
  * This method attempts to create an object of the given "type" using the "value" parameter. e.g.
  * calling createObjectFromString("java.lang.Integer", "10") will return an Integer object
  * initialized to 10.
  */
 public static Object createObjectFromString(String type, String value) throws Exception {
   Object result;
   if (primitiveToWrapper.containsKey(type)) {
     if (type.equals(Character.TYPE.getName())) {
       result = new Character(value.charAt(0));
     } else {
       result = newStringConstructor(((Class<?>) primitiveToWrapper.get(type)).getName(), value);
     }
   } else if (type.equals(Character.class.getName())) {
     result = new Character(value.charAt(0));
   } else if (Number.class.isAssignableFrom(Utils.getClass(type))) {
     result = createNumberFromStringValue(value);
   } else if (value == null || value.toString().equals("null")) {
     // hack for null value
     result = null;
   } else {
     // try to create a Java object using
     // the one-string-param constructor
     result = newStringConstructor(type, value);
   }
   return result;
 }
  public void sendSubscribe(String localURL, String buddyURI, boolean EXPIRED) {
    try {
      logger.debug("Sending SUBSCRIBE in progress to the buddy: " + buddyURI);
      int proxyPort = imUA.getProxyPort();
      String proxyAddress = imUA.getProxyAddress();
      String imProtocol = imUA.getIMProtocol();
      SipStack sipStack = imUA.getSipStack();
      SipProvider sipProvider = imUA.getSipProvider();
      MessageFactory messageFactory = imUA.getMessageFactory();
      HeaderFactory headerFactory = imUA.getHeaderFactory();
      AddressFactory addressFactory = imUA.getAddressFactory();

      // Request-URI:
      // URI requestURI=addressFactory.createURI(buddyURI);
      SipURI requestURI = addressFactory.createSipURI(null, proxyAddress);
      requestURI.setPort(proxyPort);
      requestURI.setTransportParam(imProtocol);

      // Call-Id:
      CallIdHeader callIdHeader = null;

      // CSeq:
      CSeqHeader cseqHeader = null;

      // To header:
      ToHeader toHeader = null;

      // From Header:
      FromHeader fromHeader = null;

      // Via header
      String branchId = Utils.generateBranchId();
      ViaHeader viaHeader =
          headerFactory.createViaHeader(
              imUA.getIMAddress(), imUA.getIMPort(), imProtocol, branchId);
      Vector viaList = new Vector();
      viaList.addElement(viaHeader);

      PresenceManager presenceManager = imUA.getPresenceManager();
      Presentity presentity = presenceManager.getPresentity(buddyURI);
      Dialog dialog = null;
      if (presentity != null) dialog = presentity.getDialog();

      if (dialog != null) {

        // We have to remove the subscriber and the Presentity related
        // with this Buddy...
        presenceManager.removePresentity(buddyURI);
        Subscriber subscriber = presenceManager.getSubscriber(buddyURI);
        if (subscriber == null) {
          // It means that the guy does not have us in his buddy list
          // nothing to do!!!
        } else {
          presenceManager.removeSubscriber(buddyURI);
        }

        Address localAddress = dialog.getLocalParty();
        Address remoteAddress = dialog.getRemoteParty();

        fromHeader = headerFactory.createFromHeader(localAddress, dialog.getLocalTag());
        toHeader = headerFactory.createToHeader(remoteAddress, dialog.getRemoteTag());

        long cseq = dialog.getLocalSeqNumber();
        cseqHeader = headerFactory.createCSeqHeader(cseq, "MESSAGE");

        callIdHeader = dialog.getCallId();
      } else {
        String localTag = Utils.generateTag();

        Address toAddress = addressFactory.createAddress(buddyURI);
        Address fromAddress = addressFactory.createAddress(localURL);

        fromHeader = headerFactory.createFromHeader(fromAddress, localTag);
        toHeader = headerFactory.createToHeader(toAddress, null);

        // CSeq:
        cseqHeader = headerFactory.createCSeqHeader(1L, "SUBSCRIBE");

        callIdCounter++;
        // Call-ID:
        callIdHeader =
            (CallIdHeader)
                headerFactory.createCallIdHeader("nist-sip-im-subscribe-callId" + callIdCounter);
      }

      // MaxForwards header:
      MaxForwardsHeader maxForwardsHeader = headerFactory.createMaxForwardsHeader(70);

      Request request =
          messageFactory.createRequest(
              requestURI,
              "SUBSCRIBE",
              callIdHeader,
              cseqHeader,
              fromHeader,
              toHeader,
              viaList,
              maxForwardsHeader);

      RouteHeader rh = this.imUA.getRouteToProxy();
      request.setHeader(rh);

      // Contact header:
      SipURI sipURI = addressFactory.createSipURI(null, imUA.getIMAddress());
      sipURI.setPort(imUA.getIMPort());
      sipURI.setTransportParam(imUA.getIMProtocol());
      Address contactAddress = addressFactory.createAddress(sipURI);
      ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
      request.setHeader(contactHeader);

      ExpiresHeader expiresHeader = null;
      if (EXPIRED) {
        expiresHeader = headerFactory.createExpiresHeader(0);
      } else {
        expiresHeader = headerFactory.createExpiresHeader(presenceManager.getExpiresTime());
      }
      request.setHeader(expiresHeader);

      // WE have to add a new Header: "Event"
      Header eventHeader = headerFactory.createHeader("Event", "presence");
      request.setHeader(eventHeader);

      // Add Acceptw Header
      Header acceptHeader = headerFactory.createHeader("Accept", "application/pidf+xml");
      request.setHeader(acceptHeader);

      // ProxyAuthorization header if not null:
      ProxyAuthorizationHeader proxyAuthHeader = imUA.getProxyAuthorizationHeader();
      if (proxyAuthHeader != null) request.setHeader(proxyAuthHeader);

      ClientTransaction clientTransaction = sipProvider.getNewClientTransaction(request);

      if (dialog != null) {
        dialog.sendRequest(clientTransaction);
      } else {
        clientTransaction.sendRequest();
      }

      logger.debug("IMSubscribeProcessing, sendSubscribe(), SUBSCRIBE sent:\n" + request);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Пример #17
0
 private void setTxtHotkey(int code, int mod) {
   _cap_hkey = code;
   _cap_mod = mod;
   _txtHotkey.setText(Utils.convertKeyToText(code, mod));
 }
Пример #18
0
  private VirtualMachine launch(DebuggerInfo info) throws DebuggerException {
    // create process & read password for local debugging

    // create main class & arguments ...............................................
    StringBuffer sb = new StringBuffer();
    sb.append(mainClassName);
    String[] infoArgs = info.getArguments();
    int i, k = infoArgs.length;
    for (i = 0; i < k; i++) sb.append(" \"").append(infoArgs[i]).append('"'); // NOI18N
    String main = new String(sb);

    // create connector ..............................................................
    VirtualMachineManager vmm = Bootstrap.virtualMachineManager();
    java.util.List lcs = vmm.launchingConnectors();
    k = lcs.size();
    for (i = 0; i < k; i++)
      if (((LaunchingConnector) lcs.get(i)).name().indexOf("RawCommandLineLaunch") >= 0) // NOI18N
      break;
    if (i == k) {
      finishDebugger();
      throw new DebuggerException(
          new MessageFormat(bundle.getString("EXC_Cannot_find_launcher"))
              .format(
                  new Object[] {
                    "RawCommandLineLaunch" // NOI18N
                  }));
    }
    LaunchingConnector lc = (LaunchingConnector) lcs.get(i);
    String transport = lc.transport().name();

    // create commandLine & NbProcessDescriptor ..............................
    NbProcessDescriptor debugerProcess;
    if (info instanceof ProcessDebuggerInfo)
      debugerProcess = ((ProcessDebuggerInfo) info).getDebuggerProcess();
    else debugerProcess = ProcessDebuggerType.DEFAULT_DEBUGGER_PROCESS;

    // generate password
    String password;
    if (transport.equals("dt_shmem")) { // NOI18N
      connector = getAttachingConnectorFor("dt_shmem");
      password = generatePassword();
      args = connector.defaultArguments();
      ((Argument) args.get("name")).setValue(password);
    } else {
      try {
        java.net.ServerSocket ss = new java.net.ServerSocket(0);
        password = "" + ss.getLocalPort(); // NOI18N
        ss.close();
      } catch (java.io.IOException e) {
        finishDebugger();
        throw new DebuggerException(
            new MessageFormat(bundle.getString("EXC_Cannot_find_empty_local_port"))
                .format(new Object[] {e.toString()}));
      }
      connector = getAttachingConnectorFor("dt_socket");
      args = connector.defaultArguments();
      ((Argument) args.get("port")).setValue(password);
    }
    HashMap map =
        Utils.processDebuggerInfo(
            info,
            "-Xdebug -Xnoagent -Xrunjdwp:transport="
                + // NOI18N
                transport
                + ",address="
                + // NOI18N
                password
                + ",suspend=y ", // NOI18N
            main);
    MapFormat format = new MapFormat(map);
    String commandLine =
        format.format(
            debugerProcess.getProcessName()
                + " "
                + // NOI18N
                debugerProcess.getArguments());
    println(commandLine, ERR_OUT);
    /*
    We mus wait on process start to connect...
    try {
      process = debugerProcess.exec (format);
    } catch (java.io.IOException exc) {
      finishDebugger ();
      throw new DebuggerException (
        new MessageFormat (bundle.getString ("EXC_While_create_debuggee")).
          format (new Object[] {
            debugerProcess.getProcessName (),
            exc.toString ()
          }),
        exc
      );
    }
    return connect (
      null,
      connector,
      args
    );*/

    /*      S ystem.out.println ("attaching: ");
    Utils.showConnectors (vmm.attachingConnectors ());

    S ystem.out.println ("launching: ");
    Utils.showConnectors (vmm.launchingConnectors ());

    S ystem.out.println ("listening: ");
    Utils.showConnectors (vmm.listeningConnectors ());*/

    // set debugger-start arguments
    Map params = lc.defaultArguments();
    ((Argument) params.get("command"))
        .setValue( // NOI18N
            commandLine);
    ((Argument) params.get("address"))
        .setValue( // NOI18N
            password);

    // launch VM
    try {
      return lc.launch(params);
    } catch (VMStartException exc) {
      showOutput(process = exc.process(), ERR_OUT, ERR_OUT);
      finishDebugger();
      throw new DebuggerException(
          new MessageFormat(bundle.getString("EXC_While_create_debuggee"))
              .format(
                  new Object[] {format.format(debugerProcess.getProcessName()), exc.toString()}),
          exc);
    } catch (Exception exc) {
      finishDebugger();
      throw new DebuggerException(
          new MessageFormat(bundle.getString("EXC_While_create_debuggee"))
              .format(
                  new Object[] {format.format(debugerProcess.getProcessName()), exc.toString()}),
          exc);
    }
  }
Пример #19
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;
  }
Пример #20
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);
  }
Пример #21
0
  private void initSearchToolbars() {
    DefaultActionGroup actionGroup1 = new DefaultActionGroup("search bar 1", false);
    mySearchActionsToolbar1 =
        (ActionToolbarImpl)
            ActionManager.getInstance()
                .createActionToolbar(ActionPlaces.EDITOR_TOOLBAR, actionGroup1, true);
    mySearchActionsToolbar1.setForceMinimumSize(true);
    mySearchActionsToolbar1.setReservePlaceAutoPopupIcon(false);
    mySearchActionsToolbar1.setSecondaryButtonPopupStateModifier(
        new ActionToolbarImpl.PopupStateModifier() {
          @Override
          public int getModifiedPopupState() {
            return ActionButtonComponent.PUSHED;
          }

          @Override
          public boolean willModify() {
            return myFindModel.getSearchContext() != FindModel.SearchContext.ANY;
          }
        });
    mySearchActionsToolbar1.setSecondaryActionsTooltip(
        "More Options(" + ShowMoreOptions.SHORT_CUT + ")");

    actionGroup1.add(new PrevOccurrenceAction(this, mySearchFieldWrapper));
    actionGroup1.add(new NextOccurrenceAction(this, mySearchFieldWrapper));
    actionGroup1.add(new FindAllAction(this));
    actionGroup1.addSeparator();
    actionGroup1.add(new AddOccurrenceAction(this));
    actionGroup1.add(new RemoveOccurrenceAction(this));
    actionGroup1.add(new SelectAllAction(this));
    // actionGroup1.addSeparator();
    // actionGroup1.add(new ToggleMultiline(this));//todo get rid of it!
    actionGroup1.addSeparator();

    actionGroup1.addAction(new ToggleInCommentsAction(this)).setAsSecondary(true);
    actionGroup1.addAction(new ToggleInLiteralsOnlyAction(this)).setAsSecondary(true);
    actionGroup1.addAction(new ToggleExceptCommentsAction(this)).setAsSecondary(true);
    actionGroup1.addAction(new ToggleExceptLiteralsAction(this)).setAsSecondary(true);
    actionGroup1.addAction(new ToggleExceptCommentsAndLiteralsAction(this)).setAsSecondary(true);

    DefaultActionGroup actionGroup2 = new DefaultActionGroup("search bar 2", false);
    mySearchActionsToolbar2 =
        (ActionToolbarImpl)
            ActionManager.getInstance()
                .createActionToolbar(ActionPlaces.EDITOR_TOOLBAR, actionGroup2, true);
    actionGroup2.add(new ToggleMatchCase(this));
    actionGroup2.add(new ToggleRegex(this));
    actionGroup2.add(new ToggleWholeWordsOnlyAction(this));

    myMatchInfoLabel =
        new JLabel() {
          @Override
          public Font getFont() {
            Font font = super.getFont();
            return font != null ? font.deriveFont(Font.BOLD) : null;
          }
        };
    myMatchInfoLabel.setBorder(JBUI.Borders.empty(2, 20, 0, 20));

    myClickToHighlightLabel =
        new LinkLabel<Object>(
            "Click to highlight",
            null,
            new LinkListener<Object>() {
              @Override
              public void linkSelected(LinkLabel aSource, Object aLinkData) {
                setMatchesLimit(Integer.MAX_VALUE);
                updateResults(true);
              }
            });
    myClickToHighlightLabel.setVisible(false);

    mySearchActionsToolbar2 =
        (ActionToolbarImpl)
            ActionManager.getInstance()
                .createActionToolbar(ActionPlaces.EDITOR_TOOLBAR, actionGroup2, true);
    actionGroup2.add(new DefaultCustomComponentAction(myMatchInfoLabel));
    actionGroup2.add(new DefaultCustomComponentAction(myClickToHighlightLabel));

    mySearchActionsToolbar1.setLayoutPolicy(ActionToolbar.AUTO_LAYOUT_POLICY);
    mySearchActionsToolbar2.setLayoutPolicy(ActionToolbar.AUTO_LAYOUT_POLICY);
    mySearchActionsToolbar1.setBorder(null);
    mySearchActionsToolbar2.setBorder(null);
    mySearchActionsToolbar1.setOpaque(false);
    mySearchActionsToolbar2.setOpaque(false);

    new ShowMoreOptions(mySearchActionsToolbar1, mySearchFieldWrapper);
    Utils.setSmallerFontForChildren(mySearchActionsToolbar1);
    Utils.setSmallerFontForChildren(mySearchActionsToolbar2);
  }
Пример #22
0
 public static void main(String[] args) {
   Utils.createInEDT(SampleApp.class);
 }