Ejemplo n.º 1
0
 /**
  * Show the typing notification.
  *
  * @param typing true if the typing notification should show, otherwise hide it.
  */
 public void showTyping(boolean typing) {
   if (typing) {
     String isTypingText = Res.getString("message.is.typing.a.message", participantNickname);
     getNotificationLabel().setText(isTypingText);
     getNotificationLabel().setIcon(SparkRes.getImageIcon(SparkRes.SMALL_MESSAGE_EDIT_IMAGE));
   } else {
     // Remove is typing text.
     getNotificationLabel().setText("");
     getNotificationLabel().setIcon(SparkRes.getImageIcon(SparkRes.BLANK_IMAGE));
   }
 }
Ejemplo n.º 2
0
  public RosterNode(String name, boolean isGroup) {
    super(name, true);

    this.name = name;

    this.isGroup = isGroup;
    if (isGroup) {
      openIcon = SparkRes.getImageIcon(SparkRes.MINUS_SIGN);
      closedIcon = SparkRes.getImageIcon(SparkRes.PLUS_SIGN);
    }
  }
Ejemplo n.º 3
0
  @Override
  public void messageReceived(ChatRoom room, Message message, PropertyBundle property) {
    RoarProperties props = RoarProperties.getInstance();

    if (props.getShowingPopups()
        && (_amount < props.getMaximumPopups() || props.getMaximumPopups() == 0)) {

      ImageIcon icon = SparkRes.getImageIcon(SparkRes.SPARK_IMAGE_32x32);

      String nickname = RoarPopupHelper.getNickname(room, message);
      RoarPanel.popupWindow(
          this,
          icon,
          nickname,
          message.getBody(),
          _lastusedXpos,
          _lastusedYpos,
          property.duration,
          property.backgroundColor,
          property.headerColor,
          property.textColor,
          _customaction);

      ++_amount;

      _lastusedYpos -= (HEIGHT + 5);

      if (_lastusedYpos <= HEIGHT + 5) {
        _lastusedXpos -= WIDTH + 5;
        _lastusedYpos = _defaulty;
      }
    }
  }
Ejemplo n.º 4
0
  /**
   * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and setting
   * the Agent to be offline.
   *
   * @param sendStatus true if Spark should send a presence with a status message.
   */
  public void logout(boolean sendStatus) {
    final XMPPConnection con = SparkManager.getConnection();
    String status = null;

    if (con.isConnected() && sendStatus) {
      final InputTextAreaDialog inputTextDialog = new InputTextAreaDialog();
      status =
          inputTextDialog.getInput(
              Res.getString("title.status.message"),
              Res.getString("message.current.status"),
              SparkRes.getImageIcon(SparkRes.USER1_MESSAGE_24x24),
              this);
    }

    if (status != null || !sendStatus) {
      // Notify all MainWindowListeners
      try {
        // Set auto-login to false;
        SettingsManager.getLocalPreferences().setAutoLogin(false);
        SettingsManager.saveSettings();

        fireWindowShutdown();
        setVisible(false);
      } finally {
        closeConnectionAndInvoke(status);
      }
    }
  }
Ejemplo n.º 5
0
 /** Displays the About Box for Spark. */
 private static void showAboutBox() {
   JOptionPane.showMessageDialog(
       SparkManager.getMainWindow(),
       Default.getString(Default.APPLICATION_NAME) + " " + JiveInfo.getVersion(),
       Res.getString("title.about"),
       JOptionPane.INFORMATION_MESSAGE,
       SparkRes.getImageIcon(SparkRes.MAIN_IMAGE));
 }
Ejemplo n.º 6
0
    public Entity(final DiscoverItems.Item item) {
      this.item = item;
      setVerticalTextPosition(JLabel.BOTTOM);
      setHorizontalTextPosition(JLabel.CENTER);
      setText(item.getName());
      setIcon(SparkRes.getImageIcon(SparkRes.USER1_MESSAGE_24x24));

      addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              browseItem(item);
            }
          });
    }
Ejemplo n.º 7
0
  // Modified for cargo
  public ChatRoomImpl(
      final String participantJID,
      final String participantNickname,
      String title,
      CargoOffer cargoOffer) {
    this.active = true;
    this.participantJID = participantJID;
    this.participantNickname = participantNickname;

    String[] results = this.participantJID.split("@");
    this.participantNicknameOnly = results[0];

    // Loads the current history for this user.
    loadHistory();

    // Register PacketListeners
    PacketFilter fromFilter = new FromMatchesFilter(participantJID);
    PacketFilter orFilter =
        new OrFilter(new PacketTypeFilter(Presence.class), new PacketTypeFilter(Message.class));
    PacketFilter andFilter = new AndFilter(orFilter, fromFilter);

    SparkManager.getConnection().addPacketListener(this, andFilter);

    // The roomname will be the participantJID
    this.roomname = participantJID;

    // Use the agents username as the Tab Title
    this.tabTitle = title;

    // The name of the room will be the node of the user jid + conversation.
    this.roomTitle = participantNickname;

    // Add RoomInfo
    this.getSplitPane().setRightComponent(null);
    getSplitPane().setDividerSize(0);

    presence = PresenceManager.getPresence(participantJID);

    roster = SparkManager.getConnection().getRoster();

    RosterEntry entry = roster.getEntry(participantJID);

    tabIcon = PresenceManager.getIconFromPresence(presence);

    infoButton =
        new CargoChatRoomButton("", SparkRes.getImageIcon(SparkRes.SPARK_IKONKA_WIZYTOWKA));
    infoButton.setToolTipText(Res.getString("message.view.information.about.this.user"));
    infoButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

    // Create basic toolbar.
    getToolBar().addChatRoomButton(infoButton);

    // If the user is not in the roster, then allow user to add them.
    // addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.ADD_IMAGE_24x24));

    addToRosterButton = new ChatRoomButton("", SparkRes.getImageIcon(SparkRes.SPARK_IKONKA_DODAJ));
    addToRosterButton.setRolloverIcon(SparkRes.getImageIcon(SparkRes.SPARK_IKONKA_DODAJ));
    addToRosterButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    addToRosterButton.setBorderPainted(false);
    addToRosterButton.setRolloverEnabled(false);
    addToRosterButton.setContentAreaFilled(false);
    addToRosterButton.setIgnoreRepaint(true);
    addToRosterButton.setOpaque(false);
    addToRosterButton.setBorder(null);
    addToRosterButton.setBorderPainted(false);
    addToRosterButton.setMargin(new Insets(0, 0, 0, 0));

    MouseListener[] mouseListeners2 = addToRosterButton.getMouseListeners();
    for (MouseListener mouseListener : mouseListeners2) {
      if (mouseListener instanceof MouseAdapter) {
        addToRosterButton.removeMouseListener(mouseListener);
      }
    }

    if (entry == null && !StringUtils.parseResource(participantJID).equals(participantNickname)) {
      addToRosterButton.setToolTipText(Res.getString("message.add.this.user.to.your.roster"));
      getToolBar().addChatRoomButton(addToRosterButton);

      addToRosterButton.addActionListener(this);
    }

    // Show VCard.
    infoButton.addActionListener(this);

    // If this is a private chat from a group chat room, do not show
    // toolbar.
    if (StringUtils.parseResource(participantJID).equals(participantNickname)) {
      getToolBar().setVisible(false);
    }

    typingTimerTask =
        new TimerTask() {
          public void run() {
            if (!sendTypingNotification) {
              return;
            }
            long now = System.currentTimeMillis();
            if (now - lastTypedCharTime > 2000) {
              if (!sendNotification) {
                // send cancel
                SparkManager.getMessageEventManager()
                    .sendCancelledNotification(getParticipantJID(), threadID);
                sendNotification = true;
              }
            }
          }
        };

    TaskEngine.getInstance().scheduleAtFixedRate(typingTimerTask, 2000, 2000);
    lastActivity = System.currentTimeMillis();

    super.setCargoOffer(cargoOffer);

    this.addMessageEventListener(
        new MessageEventListener() {

          @Override
          public void sendingMessage(Message message) {
            message.setProperty(CARGO_OFFER_PROPERTY, getCargoOffer().getId());
          }

          @Override
          public void receivingMessage(Message message) {}
        });

    this.addMessageListener(
        new org.jivesoftware.spark.ui.MessageListener() {

          @Override
          public void messageReceived(ChatRoom room, Message message) {
            Long cargoOfferId = (Long) message.getProperty(CARGO_OFFER_PROPERTY);
            setCargoOffer(CargoDataManager.getInstance().getCargoOfferById(cargoOfferId));

            if (getCargoOffer() != null) {
              if (acceptedOfferButton != null) {
                getEditorBar().remove(acceptedOfferButton);
              }

              JButton acceptOfferButtonTemp =
                  getAcceptOfferButton(participantNicknameOnly, getCargoOffer());
              acceptedOfferButton = acceptOfferButtonTemp;
              getEditorBar().add(acceptedOfferButton);

            } else {
              Long newCargoOfferId = null;
              if (message.getProperty(CARGO_OFFER_PROPERTY) != null) {
                newCargoOfferId = (Long) message.getProperty(CARGO_OFFER_PROPERTY);
              }

              if (newCargoOfferId != null) {
                CargoOffer co = CargoDataManager.getInstance().getCargoOfferById(newCargoOfferId);
                setCargoOffer(co);

                if (acceptedOfferButton != null) {
                  getEditorBar().remove(acceptedOfferButton);
                }
                JButton acceptOfferButton =
                    getAcceptOfferButton(participantNicknameOnly, getCargoOffer());
                acceptedOfferButton = acceptOfferButton;
                getEditorBar().add(acceptedOfferButton);
              }
            }
          }

          @Override
          public void messageSent(ChatRoom room, Message message) {
            // TODO Auto-generated method stub
            String ooo = "oeoeu";
          }
        });
  }
