/** Loads Preferences, either from server or locally. */
 private void loadPreferences() {
   boolean serverPluginInstalled =
       SipAccountPacket.isSoftPhonePluginInstalled(SparkManager.getConnection());
   if (serverPluginInstalled) {
     setupRemotePreferences(SparkManager.getConnection());
   }
 }
示例#2
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);
      }
    }
  }
  @Override
  public void initialize() {

    ProviderManager.addIQProvider(
        GameOfferPacket.ELEMENT_NAME, GameOfferPacket.NAMESPACE, GameOfferPacket.class);
    ProviderManager.addExtensionProvider(
        MovePacket.ELEMENT_NAME, MovePacket.NAMESPACE, MovePacket.class);
    ProviderManager.addExtensionProvider(
        MoveAnswerPacket.ELEMENT_NAME, MoveAnswerPacket.NAMESPACE, MoveAnswerPacket.class);

    _gameofferListener =
        new StanzaListener() {

          @Override
          public void processPacket(Stanza stanza) {
            GameOfferPacket invitation = (GameOfferPacket) stanza;
            if (invitation.getType() == IQ.Type.get) {
              showInvitationInChat(invitation);
            }
          }
        };

    SparkManager.getConnection()
        .addAsyncStanzaListener(_gameofferListener, new StanzaTypeFilter(GameOfferPacket.class));

    _chatRoomListener = new ChatRoomOpeningListener();

    SparkManager.getChatManager().addChatRoomListener(_chatRoomListener);
  }
  public void initialize() {
    this.con = SparkManager.getConnection();
    EventQueue.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            addressLabel = new JLabel();
            addressField = new JComboBox();
            addressField.setEditable(true);
            addressField.addItem(con.getHost());
          }
        });
    SparkManager.getWorkspace()
        .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(KeyStroke.getKeyStroke("F8"), "showBrowser");
    SparkManager.getWorkspace()
        .getActionMap()
        .put(
            "showBrowser",
            new AbstractAction("showBrowser") {
              private static final long serialVersionUID = 341826581565007606L;

              public void actionPerformed(ActionEvent evt) {
                display();
              }
            });
  }
示例#5
0
  public void closeChatRoom() {
    // If already closed, don't bother.
    if (!active) {
      return;
    }

    super.closeChatRoom();

    // Remove info listener
    infoButton.removeActionListener(this);
    addToRosterButton.removeActionListener(this);

    // Send a cancel notification event on closing if listening.
    if (!sendNotification) {
      // send cancel
      SparkManager.getMessageEventManager()
          .sendCancelledNotification(getParticipantJID(), threadID);

      sendNotification = true;
    }

    SparkManager.getChatManager().removeChat(this);

    SparkManager.getConnection().removePacketListener(this);
    if (typingTimerTask != null) {
      TaskEngine.getInstance().cancelScheduledTask(typingTimerTask);
      typingTimerTask = null;
    }
    active = false;
  }
  /** Creating PrivacyListManager instance */
  private PrivacyManager() {
    XMPPConnection conn = SparkManager.getConnection();
    if (conn == null) {
      Log.error("Privacy plugin: Connection not initialized.");
    }

    _active = checkIfPrivacyIsSupported(conn);

    if (_active) {
      privacyManager = PrivacyListManager.getInstanceFor(conn);
      initializePrivacyLists();
    }
  }
示例#7
0
 /**
  * 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();
   }
 }
示例#8
0
  /**
   * 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);
  }
示例#9
0
 private void checkEvents(String from, String packetID, MessageEvent messageEvent) {
   if (messageEvent.isDelivered() || messageEvent.isDisplayed()) {
     // Create the message to send
     Message msg = new Message(from);
     // Create a MessageEvent Package and add it to the message
     MessageEvent event = new MessageEvent();
     if (messageEvent.isDelivered()) {
       event.setDelivered(true);
     }
     if (messageEvent.isDisplayed()) {
       event.setDisplayed(true);
     }
     event.setPacketID(packetID);
     msg.addExtension(event);
     // Send the packet
     SparkManager.getConnection().sendPacket(msg);
   }
 }
示例#10
0
  /**
   * Sends a broadcast message to all users selected.
   *
   * @param dlg
   */
  private boolean sendBroadcasts(JDialog dlg) {
    final Set<String> jids = new HashSet<String>();

    for (CheckNode node : nodes) {
      if (node.isSelected()) {
        String jid = (String) node.getAssociatedObject();
        jids.add(jid);
      }
    }

    if (jids.size() == 0) {
      JOptionPane.showMessageDialog(
          dlg,
          Res.getString("message.broadcast.no.user.selected"),
          Res.getString("title.error"),
          JOptionPane.ERROR_MESSAGE);
      return false;
    }

    String text = messageBox.getText();
    if (!ModelUtil.hasLength(text)) {
      JOptionPane.showMessageDialog(
          dlg,
          Res.getString("message.broadcast.no.text"),
          Res.getString("title.error"),
          JOptionPane.ERROR_MESSAGE);
      return false;
    }

    for (String jid : jids) {
      final Message message = new Message();
      message.setTo(jid);
      message.setBody(text);

      if (normalMessageButton.isSelected()) {
        message.setType(Message.Type.normal);
      } else {
        message.setType(Message.Type.headline);
      }
      SparkManager.getConnection().sendPacket(message);
    }

    return true;
  }