Ejemplo n.º 8
0
/**
 * The <code>MainWindow</code> class acts as both the DockableHolder and the proxy to the Workspace
 * in Spark.
 *
 * @version 1.0, 03/12/14
 */
public final class MainWindow extends ChatFrame implements ActionListener {
  private static final long serialVersionUID = -6062104959613603510L;

  private final Set<MainWindowListener> listeners = new HashSet<MainWindowListener>();

  private final JMenu connectMenu = new JMenu();
  private final JMenu contactsMenu = new JMenu();
  private final JMenu actionsMenu = new JMenu();
  private final JMenu pluginsMenu = new JMenu();
  private final JMenu helpMenu = new JMenu();

  private JMenuItem preferenceMenuItem;
  private JCheckBoxMenuItem alwaysOnTopItem;

  private final JMenuItem menuAbout =
      new JMenuItem(SparkRes.getImageIcon(SparkRes.INFORMATION_IMAGE));
  private final JMenuItem sparkforumItem = new JMenuItem();

  private final JMenuBar mainWindowBar = new JMenuBar();

  private boolean focused;

  private JToolBar topToolbar = new JToolBar();

  private JSplitPane splitPane;

  private static MainWindow singleton;
  private static final Object LOCK = new Object();

  /**
   * Returns the singleton instance of <CODE>MainWindow</CODE>, creating it if necessary.
   *
   * <p>
   *
   * @return the singleton instance of <Code>MainWindow</CODE>
   */
  public static MainWindow getInstance() {
    // Synchronize on LOCK to ensure that we don't end up creating
    // two singletons.

    synchronized (LOCK) {
      if (null == singleton) {
        MainWindow controller =
            new MainWindow(
                Default.getString(Default.APPLICATION_NAME), SparkManager.getApplicationImage());
        singleton = controller;
      }
    }
    return singleton;
  }

  /**
   * Constructs the UI for the MainWindow. The MainWindow UI is the container for the entire Spark
   * application.
   *
   * @param title the title of the frame.
   * @param icon the icon used in the frame.
   */
  private MainWindow(String title, ImageIcon icon) {

    // Initialize and dock the menus
    buildMenu();

    // Add Workspace Container
    getContentPane().setLayout(new BorderLayout());

    LayoutSettings settings = LayoutSettingsManager.getLayoutSettings();
    if (settings.getMainWindowX() == 0 && settings.getMainWindowY() == 0) {
      // Use default settings.
      setSize(300, 500);
      GraphicUtils.centerWindowOnScreen(this);
    } else {
      setBounds(
          settings.getMainWindowX(),
          settings.getMainWindowY(),
          settings.getMainWindowWidth(),
          settings.getMainWindowHeight());
    }

    // Add menubar
    this.setJMenuBar(mainWindowBar);
    this.getContentPane().add(topToolbar, BorderLayout.NORTH);

    setTitle(title);
    setIconImage(icon.getImage());

    // Setup WindowListener to be the proxy to the actual window listener
    // which cannot normally be used outside of the Window component because
    // of protected access.
    addWindowListener(
        new WindowAdapter() {

          /**
           * This event fires when the window has become active.
           *
           * @param e WindowEvent is not used.
           */
          public void windowActivated(WindowEvent e) {
            fireWindowActivated();
          }

          /** Invoked when a window is de-activated. */
          public void windowDeactivated(WindowEvent e) {}

          /**
           * This event fires whenever a user minimizes the window from the toolbar.
           *
           * @param e WindowEvent is not used.
           */
          public void windowIconified(WindowEvent e) {}

          /**
           * This event fires when the application is closing. This allows Plugins to do any
           * persistence or other work before exiting.
           *
           * @param e WindowEvent is never used.
           */
          public void windowClosing(WindowEvent e) {
            saveLayout();
            setVisible(false);
          }
        });

    this.addWindowFocusListener(new MainWindowFocusListener());
  }

  /**
   * Adds a MainWindow listener to {@link MainWindow}. The listener will be called when either the
   * MainWindow has been minimized, maximized, or is shutting down.
   *
   * @param listener the <code>MainWindowListener</code> to register
   */
  public void addMainWindowListener(MainWindowListener listener) {
    listeners.add(listener);
  }

  /**
   * Removes the specified {@link MainWindowListener}.
   *
   * @param listener the <code>MainWindowListener</code> to remove.
   */
  public void removeMainWindowListener(MainWindowListener listener) {
    listeners.remove(listener);
  }

  /**
   * Notifies all {@link MainWindowListener}s that the <code>MainWindow</code> has been activated.
   */
  private void fireWindowActivated() {
    for (MainWindowListener listener : listeners) {
      listener.mainWindowActivated();
    }

    if (Spark.isMac()) {
      setJMenuBar(mainWindowBar);
    }
  }

  /** Notifies all {@link MainWindowListener}s that the <code>MainWindow</code> is shutting down. */
  private void fireWindowShutdown() {
    for (MainWindowListener listener : listeners) {
      listener.shutdown();
    }
  }

  /**
   * Invokes the Preferences Dialog.
   *
   * @param e the ActionEvent
   */
  public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(preferenceMenuItem)) {
      SparkManager.getPreferenceManager().showPreferences();
    }
  }

  /**
   * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and setting
   * the Agent to be offline.
   */
  public void shutdown() {
    final XMPPConnection con = SparkManager.getConnection();

    if (con.isConnected()) {
      // Send disconnect.
      con.disconnect();
    }

    // Notify all MainWindowListeners
    try {
      fireWindowShutdown();
    } catch (Exception ex) {
      Log.error(ex);
    }
    // Close application.
    if (!Default.getBoolean("DISABLE_EXIT")) System.exit(1);
  }

  /**
   * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and setting
   * the Agent to be offline.
   *
   * @param sendStatus true if Spark should send a presence with a status message.
   */
  public void logout(boolean sendStatus) {
    final XMPPConnection con = SparkManager.getConnection();
    String status = null;

    if (con.isConnected() && sendStatus) {
      final InputTextAreaDialog inputTextDialog = new InputTextAreaDialog();
      status =
          inputTextDialog.getInput(
              Res.getString("title.status.message"),
              Res.getString("message.current.status"),
              SparkRes.getImageIcon(SparkRes.USER1_MESSAGE_24x24),
              this);
    }

    if (status != null || !sendStatus) {
      // Notify all MainWindowListeners
      try {
        // Set auto-login to false;
        SettingsManager.getLocalPreferences().setAutoLogin(false);
        SettingsManager.saveSettings();

        fireWindowShutdown();
        setVisible(false);
      } finally {
        closeConnectionAndInvoke(status);
      }
    }
  }

  /**
   * Closes the current connection and restarts Spark.
   *
   * @param reason the reason for logging out. This can be if user gave no reason.
   */
  public void closeConnectionAndInvoke(String reason) {
    final XMPPConnection con = SparkManager.getConnection();
    if (con.isConnected()) {
      if (reason != null) {
        Presence byePresence = new Presence(Presence.Type.unavailable, reason, -1, null);
        con.disconnect(byePresence);
      } else {
        con.disconnect();
      }
    }
    if (!restartApplicationWithScript()) {
      restartApplicationWithJava();
    }
  }

  private File getLibDirectory() throws IOException {
    File jarFile;
    try {
      jarFile = new File(Startup.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    } catch (Exception e) {
      Log.error("Cannot get jar file containing the startup class", e);
      return null;
    }
    if (!jarFile.getName().endsWith(".jar")) {
      Log.error("The startup class is not packaged in a jar file");
      return null;
    }
    File libDir = jarFile.getParentFile();
    return libDir;
  }

  private String getClasspath() throws IOException {
    File libDir = getLibDirectory();
    String libPath = libDir.getCanonicalPath();
    String[] files = libDir.list();
    StringBuilder classpath = new StringBuilder();
    for (String file : files) {
      if (file.endsWith(".jar")) {
        classpath.append(libPath + File.separatorChar + file + File.pathSeparatorChar);
      }
    }
    return classpath.toString();
  }

  private String getCommandPath() throws IOException {
    return getLibDirectory().getParentFile().getCanonicalPath();
  }

  public boolean restartApplicationWithScript() {
    String command = null;
    try {
      if (Spark.isWindows()) {
        String sparkExe =
            getCommandPath() + File.separator + Default.getString(Default.SHORT_NAME) + ".exe";
        if (!new File(sparkExe).exists()) {
          Log.warning("Client EXE file does not exist");
          return false;
        }
        String starterExe = getCommandPath() + File.separator + "starter.exe";
        if (!new File(starterExe).exists()) {
          Log.warning("Starter EXE file does not exist");
          return false;
        }
        command = starterExe + " \"" + sparkExe + "\"";
      } else if (Spark.isLinux()) {
        command = getCommandPath() + File.separator + Default.getString(Default.SHORT_NAME);
        if (!new File(command).exists()) {
          Log.warning("Client startup script does not exist");
          return false;
        }
      } else if (Spark.isMac()) {
        command = "open -a " + Default.getString(Default.SHORT_NAME);
      }

      Runtime.getRuntime().exec(command);
      System.exit(0);
      return true;
    } catch (IOException e) {
      Log.error("Error trying to restart application with script", e);
      return false;
    }
  }

  public boolean restartApplicationWithJava() {
    String javaBin =
        System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar + "java";
    try {
      String toExec[] =
          new String[] {javaBin, "-cp", getClasspath(), "org.jivesoftware.launcher.Startup"};
      Runtime.getRuntime().exec(toExec);
    } catch (Exception e) {
      Log.error("Error trying to restart application with java", e);
      return false;
    }
    System.exit(0);
    return true;
  }

  /** Setup the Main Toolbar with File, Tools and Help. */
  private void buildMenu() {

    // setup file menu
    final JMenuItem exitMenuItem = new JMenuItem();

    // Setup ResourceUtils
    ResourceUtils.resButton(connectMenu, "&" + Default.getString(Default.APPLICATION_NAME));
    ResourceUtils.resButton(contactsMenu, Res.getString("menuitem.contacts"));
    ResourceUtils.resButton(actionsMenu, Res.getString("menuitem.actions"));
    ResourceUtils.resButton(exitMenuItem, Res.getString("menuitem.exit"));
    ResourceUtils.resButton(pluginsMenu, Res.getString("menuitem.plugins"));

    exitMenuItem.setIcon(null);

    mainWindowBar.add(connectMenu);
    mainWindowBar.add(contactsMenu);
    mainWindowBar.add(actionsMenu);
    // mainWindowBar.add(pluginsMenu);
    mainWindowBar.add(helpMenu);

    preferenceMenuItem = new JMenuItem(SparkRes.getImageIcon(SparkRes.PREFERENCES_IMAGE));
    preferenceMenuItem.setText(Res.getString("title.spark.preferences"));
    preferenceMenuItem.addActionListener(this);
    connectMenu.add(preferenceMenuItem);

    alwaysOnTopItem = new JCheckBoxMenuItem();
    ResourceUtils.resButton(alwaysOnTopItem, Res.getString("menuitem.always.on.top"));
    alwaysOnTopItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            if (alwaysOnTopItem.isSelected()) {
              SettingsManager.getLocalPreferences().setMainWindowAlwaysOnTop(true);
              MainWindow.getInstance().setAlwaysOnTop(true);
            } else {
              SettingsManager.getLocalPreferences().setMainWindowAlwaysOnTop(false);
              MainWindow.getInstance().setAlwaysOnTop(false);
            }
          }
        });

    if (SettingsManager.getLocalPreferences().isMainWindowAlwaysOnTop()) {
      alwaysOnTopItem.setSelected(true);
      this.setAlwaysOnTop(true);
    }
    connectMenu.add(alwaysOnTopItem);

    if (!Default.getBoolean("DISABLE_EXIT")) connectMenu.addSeparator();

    // EventQueue.invokeLater(new Runnable() {
    //	public void run() {

    JMenuItem logoutMenuItem = new JMenuItem();
    ResourceUtils.resButton(logoutMenuItem, Res.getString("menuitem.logout.no.status"));
    logoutMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            logout(false);
          }
        });

    JMenuItem logoutWithStatus = new JMenuItem();
    ResourceUtils.resButton(logoutWithStatus, Res.getString("menuitem.logout.with.status"));
    logoutWithStatus.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            logout(true);
          }
        });

    if ((Spark.isWindows() || Spark.isLinux() || Spark.isMac())
        && !Default.getBoolean("DISABLE_EXIT")) {
      connectMenu.add(logoutMenuItem);
      connectMenu.add(logoutWithStatus);
      connectMenu.addSeparator();
    }

    if (!Default.getBoolean("DISABLE_EXIT")) {
      connectMenu.add(exitMenuItem);
    }

    JMenuItem updateMenu = new JMenuItem("", SparkRes.getImageIcon(SparkRes.DOWNLOAD_16x16));
    ResourceUtils.resButton(updateMenu, Res.getString("menuitem.check.for.updates"));
    updateMenu.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            checkForUpdates(true);
          }
        });

    // Add Error Dialog Viewer
    final Action viewErrors =
        new AbstractAction() {
          private static final long serialVersionUID = -420926784631340112L;

          public void actionPerformed(ActionEvent e) {
            File logDir = new File(Spark.getLogDirectory(), "errors.log");
            if (!logDir.exists()) {
              JOptionPane.showMessageDialog(
                  SparkManager.getMainWindow(),
                  "No error logs found.",
                  "Error Log",
                  JOptionPane.INFORMATION_MESSAGE);
            } else {
              showErrorLog();
            }
          }
        };

    viewErrors.putValue(Action.NAME, Res.getString("menuitem.view.logs"));

    final Action viewHelpGuideAction =
        new AbstractAction() {

          final String url = Default.getString(Default.HELP_USER_GUIDE);
          private static final long serialVersionUID = 2680369963282231348L;

          public void actionPerformed(ActionEvent actionEvent) {
            try {

              BrowserLauncher.openURL(url);
            } catch (Exception e) {
              Log.error("Unable to load online help.", e);
            }
          }
        };

    if (!Default.getBoolean("HELP_USER_GUIDE_DISABLED")) {
      viewHelpGuideAction.putValue(Action.NAME, Res.getString("menuitem.user.guide"));
      viewHelpGuideAction.putValue(
          Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_QUESTION));
      helpMenu.add(viewHelpGuideAction);
    }
    if (!Default.getBoolean("HELP_FORUM_DISABLED")) {
      helpMenu.add(sparkforumItem);
    }

    // Build Help Menu
    if (!Default.getBoolean(Default.DISABLE_UPDATES)) {
      helpMenu.add(updateMenu);
    }
    helpMenu.addSeparator();
    helpMenu.add(viewErrors);
    helpMenu.add(menuAbout);

    // ResourceUtils - Adds mnemonics
    ResourceUtils.resButton(preferenceMenuItem, Res.getString("menuitem.preferences"));
    ResourceUtils.resButton(helpMenu, Res.getString("menuitem.help"));
    ResourceUtils.resButton(menuAbout, Res.getString("menuitem.about"));

    if (Default.getString("HELP_FORUM_TEXT").length() > 0) {
      ResourceUtils.resButton(sparkforumItem, Default.getString("HELP_FORUM_TEXT"));
    } else {
      ResourceUtils.resButton(sparkforumItem, Res.getString("menuitem.online.help"));
    }
    // Register shutdown with the exit menu.
    exitMenuItem.addActionListener(
        new AbstractAction() {
          private static final long serialVersionUID = -2301236575241532698L;

          public void actionPerformed(ActionEvent e) {
            shutdown();
          }
        });

    sparkforumItem.addActionListener(
        new AbstractAction() {
          private static final long serialVersionUID = -1423433460333010339L;

          final String url = Default.getString("HELP_FORUM");

          public void actionPerformed(ActionEvent e) {
            try {
              BrowserLauncher.openURL(url);
            } catch (Exception browserException) {
              Log.error("Error launching browser:", browserException);
            }
          }
        });

    // Show About Box
    menuAbout.addActionListener(
        new AbstractAction() {
          private static final long serialVersionUID = -7173666373051354502L;

          public void actionPerformed(ActionEvent e) {
            showAboutBox();
          }
        });

    if (!Default.getBoolean("DISABLE_UPDATES")) {
      // Execute spark update checker after one minute.
      final TimerTask task =
          new SwingTimerTask() {
            public void doRun() {
              checkForUpdates(false);
            }
          };

      TaskEngine.getInstance().schedule(task, 60000);
    }

    if (SettingsManager.getLocalPreferences().isDebuggerEnabled()) {
      JMenuItem rawPackets = new JMenuItem(SparkRes.getImageIcon(SparkRes.TRAY_IMAGE));
      rawPackets.setText("Send Packets");
      rawPackets.addActionListener(
          new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              new RawPacketSender();
            }
          });

      connectMenu.add(rawPackets, 2);
    }
  }

  /**
   * Returns the JMenuBar for the MainWindow. You would call this if you wished to add or remove
   * menu items to the main menubar. (File | Tools | Help)
   *
   * @return the Jive Talker Main Window MenuBar
   */
  public JMenuBar getMenu() {
    return mainWindowBar;
  }

  /**
   * Returns the Menu in the JMenuBar by it's name. For example:
   *
   * <p>
   *
   * <pre>
   * JMenu toolsMenu = getMenuByName("Tools");
   * </pre>
   *
   * @param name the name of the Menu.
   * @return the JMenu item with the requested name.
   */
  public JMenu getMenuByName(String name) {
    for (int i = 0; i < getMenu().getMenuCount(); i++) {
      JMenu menu = getMenu().getMenu(i);
      if (menu.getText().equals(name)) {
        return menu;
      }
    }
    return null;
  }

  /**
   * Returns true if the Spark window is in focus.
   *
   * @return true if the Spark window is in focus.
   */
  public boolean isInFocus() {
    return focused;
  }

  private class MainWindowFocusListener implements WindowFocusListener {

    public void windowGainedFocus(WindowEvent e) {
      focused = true;
    }

    public void windowLostFocus(WindowEvent e) {
      focused = false;
    }
  }

  /**
   * Return the top toolbar in the Main Window to allow for customization.
   *
   * @return the MainWindows top toolbar.
   */
  public JToolBar getTopToolBar() {
    return topToolbar;
  }

  /**
   * Checks for the latest update on the server.
   *
   * @param forced true if you want to bypass the normal checking security.
   */
  private void checkForUpdates(final boolean forced) {
    final CheckUpdates updater = new CheckUpdates();
    try {
      final SwingWorker updateThread =
          new SwingWorker() {
            public Object construct() {
              try {
                Thread.sleep(50);
              } catch (InterruptedException e) {
                Log.error(e);
              }
              return "ok";
            }

            public void finished() {
              try {
                updater.checkForUpdate(forced);
              } catch (Exception e) {
                Log.error("There was an error while checking for a new update.", e);
              }
            }
          };

      updateThread.start();

    } catch (Exception e) {
      Log.warning("Error updating.", e);
    }
  }

  /** Displays the About Box for Spark. */
  private static void showAboutBox() {
    JOptionPane.showMessageDialog(
        SparkManager.getMainWindow(),
        Default.getString(Default.APPLICATION_NAME) + " " + JiveInfo.getVersion(),
        Res.getString("title.about"),
        JOptionPane.INFORMATION_MESSAGE,
        SparkRes.getImageIcon(SparkRes.MAIN_IMAGE));
  }

  /** Displays the Spark error log. */
  private void showErrorLog() {
    final File logDir = new File(Spark.getLogDirectory(), "errors.log");

    // Read file and show
    final String errorLogs = URLFileSystem.getContents(logDir);

    final JFrame frame = new JFrame(Res.getString("title.client.logs"));
    frame.setLayout(new BorderLayout());
    frame.setIconImage(SparkManager.getApplicationImage().getImage());

    final JTextPane pane = new JTextPane();
    pane.setBackground(Color.white);
    pane.setFont(new Font("Dialog", Font.PLAIN, 12));
    pane.setEditable(false);
    pane.setText(errorLogs);

    frame.add(new JScrollPane(pane), BorderLayout.CENTER);

    final JButton copyButton = new JButton(Res.getString("button.copy.to.clipboard"));
    frame.add(copyButton, BorderLayout.SOUTH);

    copyButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            SparkManager.setClipboard(errorLogs);
            copyButton.setEnabled(false);
          }
        });

    frame.pack();
    frame.setSize(600, 400);

    GraphicUtils.centerWindowOnScreen(frame);
    frame.setVisible(true);
  }

  /** Saves the layout on closing of the main window. */
  public void saveLayout() {
    try {
      LayoutSettings settings = LayoutSettingsManager.getLayoutSettings();
      settings.setMainWindowHeight(getHeight());
      settings.setMainWindowWidth(getWidth());
      settings.setMainWindowX(getX());
      settings.setMainWindowY(getY());
      LayoutSettingsManager.saveLayoutSettings();
    } catch (Exception e) {
      // Don't let this cause a real problem shutting down.
    }
  }

  /**
   * Return true if the MainWindow is docked.
   *
   * @return true if the window is docked.
   */
  public boolean isDocked() {
    LocalPreferences preferences = SettingsManager.getLocalPreferences();
    return preferences.isDockingEnabled();
  }

  /**
   * Returns the inner split pane.
   *
   * @return the split pane.
   */
  public JSplitPane getSplitPane() {
    // create the split pane only if required.
    if (splitPane == null) {
      splitPane = new JSplitPane();
    }
    return this.splitPane;
  }
}
Ejemplo n.º 9
0
  /** Setup the Main Toolbar with File, Tools and Help. */
  private void buildMenu() {

    // setup file menu
    final JMenuItem exitMenuItem = new JMenuItem();

    // Setup ResourceUtils
    ResourceUtils.resButton(connectMenu, "&" + Default.getString(Default.APPLICATION_NAME));
    ResourceUtils.resButton(contactsMenu, Res.getString("menuitem.contacts"));
    ResourceUtils.resButton(actionsMenu, Res.getString("menuitem.actions"));
    ResourceUtils.resButton(exitMenuItem, Res.getString("menuitem.exit"));
    ResourceUtils.resButton(pluginsMenu, Res.getString("menuitem.plugins"));

    exitMenuItem.setIcon(null);

    mainWindowBar.add(connectMenu);
    mainWindowBar.add(contactsMenu);
    mainWindowBar.add(actionsMenu);
    // mainWindowBar.add(pluginsMenu);
    mainWindowBar.add(helpMenu);

    preferenceMenuItem = new JMenuItem(SparkRes.getImageIcon(SparkRes.PREFERENCES_IMAGE));
    preferenceMenuItem.setText(Res.getString("title.spark.preferences"));
    preferenceMenuItem.addActionListener(this);
    connectMenu.add(preferenceMenuItem);

    alwaysOnTopItem = new JCheckBoxMenuItem();
    ResourceUtils.resButton(alwaysOnTopItem, Res.getString("menuitem.always.on.top"));
    alwaysOnTopItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            if (alwaysOnTopItem.isSelected()) {
              SettingsManager.getLocalPreferences().setMainWindowAlwaysOnTop(true);
              MainWindow.getInstance().setAlwaysOnTop(true);
            } else {
              SettingsManager.getLocalPreferences().setMainWindowAlwaysOnTop(false);
              MainWindow.getInstance().setAlwaysOnTop(false);
            }
          }
        });

    if (SettingsManager.getLocalPreferences().isMainWindowAlwaysOnTop()) {
      alwaysOnTopItem.setSelected(true);
      this.setAlwaysOnTop(true);
    }
    connectMenu.add(alwaysOnTopItem);

    if (!Default.getBoolean("DISABLE_EXIT")) connectMenu.addSeparator();

    // EventQueue.invokeLater(new Runnable() {
    //	public void run() {

    JMenuItem logoutMenuItem = new JMenuItem();
    ResourceUtils.resButton(logoutMenuItem, Res.getString("menuitem.logout.no.status"));
    logoutMenuItem.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            logout(false);
          }
        });

    JMenuItem logoutWithStatus = new JMenuItem();
    ResourceUtils.resButton(logoutWithStatus, Res.getString("menuitem.logout.with.status"));
    logoutWithStatus.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            logout(true);
          }
        });

    if ((Spark.isWindows() || Spark.isLinux() || Spark.isMac())
        && !Default.getBoolean("DISABLE_EXIT")) {
      connectMenu.add(logoutMenuItem);
      connectMenu.add(logoutWithStatus);
      connectMenu.addSeparator();
    }

    if (!Default.getBoolean("DISABLE_EXIT")) {
      connectMenu.add(exitMenuItem);
    }

    JMenuItem updateMenu = new JMenuItem("", SparkRes.getImageIcon(SparkRes.DOWNLOAD_16x16));
    ResourceUtils.resButton(updateMenu, Res.getString("menuitem.check.for.updates"));
    updateMenu.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            checkForUpdates(true);
          }
        });

    // Add Error Dialog Viewer
    final Action viewErrors =
        new AbstractAction() {
          private static final long serialVersionUID = -420926784631340112L;

          public void actionPerformed(ActionEvent e) {
            File logDir = new File(Spark.getLogDirectory(), "errors.log");
            if (!logDir.exists()) {
              JOptionPane.showMessageDialog(
                  SparkManager.getMainWindow(),
                  "No error logs found.",
                  "Error Log",
                  JOptionPane.INFORMATION_MESSAGE);
            } else {
              showErrorLog();
            }
          }
        };

    viewErrors.putValue(Action.NAME, Res.getString("menuitem.view.logs"));

    final Action viewHelpGuideAction =
        new AbstractAction() {

          final String url = Default.getString(Default.HELP_USER_GUIDE);
          private static final long serialVersionUID = 2680369963282231348L;

          public void actionPerformed(ActionEvent actionEvent) {
            try {

              BrowserLauncher.openURL(url);
            } catch (Exception e) {
              Log.error("Unable to load online help.", e);
            }
          }
        };

    if (!Default.getBoolean("HELP_USER_GUIDE_DISABLED")) {
      viewHelpGuideAction.putValue(Action.NAME, Res.getString("menuitem.user.guide"));
      viewHelpGuideAction.putValue(
          Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_QUESTION));
      helpMenu.add(viewHelpGuideAction);
    }
    if (!Default.getBoolean("HELP_FORUM_DISABLED")) {
      helpMenu.add(sparkforumItem);
    }

    // Build Help Menu
    if (!Default.getBoolean(Default.DISABLE_UPDATES)) {
      helpMenu.add(updateMenu);
    }
    helpMenu.addSeparator();
    helpMenu.add(viewErrors);
    helpMenu.add(menuAbout);

    // ResourceUtils - Adds mnemonics
    ResourceUtils.resButton(preferenceMenuItem, Res.getString("menuitem.preferences"));
    ResourceUtils.resButton(helpMenu, Res.getString("menuitem.help"));
    ResourceUtils.resButton(menuAbout, Res.getString("menuitem.about"));

    if (Default.getString("HELP_FORUM_TEXT").length() > 0) {
      ResourceUtils.resButton(sparkforumItem, Default.getString("HELP_FORUM_TEXT"));
    } else {
      ResourceUtils.resButton(sparkforumItem, Res.getString("menuitem.online.help"));
    }
    // Register shutdown with the exit menu.
    exitMenuItem.addActionListener(
        new AbstractAction() {
          private static final long serialVersionUID = -2301236575241532698L;

          public void actionPerformed(ActionEvent e) {
            shutdown();
          }
        });

    sparkforumItem.addActionListener(
        new AbstractAction() {
          private static final long serialVersionUID = -1423433460333010339L;

          final String url = Default.getString("HELP_FORUM");

          public void actionPerformed(ActionEvent e) {
            try {
              BrowserLauncher.openURL(url);
            } catch (Exception browserException) {
              Log.error("Error launching browser:", browserException);
            }
          }
        });

    // Show About Box
    menuAbout.addActionListener(
        new AbstractAction() {
          private static final long serialVersionUID = -7173666373051354502L;

          public void actionPerformed(ActionEvent e) {
            showAboutBox();
          }
        });

    if (!Default.getBoolean("DISABLE_UPDATES")) {
      // Execute spark update checker after one minute.
      final TimerTask task =
          new SwingTimerTask() {
            public void doRun() {
              checkForUpdates(false);
            }
          };

      TaskEngine.getInstance().schedule(task, 60000);
    }

    if (SettingsManager.getLocalPreferences().isDebuggerEnabled()) {
      JMenuItem rawPackets = new JMenuItem(SparkRes.getImageIcon(SparkRes.TRAY_IMAGE));
      rawPackets.setText("Send Packets");
      rawPackets.addActionListener(
          new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
              new RawPacketSender();
            }
          });

      connectMenu.add(rawPackets, 2);
    }
  }