示例#11
0
  /**
   * Sends a message to the appropriate jid. The message is automatically added to the transcript.
   *
   * @param message the message to send.
   */
  public void sendMessage(Message message) {
    lastActivity = System.currentTimeMillis();

    try {
      getTranscriptWindow()
          .insertMessage(getNickname(), message, ChatManager.TO_COLOR, Color.white);
      getChatInputEditor().selectAll();

      getTranscriptWindow().validate();
      getTranscriptWindow().repaint();
      getChatInputEditor().clear();
    } catch (Exception ex) {
      Log.error("Error sending message", ex);
    }

    // Before sending message, let's add our full jid for full verification
    message.setType(Message.Type.chat);
    message.setTo(participantJID);
    message.setFrom(SparkManager.getSessionManager().getJID());

    // Notify users that message has been sent
    fireMessageSent(message);

    addToTranscript(message, false);

    getChatInputEditor().setCaretPosition(0);
    getChatInputEditor().requestFocusInWindow();
    scrollToBottom();

    // No need to request displayed or delivered as we aren't doing anything
    // with this
    // information.
    MessageEventManager.addNotificationsRequests(message, true, false, false, true);

    // Send the message that contains the notifications request
    try {
      fireOutgoingMessageSending(message);
      SparkManager.getConnection().sendPacket(message);
    } catch (Exception ex) {
      Log.error("Error sending message", ex);
    }
  }
示例#12
0
  /** Saves the VCard. */
  private void saveVCard() {
    final VCard vcard = new VCard();

    // Save personal info
    vcard.setFirstName(personalPanel.getFirstName());
    vcard.setLastName(personalPanel.getLastName());
    vcard.setMiddleName(personalPanel.getMiddleName());
    vcard.setEmailHome(personalPanel.getEmailAddress());
    vcard.setNickName(personalPanel.getNickname());

    // Save business info
    vcard.setOrganization(businessPanel.getCompany());
    vcard.setAddressFieldWork("STREET", businessPanel.getStreetAddress());
    vcard.setAddressFieldWork("LOCALITY", businessPanel.getCity());
    vcard.setAddressFieldWork("REGION", businessPanel.getState());
    vcard.setAddressFieldWork("PCODE", businessPanel.getZipCode());
    vcard.setAddressFieldWork("CTRY", businessPanel.getCountry());
    vcard.setField("TITLE", businessPanel.getJobTitle());
    vcard.setOrganizationUnit(businessPanel.getDepartment());
    vcard.setPhoneWork("VOICE", businessPanel.getPhone());
    vcard.setPhoneWork("FAX", businessPanel.getFax());
    vcard.setPhoneWork("PAGER", businessPanel.getPager());
    vcard.setPhoneWork("CELL", businessPanel.getMobile());
    vcard.setField("URL", businessPanel.getWebPage());

    // Save Home Info
    vcard.setAddressFieldHome("STREET", homePanel.getStreetAddress());
    vcard.setAddressFieldHome("LOCALITY", homePanel.getCity());
    vcard.setAddressFieldHome("REGION", homePanel.getState());
    vcard.setAddressFieldHome("PCODE", homePanel.getZipCode());
    vcard.setAddressFieldHome("CTRY", homePanel.getCountry());
    vcard.setPhoneHome("VOICE", homePanel.getPhone());
    vcard.setPhoneHome("FAX", homePanel.getFax());
    vcard.setPhoneHome("PAGER", homePanel.getPager());
    vcard.setPhoneHome("CELL", homePanel.getMobile());

    // Save Avatar
    final File avatarFile = avatarPanel.getAvatarFile();
    byte[] avatarBytes = avatarPanel.getAvatarBytes();

    if (avatarFile != null) {
      try {
        // Make it 48x48
        ImageIcon icon = new ImageIcon(avatarFile.toURI().toURL());
        Image image = icon.getImage();
        image = image.getScaledInstance(-1, 48, Image.SCALE_SMOOTH);
        avatarBytes = GraphicUtils.getBytesFromImage(image);
      } catch (MalformedURLException e) {
        Log.error("Unable to set avatar.", e);
      }
    }

    // If avatar bytes, persist as vcard.
    if (avatarBytes != null) {
      vcard.setAvatar(avatarBytes);
    }

    try {
      final VCardManager vcardManager = SparkManager.getVCardManager();
      vcardManager.setPersonalVCard(vcard);

      vcard.save(SparkManager.getConnection());

      // Notify users.
      if (avatarFile != null || avatarBytes != null) {
        Presence presence = SparkManager.getWorkspace().getStatusBar().getPresence();
        Presence newPresence =
            new Presence(
                presence.getType(),
                presence.getStatus(),
                presence.getPriority(),
                presence.getMode());

        // Change my own presence
        SparkManager.getSessionManager().changePresence(newPresence);

        // Chnage avatar in status bar.
        StatusBar statusBar = SparkManager.getWorkspace().getStatusBar();
        statusBar.setAvatar(new ImageIcon(vcard.getAvatar()));
      } else {
        String firstName = vcard.getFirstName();
        String lastName = vcard.getLastName();
        StatusBar statusBar = SparkManager.getWorkspace().getStatusBar();
        if (ModelUtil.hasLength(firstName) && ModelUtil.hasLength(lastName)) {
          statusBar.setNickname(firstName + " " + lastName);
        } else if (ModelUtil.hasLength(firstName)) {
          statusBar.setNickname(firstName);
        }

        statusBar.setAvatar(null);
      }

      // Notify listenres
      SparkManager.getVCardManager().notifyVCardListeners();
    } catch (XMPPException e) {
      Log.error(e);
      JOptionPane.showMessageDialog(
          SparkManager.getMainWindow(),
          Res.getString("message.vcard.not.supported"),
          Res.getString("title.error"),
          JOptionPane.ERROR_MESSAGE);
    }
  }
  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));
  }
示例#14
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.");
    }
  }
示例#15
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);
  }
示例#16
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";
          }
        });
  }