Ejemplo n.º 10
0
  /**
   * Displays the VCard for an individual.
   *
   * @param vCard the users vcard.
   * @param parent the parent component, used for location.
   */
  public void editProfile(final VCard vCard, JComponent parent) {
    final JTabbedPane tabbedPane = new JTabbedPane();

    // Initialize Panels
    personalPanel = new PersonalPanel();
    personalPanel.showJID(false);

    businessPanel = new BusinessPanel();
    homePanel = new HomePanel();
    avatarPanel = new AvatarPanel();
    // employeePanel		= new EmployeePanel();

    String employeeOf = vCard.getField("employeeOf");
    if (vCard.getJabberId()
        == SparkManager.getUserManager()
            .getJIDFromDisplayName(SparkManager.getUserManager().getNickname())) {
      if ((employeeOf == null || employeeOf.isEmpty())) {
        employeeListPanel = new EmployeeListPanel();

        tabbedPane.addTab(Res.getString("tab.home"), homePanel);
        tabbedPane.addTab(Res.getString("tab.business"), personalPanel);
        tabbedPane.addTab(Res.getString("tab.business"), businessPanel);
        tabbedPane.addTab(Res.getString("tab.employees"), employeeListPanel); // zmienione
        employee = false;
      } else {
      }
    }

    tabbedPane.addTab(Res.getString("tab.avatar"), avatarPanel);

    // Build the UI
    buildUI(vCard);

    final JOptionPane pane;
    final JDialog dlg;

    TitlePanel titlePanel;

    ImageIcon icon = VCardManager.getAvatarIcon(vCard);
    if (icon == null) {
      icon = SparkRes.getImageIcon(SparkRes.BLANK_24x24);
    }

    // Create the title panel for this dialog
    titlePanel =
        new TitlePanel(
            Res.getString("title.edit.profile"), Res.getString("message.save.profile"), icon, true);

    // Construct main panel w/ layout.
    final JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(titlePanel, BorderLayout.NORTH);

    // The user should only be able to close this dialog.
    Object[] options = {Res.getString("save"), Res.getString("cancel")};
    pane =
        new JOptionPane(
            tabbedPane,
            JOptionPane.PLAIN_MESSAGE,
            JOptionPane.OK_CANCEL_OPTION,
            null,
            options,
            options[0]);

    mainPanel.add(pane, BorderLayout.CENTER);

    JOptionPane p = new JOptionPane();
    dlg = p.createDialog(parent, Res.getString("title.profile.information"));
    dlg.setModal(false);

    dlg.pack();
    dlg.setSize(600, 400);
    dlg.setResizable(true);
    dlg.setContentPane(mainPanel);
    dlg.setLocationRelativeTo(parent);

    PropertyChangeListener changeListener =
        new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent e) {
            String value = (String) pane.getValue();
            if (Res.getString("cancel").equals(value)) {
              pane.removePropertyChangeListener(this);
              dlg.dispose();
            } else if (Res.getString("save").equals(value)) {
              //                    pane.removePropertyChangeListener(this);
              // dlg.dispose();
              // saveVCard();
              preSaveVCard();
            }
          }
        };

    // JPanel bottomPanel = (JPanel)pane.getComponent(0);

    JButton saveButton = new JButton();

    tabbedPane.addChangeListener(
        new ChangeListener() {

          @Override
          public void stateChanged(ChangeEvent e) {
            preSaveVCard();
          }
        });

    for (Component component : pane.getComponents()) {
      if (component instanceof JButton) {
        JButton b = (JButton) component;

        if (b.getText().equalsIgnoreCase("Save")) {
          saveButton = (JButton) component;
        }
      }
    }

    saveButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            preSaveVCard();
          }
        });

    avatarPanel.setParentDialog(dlg);
    dlg.setVisible(true);
    dlg.toFront();
    dlg.requestFocus();

    personalPanel.focus();
  }
Ejemplo n.º 11
0
  /**
   * Displays a users profile.
   *
   * @param jid the jid of the user.
   * @param vcard the users vcard.
   * @param parent the parent component, used for location handling.
   */
  public void displayProfile(final String jid, VCard vcard, JComponent parent) {
    VCardViewer viewer = new VCardViewer(jid);

    final JFrame dlg = new JFrame(Res.getString("title.view.profile.for", jid));

    avatarLabel = new JLabel();
    avatarLabel.setHorizontalAlignment(JButton.RIGHT);
    avatarLabel.setBorder(BorderFactory.createBevelBorder(0, Color.white, Color.lightGray));

    // The user should only be able to close this dialog.
    Object[] options = {Res.getString("button.view.profile"), Res.getString("close")};
    final JOptionPane pane =
        new JOptionPane(
            viewer,
            JOptionPane.PLAIN_MESSAGE,
            JOptionPane.OK_CANCEL_OPTION,
            null,
            options,
            options[0]);

    //  mainPanel.add(pane, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
    // GridBagConstraints.BOTH, new Insets(0, 5, 5, 5), 0, 0));

    dlg.setIconImage(SparkRes.getImageIcon(SparkRes.PROFILE_IMAGE_16x16).getImage());

    dlg.pack();
    dlg.setSize(350, 250);
    dlg.setResizable(true);
    dlg.setContentPane(pane);
    dlg.setLocationRelativeTo(parent);

    PropertyChangeListener changeListener =
        new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent e) {
            if (pane.getValue() instanceof Integer) {
              pane.removePropertyChangeListener(this);
              dlg.dispose();
              return;
            }
            String value = (String) pane.getValue();
            if (Res.getString("close").equals(value)) {
              pane.removePropertyChangeListener(this);
              dlg.dispose();
            } else if (Res.getString("button.view.profile").equals(value)) {
              pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
              SparkManager.getVCardManager().viewFullProfile(jid, pane);
            }
          }
        };

    pane.addPropertyChangeListener(changeListener);

    dlg.addKeyListener(
        new KeyAdapter() {
          public void keyPressed(KeyEvent keyEvent) {
            if (keyEvent.getKeyChar() == KeyEvent.VK_ESCAPE) {
              dlg.dispose();
            }
          }
        });

    dlg.setVisible(true);
    dlg.toFront();
    dlg.requestFocus();
  }
Ejemplo n.º 12
0
  /**
   * Displays the VCard for an individual.
   *
   * @param vCard the users vcard.
   * @param parent the parent component, used for location.
   */
  public void viewFullProfile(final VCard vCard, JComponent parent) {
    final JTabbedPane tabbedPane = new JTabbedPane();

    // Initialize Panels
    personalPanel = new PersonalPanel();
    personalPanel.allowEditing(false);
    personalPanel.showJID(false);

    //        tabbedPane.addTab(Res.getString("tab.personal"), personalPanel);

    businessPanel = new BusinessPanel();
    businessPanel.allowEditing(false);
    tabbedPane.addTab(Res.getString("tab.business"), businessPanel);

    homePanel = new HomePanel();
    homePanel.allowEditing(false);
    //        tabbedPane.addTab(Res.getString("tab.home"), homePanel);

    avatarPanel = new AvatarPanel();
    avatarPanel.allowEditing(false);
    tabbedPane.addTab(Res.getString("tab.avatar"), avatarPanel);

    //        employeePanel = new EmployeePanel();
    //        employeePanel.allowEditing(false);
    //        tabbedPane.addTab("Pracownicy", employeePanel);

    String employeeOf = vCard.getField("employeeOf");
    if (vCard.getJabberId()
        == SparkManager.getUserManager()
            .getJIDFromDisplayName(SparkManager.getUserManager().getNickname())) {
      if ((employeeOf == null || employeeOf.isEmpty())) {
        employeeListPanel = new EmployeeListPanel();
        tabbedPane.addTab(Res.getString("tab.home"), homePanel);
        tabbedPane.addTab(Res.getString("tab.business"), businessPanel);
        tabbedPane.addTab("Pracownicy", employeeListPanel);
        employee = false;
      } else {

      }
    }

    // Build the UI
    buildUI(vCard);

    final JOptionPane pane;
    final JDialog dlg;

    TitlePanel titlePanel;

    ImageIcon icon = VCardManager.getAvatarIcon(vCard);
    if (icon == null) {
      icon = SparkRes.getImageIcon(SparkRes.BLANK_24x24);
    }

    // Create the title panel for this dialog
    titlePanel = new TitlePanel(Res.getString("title.profile.information"), "", icon, true);

    // Construct main panel w/ layout.
    final JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(titlePanel, BorderLayout.NORTH);

    // The user should only be able to close this dialog.
    Object[] options = {Res.getString("close")};
    pane =
        new JOptionPane(
            tabbedPane,
            JOptionPane.PLAIN_MESSAGE,
            JOptionPane.OK_CANCEL_OPTION,
            null,
            options,
            options[0]);

    mainPanel.add(pane, BorderLayout.CENTER);

    JOptionPane p = new JOptionPane();
    dlg = p.createDialog(parent, Res.getString("title.profile.information"));
    dlg.setModal(false);

    dlg.pack();
    dlg.setSize(600, 400);
    dlg.setResizable(true);
    dlg.setContentPane(mainPanel);
    dlg.setLocationRelativeTo(parent);

    PropertyChangeListener changeListener =
        new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent e) {
            Object o = pane.getValue();
            if (o instanceof Integer) {
              pane.removePropertyChangeListener(this);
              dlg.dispose();
              return;
            }

            String value = (String) pane.getValue();
            if (Res.getString("close").equals(value)) {
              pane.removePropertyChangeListener(this);
              dlg.dispose();
            }
          }
        };

    pane.addPropertyChangeListener(changeListener);

    dlg.setVisible(true);
    dlg.toFront();
    dlg.requestFocus();

    personalPanel.focus();
  }
Ejemplo n.º 13
0
  private JButton getAcceptOfferButton(final String nick, CargoOffer co) {
    JButton acceptOfferButton = new JButton();
    acceptOfferButton.setToolTipText("Zaakceptuj ofert\u0119");

    CargoOffersLoadPanel loadPanel = new CargoOffersLoadPanel();
    JPanel renderedPanel = new JPanel();
    loadPanel.render(co, renderedPanel, 0);
    renderedPanel.setOpaque(false);

    CargoOffersUnloadPanel unloadPanel = new CargoOffersUnloadPanel();
    JPanel renderedUnloadPanel = new JPanel();
    unloadPanel.render(co, renderedUnloadPanel, 0);
    renderedUnloadPanel.setOpaque(false);

    CargoOffersSubmissionDatePanel submissionPanel = new CargoOffersSubmissionDatePanel();
    JPanel renderedSubmissionDatePanel = new JPanel();
    submissionPanel.render(co, renderedSubmissionDatePanel, 0);
    renderedSubmissionDatePanel.setOpaque(false);

    renderedSubmissionDatePanel.setOpaque(false);

    acceptOfferButton.setLayout(new FlowLayout());

    acceptOfferButton.add(renderedPanel);
    acceptOfferButton.add(renderedUnloadPanel);
    acceptOfferButton.add(renderedSubmissionDatePanel);

    // dodatki wygladowe tego buttonu
    acceptOfferButton.setBorderPainted(false);
    acceptOfferButton.setContentAreaFilled(false);
    acceptOfferButton.setFocusPainted(false);
    acceptOfferButton.setOpaque(false);
    acceptOfferButton.setVerticalTextPosition(SwingConstants.CENTER);
    acceptOfferButton.setHorizontalTextPosition(SwingConstants.CENTER);
    acceptOfferButton.setIcon(SparkRes.getImageIcon(SparkRes.CARGO_AKCEPTACJA_OFERTY1));
    acceptOfferButton.setRolloverIcon(SparkRes.getImageIcon(SparkRes.CARGO_AKCEPTACJA_OFERTY2));
    acceptOfferButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    // koniec dodatkow

    acceptOfferButton.addActionListener(
        new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            String initiator = null;
            String initiated = null;

            initiator = SparkManager.getSessionManager().getUsername();
            initiated = nick;

            CargoOffer co = getCargoOffer();
            OfferAcceptance offerAcceptance = new OfferAcceptance();
            offerAcceptance.setInitiator(initiator);
            offerAcceptance.setInitiated(initiated);
            offerAcceptance.setOfferId(co.getId());
            CargoDataManager.getInstance().initiateOfferAcceptance(initiator, initiated, co);
          }
        });

    return acceptOfferButton;
  }
Ejemplo n.º 14
0
  public void display() {
    final JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new GridBagLayout());

    // Setup resource
    ResourceUtils.resLabel(addressLabel, addressField, Res.getString("label.jabber.address") + ":");

    RolloverButton backButton = new RolloverButton();
    backButton.setIcon(SparkRes.getImageIcon(SparkRes.LEFT_ARROW_IMAGE));
    backButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            int selectedItem = addressField.getSelectedIndex();
            if (selectedItem > 0) {
              Object historyItem = addressField.getItemAt(selectedItem - 1);
              browse((String) historyItem);
            }
          }
        });

    mainPanel.add(
        backButton,
        new GridBagConstraints(
            0,
            0,
            1,
            1,
            0.0,
            0.0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(5, 5, 5, 5),
            0,
            0));
    mainPanel.add(
        addressLabel,
        new GridBagConstraints(
            1,
            0,
            1,
            1,
            0.0,
            0.0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(5, 5, 5, 5),
            0,
            0));
    mainPanel.add(
        addressField,
        new GridBagConstraints(
            2,
            0,
            1,
            1,
            1.0,
            0.0,
            GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL,
            new Insets(5, 5, 5, 5),
            0,
            0));

    JButton browseButton = new JButton("");
    ResourceUtils.resButton(browseButton, Res.getString("button.browse"));
    browseButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            String serviceName = (String) addressField.getSelectedItem();
            if (!ModelUtil.hasLength(serviceName)) {
              return;
            }
            browse(serviceName);
          }
        });
    mainPanel.add(
        addressField,
        new GridBagConstraints(
            2,
            0,
            1,
            1,
            1.0,
            0.0,
            GridBagConstraints.WEST,
            GridBagConstraints.HORIZONTAL,
            new Insets(5, 5, 5, 5),
            0,
            0));
    mainPanel.add(
        browseButton,
        new GridBagConstraints(
            3,
            0,
            1,
            1,
            0.0,
            0.0,
            GridBagConstraints.WEST,
            GridBagConstraints.NONE,
            new Insets(5, 5, 5, 5),
            0,
            0));

    browsePanel = new JPanel();
    browsePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
    browsePanel.setBackground(Color.white);

    JScrollPane pane =
        new JScrollPane(
            browsePanel,
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    browsePanel.setPreferredSize(new Dimension(0, 0));
    mainPanel.add(
        pane,
        new GridBagConstraints(
            0,
            1,
            4,
            1,
            1.0,
            1.0,
            GridBagConstraints.WEST,
            GridBagConstraints.BOTH,
            new Insets(5, 5, 5, 5),
            0,
            0));

    JFrame frame = new JFrame();
    frame.setIconImage(SparkRes.getImageIcon(SparkRes.FIND_IMAGE).getImage());

    JDialog dialog = new JDialog(frame, Res.getString("title.jabber.browser"));
    dialog.getContentPane().setLayout(new BorderLayout());
    dialog.getContentPane().add(mainPanel, BorderLayout.CENTER);
    dialog.pack();
    dialog.setSize(600, 400);
    dialog.setLocationRelativeTo(SparkManager.getMainWindow());
    dialog.setVisible(true);
  }
  public void initialize() {
    // Listen for right-clicks on ContactItem
    final ContactList contactList = SparkManager.getWorkspace().getContactList();

    final Action listenAction =
        new AbstractAction() {
          private static final long serialVersionUID = 7705539667621148816L;

          public void actionPerformed(ActionEvent e) {

            for (ContactItem item : contactList.getSelectedUsers()) {
              String bareAddress = StringUtils.parseBareAddress(item.getJID());
              sparkContacts.add(bareAddress);
            }
          }
        };

    listenAction.putValue(Action.NAME, Res.getString("menuitem.alert.when.online"));
    listenAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_ALARM_CLOCK));

    final Action removeAction =
        new AbstractAction() {
          private static final long serialVersionUID = -8726129089417116105L;

          public void actionPerformed(ActionEvent e) {

            for (ContactItem item : contactList.getSelectedUsers()) {
              String bareAddress = StringUtils.parseBareAddress(item.getJID());
              sparkContacts.remove(bareAddress);
            }
          }
        };

    removeAction.putValue(Action.NAME, Res.getString("menuitem.remove.alert.when.online"));
    removeAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.SMALL_DELETE));

    contactList.addContextMenuListener(
        new ContextMenuListener() {
          public void poppingUp(Object object, JPopupMenu popup) {
            if (object instanceof ContactItem) {
              ContactItem item = (ContactItem) object;
              String bareAddress = StringUtils.parseBareAddress(item.getJID());
              if (!item.getPresence().isAvailable() || item.getPresence().isAway()) {
                if (sparkContacts.contains(bareAddress)) {
                  popup.add(removeAction);
                } else {
                  popup.add(listenAction);
                }
              }
            }
          }

          public void poppingDown(JPopupMenu popup) {}

          public boolean handleDefaultAction(MouseEvent e) {
            return false;
          }
        });

    // Check presence changes
    SparkManager.getConnection()
        .addPacketListener(
            new PacketListener() {
              public void processPacket(final Packet packet) {
                try {
                  EventQueue.invokeAndWait(
                      new Runnable() {
                        public void run() {
                          Presence presence = (Presence) packet;
                          if (!presence.isAvailable() || presence.isAway()) {
                            return;
                          }
                          String from = presence.getFrom();

                          ArrayList<String> removelater = new ArrayList<String>();

                          for (final String jid : sparkContacts) {
                            if (jid.equals(StringUtils.parseBareAddress(from))) {
                              removelater.add(jid);
                              // sparkContacts.remove(jid);

                              String nickname =
                                  SparkManager.getUserManager().getUserNicknameFromJID(jid);
                              String time = SparkManager.DATE_SECOND_FORMATTER.format(new Date());
                              String infoText =
                                  Res.getString(
                                      "message.user.now.available.to.chat", nickname, time);

                              if (localPref.getShowToasterPopup()) {
                                SparkToaster toaster = new SparkToaster();
                                toaster.setDisplayTime(5000);
                                toaster.setBorder(BorderFactory.createBevelBorder(0));

                                toaster.setToasterHeight(150);
                                toaster.setToasterWidth(200);

                                toaster.setTitle(nickname);
                                toaster.showToaster(null, infoText);

                                toaster.setCustomAction(
                                    new AbstractAction() {
                                      private static final long serialVersionUID =
                                          4827542713848133369L;

                                      @Override
                                      public void actionPerformed(ActionEvent e) {
                                        SparkManager.getChatManager().getChatRoom(jid);
                                      }
                                    });
                              }

                              ChatRoom room = SparkManager.getChatManager().getChatRoom(jid);

                              if (localPref.getWindowTakesFocus()) {
                                SparkManager.getChatManager().activateChat(jid, nickname);
                              }

                              room.getTranscriptWindow()
                                  .insertNotificationMessage(
                                      infoText, ChatManager.NOTIFICATION_COLOR);
                            }
                          }
                          for (String s : removelater) {
                            sparkContacts.remove(s);
                          }
                        }
                      });
                } catch (Exception ex) {
                  ex.printStackTrace();
                }
              }
            },
            new PacketTypeFilter(Presence.class));
  }
Ejemplo n.º 16
0
  @Override
  public void initialize() {

    if (SystemTray.isSupported()) {

      JMenuItem openMenu = new JMenuItem(Res.getString("menuitem.open"));
      JMenuItem minimizeMenu = new JMenuItem(Res.getString("menuitem.hide"));
      JMenuItem exitMenu = new JMenuItem(Res.getString("menuitem.exit"));
      statusMenu = new JMenu(Res.getString("menuitem.status"));
      JMenuItem logoutMenu = new JMenuItem(Res.getString("menuitem.logout.no.status"));

      SystemTray tray = SystemTray.getSystemTray();
      SparkManager.getNativeManager().addNativeHandler(this);
      ChatManager.getInstance().addChatMessageHandler(chatMessageHandler);
      // XEP-0085 suport (replaces the obsolete XEP-0022)
      org.jivesoftware.smack.chat.ChatManager.getInstanceFor(SparkManager.getConnection())
          .addChatListener(this);

      if (Spark.isLinux()) {
        newMessageIcon = SparkRes.getImageIcon(SparkRes.MESSAGE_NEW_TRAY_LINUX);
        typingIcon = SparkRes.getImageIcon(SparkRes.TYPING_TRAY_LINUX);
      } else {
        newMessageIcon = SparkRes.getImageIcon(SparkRes.MESSAGE_NEW_TRAY);
        typingIcon = SparkRes.getImageIcon(SparkRes.TYPING_TRAY);
      }

      availableIcon = Default.getImageIcon(Default.TRAY_IMAGE);
      if (Spark.isLinux()) {
        if (availableIcon == null) {
          availableIcon = SparkRes.getImageIcon(SparkRes.TRAY_IMAGE_LINUX);
          Log.error(availableIcon.toString());
        }
        awayIcon = SparkRes.getImageIcon(SparkRes.TRAY_AWAY_LINUX);
        dndIcon = SparkRes.getImageIcon(SparkRes.TRAY_DND_LINUX);
        offlineIcon = SparkRes.getImageIcon(SparkRes.TRAY_OFFLINE_LINUX);
        connectingIcon = SparkRes.getImageIcon(SparkRes.TRAY_CONNECTING_LINUX);
      } else {
        if (availableIcon == null) {
          availableIcon = SparkRes.getImageIcon(SparkRes.TRAY_IMAGE);
        }
        awayIcon = SparkRes.getImageIcon(SparkRes.TRAY_AWAY);
        dndIcon = SparkRes.getImageIcon(SparkRes.TRAY_DND);
        offlineIcon = SparkRes.getImageIcon(SparkRes.TRAY_OFFLINE);
        connectingIcon = SparkRes.getImageIcon(SparkRes.TRAY_CONNECTING);
      }

      popupMenu.add(openMenu);
      openMenu.addActionListener(
          new AbstractAction() {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent event) {
              SparkManager.getMainWindow().setVisible(true);
              SparkManager.getMainWindow().toFront();
            }
          });
      popupMenu.add(minimizeMenu);
      minimizeMenu.addActionListener(
          new AbstractAction() {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent event) {
              SparkManager.getMainWindow().setVisible(false);
            }
          });
      popupMenu.addSeparator();
      addStatusMessages();
      popupMenu.add(statusMenu);
      statusMenu.addActionListener(
          new AbstractAction() {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent event) {}
          });

      if (Spark.isWindows()) {
        if (!Default.getBoolean("DISABLE_EXIT")) popupMenu.add(logoutMenu);

        logoutMenu.addActionListener(
            new AbstractAction() {
              private static final long serialVersionUID = 1L;

              @Override
              public void actionPerformed(ActionEvent e) {
                SparkManager.getMainWindow().logout(false);
              }
            });
      }
      // Exit Menu
      exitMenu.addActionListener(
          new AbstractAction() {
            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
              SparkManager.getMainWindow().shutdown();
            }
          });
      if (!Default.getBoolean("DISABLE_EXIT")) popupMenu.add(exitMenu);

      /** If connection closed set offline tray image */
      SparkManager.getConnection()
          .addConnectionListener(
              new ConnectionListener() {

                @Override
                public void connected(XMPPConnection xmppConnection) {
                  trayIcon.setImage(availableIcon.getImage());
                }

                @Override
                public void authenticated(XMPPConnection xmppConnection, boolean b) {
                  trayIcon.setImage(availableIcon.getImage());
                }

                @Override
                public void connectionClosed() {
                  trayIcon.setImage(offlineIcon.getImage());
                }

                @Override
                public void connectionClosedOnError(Exception arg0) {
                  trayIcon.setImage(offlineIcon.getImage());
                }

                @Override
                public void reconnectingIn(int arg0) {
                  trayIcon.setImage(connectingIcon.getImage());
                }

                @Override
                public void reconnectionSuccessful() {
                  trayIcon.setImage(availableIcon.getImage());
                }

                @Override
                public void reconnectionFailed(Exception arg0) {
                  trayIcon.setImage(offlineIcon.getImage());
                }
              });

      SparkManager.getSessionManager()
          .addPresenceListener(
              presence -> {
                if (presence.getMode() == Presence.Mode.available) {
                  trayIcon.setImage(availableIcon.getImage());
                } else if (presence.getMode() == Presence.Mode.away
                    || presence.getMode() == Presence.Mode.xa) {
                  trayIcon.setImage(awayIcon.getImage());
                } else if (presence.getMode() == Presence.Mode.dnd) {
                  trayIcon.setImage(dndIcon.getImage());
                } else {
                  trayIcon.setImage(availableIcon.getImage());
                }
              });

      try {

        trayIcon =
            new TrayIcon(
                availableIcon.getImage(), Default.getString(Default.APPLICATION_NAME), null);
        trayIcon.setImageAutoSize(true);

        trayIcon.addMouseListener(
            new MouseListener() {

              @Override
              public void mouseClicked(MouseEvent event) {
                // if we are using double click on tray icon
                if ((!pref.isUsingSingleTrayClick()
                        && event.getButton() == MouseEvent.BUTTON1
                        && event.getClickCount() % 2 == 0)
                    ||
                    // if we using single click on tray icon
                    (pref.isUsingSingleTrayClick()
                        && event.getButton() == MouseEvent.BUTTON1
                        && event.getClickCount() == 1)) {

                  // bring the mainwindow to front
                  if ((SparkManager.getMainWindow().isVisible())
                      && (SparkManager.getMainWindow().getState() == java.awt.Frame.NORMAL)) {
                    SparkManager.getMainWindow().setVisible(false);
                  } else {
                    SparkManager.getMainWindow().setVisible(true);
                    SparkManager.getMainWindow().setState(java.awt.Frame.NORMAL);
                    SparkManager.getMainWindow().toFront();
                  }

                } else if (event.getButton() == MouseEvent.BUTTON1) {
                  SparkManager.getMainWindow().toFront();
                  // SparkManager.getMainWindow().requestFocus();
                } else if (event.getButton() == MouseEvent.BUTTON3) {

                  if (popupMenu.isVisible()) {
                    popupMenu.setVisible(false);
                  } else {

                    double x = MouseInfo.getPointerInfo().getLocation().getX();
                    double y = MouseInfo.getPointerInfo().getLocation().getY();

                    if (Spark.isMac()) {
                      popupMenu.setLocation((int) x, (int) y);
                    } else {
                      popupMenu.setLocation(event.getX(), event.getY());
                    }

                    popupMenu.setInvoker(popupMenu);
                    popupMenu.setVisible(true);
                  }
                }
              }

              @Override
              public void mouseEntered(MouseEvent event) {}

              @Override
              public void mouseExited(MouseEvent event) {}

              @Override
              public void mousePressed(MouseEvent event) {

                // on Mac i would want the window to show when i left-click the Icon
                if (Spark.isMac() && event.getButton() != MouseEvent.BUTTON3) {
                  SparkManager.getMainWindow().setVisible(false);
                  SparkManager.getMainWindow().setVisible(true);
                  SparkManager.getMainWindow().requestFocusInWindow();
                  SparkManager.getMainWindow().bringFrameIntoFocus();
                  SparkManager.getMainWindow().toFront();
                  SparkManager.getMainWindow().requestFocus();
                }
              }

              @Override
              public void mouseReleased(MouseEvent event) {}
            });

        tray.add(trayIcon);
      } catch (Exception e) {
        // Not Supported
      }
    } else {
      Log.error("Tray don't supports on this platform.");
    }
  }
Ejemplo n.º 17
0
  /**
   * Updates the icon of the user based on their presence.
   *
   * @param presence the users presence.
   */
  public void updatePresenceIcon(Presence presence) {
    ChatManager chatManager = SparkManager.getChatManager();
    boolean handled = chatManager.fireContactItemPresenceChanged(this, presence);
    if (handled) {
      return;
    }

    String status = presence.getStatus();
    Icon statusIcon = SparkRes.getImageIcon(SparkRes.GREEN_BALL);
    boolean isAvailable = false;
    if (status == null && presence.isAvailable()) {
      Presence.Mode mode = presence.getMode();
      if (mode == Presence.Mode.available) {
        status = Res.getString("status.online");
        isAvailable = true;
      } else if (mode == Presence.Mode.away) {
        status = Res.getString("status.away");
        statusIcon = SparkRes.getImageIcon(SparkRes.IM_AWAY);
      } else if (mode == Presence.Mode.chat) {
        status = Res.getString("status.free.to.chat");
      } else if (mode == Presence.Mode.dnd) {
        status = Res.getString("status.do.not.disturb");
        statusIcon = SparkRes.getImageIcon(SparkRes.IM_AWAY);
      } else if (mode == Presence.Mode.xa) {
        status = Res.getString("status.extended.away");
        statusIcon = SparkRes.getImageIcon(SparkRes.IM_AWAY);
      }
    }

    if (presence.isAvailable()
        && (presence.getMode() == Presence.Mode.dnd
            || presence.getMode() == Presence.Mode.away
            || presence.getMode() == Presence.Mode.xa)) {
      statusIcon = SparkRes.getImageIcon(SparkRes.IM_AWAY);
    } else if (presence.isAvailable()) {
      isAvailable = true;
    } else if (!presence.isAvailable()) {
      getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, fontSize));
      getNicknameLabel().setForeground((Color) UIManager.get("ContactItemOffline.color"));

      RosterEntry entry = SparkManager.getConnection().getRoster().getEntry(getJID());
      if (entry != null
          && (entry.getType() == RosterPacket.ItemType.none
              || entry.getType() == RosterPacket.ItemType.from)
          && RosterPacket.ItemStatus.SUBSCRIPTION_PENDING == entry.getStatus()) {
        // Do not move out of group.
        setIcon(SparkRes.getImageIcon(SparkRes.SMALL_QUESTION));
        getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, fontSize));
        setStatusText(Res.getString("status.pending"));
      } else {
        // We should keep the offline bullet (not available) instead of putting icon null.
        setIcon(SparkRes.getImageIcon(SparkRes.CLEAR_BALL_ICON));
        setFont(new Font("Dialog", Font.PLAIN, fontSize));
        getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, fontSize));
        setAvailable(false);
        if (ModelUtil.hasLength(status)) {
          setStatusText(status);
        } else {
          setStatusText("");
        }
      }

      sideIcon.setIcon(null);
      setAvailable(false);
      return;
    }

    Icon sIcon = PresenceManager.getIconFromPresence(presence);
    if (sIcon != null) {
      setIcon(sIcon);
    } else {
      setIcon(statusIcon);
    }
    if (status != null) {
      setStatus(status);
    }

    if (PresenceManager.isOnPhone(presence)) {
      statusIcon = SparkRes.getImageIcon(SparkRes.ON_PHONE_IMAGE);
      setIcon(statusIcon);
    }

    // Always change nickname label to black.
    getNicknameLabel().setForeground((Color) UIManager.get("ContactItemNickname.foreground"));

    if (isAvailable) {
      getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, fontSize));
      if (Res.getString("status.online").equals(status)
          || Res.getString("available").equalsIgnoreCase(status)) {
        setStatusText("");
      } else {
        setStatusText(status);
      }
    } else if (presence.isAvailable()) {
      LocalPreferences pref = SettingsManager.getLocalPreferences();
      if (pref.isGrayingOutEnabled()) {
        getNicknameLabel().setFont(new Font("Dialog", Font.ITALIC, fontSize));
        getNicknameLabel().setForeground(Color.gray);
      } else {
        getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, fontSize));
        getNicknameLabel().setForeground(Color.black);
      }
      if (status != null) {
        setStatusText(status);
      }
    }

    setAvailable(true);
  }
Ejemplo n.º 18
0
 public Icon getInactiveIcon() {
   return SparkRes.getImageIcon(SparkRes.ICQ_TRANSPORT_INACTIVE_IMAGE);
 }