Package net.sphene.goim.rcp.ui

Source Code of net.sphene.goim.rcp.ui.MUCBrowserGUI

/*
* File    : MUCBrowserGUI.java
* Created : 22.01.2006
* By      : kahless
*
* GOIM - Gamers Own Instant Messenger
* Copyright (C) 2005-2006 Herbert Poul
*              (JabberId: kahless@sphene.net / Email: herbert.poul@gmail.com)
* http://goim.sphene.net
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package net.sphene.goim.rcp.ui;

import java.util.Iterator;

import net.sphene.goim.rcp.beans.GOIMAccount;
import net.sphene.goim.rcp.xmpp.StatusChangedEvent;
import net.sphene.goim.rcp.xmpp.util.JabberErrorConditionMapping;
import net.sphene.goim.rcp.xmpp.util.MUCUtils;
import net.sphene.libs.SpheneListener;

import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.ParticipantStatusListener;
import org.jivesoftware.smackx.muc.RoomInfo;
import org.jivesoftware.smackx.muc.SubjectUpdatedListener;
import org.jivesoftware.smackx.packet.MUCUser;
import org.jivesoftware.smackx.packet.MUCUser.Item;

public class MUCBrowserGUI extends ChatBrowserGUI {
  private MultiUserChat muc;

  private SashForm rootSashForm;
  private Tree userList;
  private TreeItem moderators;
  private TreeItem participants;
  private TreeItem visitors;

  private ConnectionListener mucConnectionListener;
  private PacketListener participantListener;
  private PacketListener mucMessageListener;
  private ParticipantStatusListener participantStatusListener;

  private SubjectUpdatedListener mucSubjectUpdateListener;

  private Text txtTopic;



  public MUCBrowserGUI(Composite parent, int style) {
    super(parent, style);
    this.addDisposeListener(new DisposeListener() {
      public void widgetDisposed(DisposeEvent e) {
        System.out.println("Leaving room.");
        muc.leave();
      }
    });
  }


  public MultiUserChat getMUC() {
    return muc;
  }
 
 
  /**
   *
   */
  public void init(GOIMAccount account, MultiUserChat muC) {
    this.account = account;
    this.muc = muC;
   
    toolItemHistory.setEnabled(false);
    toolItemVCard.setEnabled(false);
    statusLabel.setVisible(false);
    userList.setVisible(true);
   
   
    chatParticipantStatus.setLayout(new GridLayout(3,false));
   
    Button mucOptions = new Button(chatParticipantStatus,SWT.PUSH);
    mucOptions.setText("Options");
   
    Label lblTopic = new Label(chatParticipantStatus,SWT.NULL);
    lblTopic.setText("Topic:");
   
    txtTopic = new Text(chatParticipantStatus,SWT.READ_ONLY|SWT.BORDER);
    txtTopic.setLayoutData(new GridData(SWT.FILL,SWT.CENTER,true,false));
   
    mucOptions.addListener(SWT.MouseDown,new Listener() {
      private Menu mucOptionsMenu;

      public void handleEvent(Event event) {
        if(mucOptionsMenu == null) {
          mucOptionsMenu = new Menu(txtTopic.getShell(),SWT.POP_UP);
         
          MenuItem changeTopic = new MenuItem(mucOptionsMenu,SWT.PUSH);
          changeTopic.setText("Change Subject");
         
          MenuItem invite = new MenuItem(mucOptionsMenu,SWT.PUSH);
          invite.setText("Invite someone to this Room");
         
          final MenuItem autoJoin = new MenuItem(mucOptionsMenu,SWT.CHECK);
          autoJoin.setText("Automatically join this channel on each connect");
         
          autoJoin.setSelection(MUCUtils.isOnAutoJoinList(MUCBrowserGUI.this.account,muc.getRoom()));
         
          changeTopic.addListener(SWT.Selection,new Listener() {
            public void handleEvent(Event event) {
              InputDialog inputDialog = new InputDialog(txtTopic.getShell(),
                  "Change Subject",
                  "Enter a new Subject for the room " + muc.getRoom(),
                  txtTopic.getText(),
                  null);
              int r = inputDialog.open();
              if(r != InputDialog.OK) return;
              try {
                muc.changeSubject(inputDialog.getValue());
              } catch (XMPPException e) {
                e.printStackTrace();
                String msg = e.getMessage();
                if(e.getXMPPError() != null) {
                  msg = JabberErrorConditionMapping.getMeaning(e.getXMPPError().getCode());
                  if(e.getXMPPError().getMessage() != null)
                    msg = msg + " - " + e.getXMPPError().getMessage();
                }
                throw new RuntimeException(msg,e);
              }
            }
          });
          invite.addListener(SWT.Selection,new Listener() {
            public void handleEvent(Event event) {
              InputDialog inputDialog = new InputDialog(txtTopic.getShell(),
                  "Invite Someone",
                  "Enter JID of whom you want to invite to this Room (Afterwards you can enter an invite message)",
                  "",
                  null);
              int r = inputDialog.open();
              if(r != InputDialog.OK) return;
              String jid = inputDialog.getValue();
              inputDialog = new InputDialog(txtTopic.getShell(),
                  "Invite Someone",
                  "Enter Invite Message (Reason for the invitation)",
                  "Join me on " + muc.getRoom(),
                  null);
              r = inputDialog.open();
              if(r != InputDialog.OK) return;
              String reason = inputDialog.getValue();
              muc.invite(jid,reason);
            }
          });
          autoJoin.addListener(SWT.Selection,new Listener() {
            public void handleEvent(Event event) {
              if(!autoJoin.getSelection()) {
                //autoJoin.setSelection(false);
                MUCUtils.removeFromAutoJoinList(MUCBrowserGUI.this.account,muc.getRoom());
              } else {
                //autoJoin.setSelection(true);
                MUCUtils.addToAutoJoinList(MUCBrowserGUI.this.account,muc.getRoom());
              }
            }
          });
        }
        mucOptionsMenu.setVisible(true);
      }
    });
   
    mucSubjectUpdateListener = new SubjectUpdatedListener() {
      public void subjectUpdated(final String subject, final String from) {
        txtTopic.getDisplay().asyncExec(new Runnable() { public void run() {
          txtTopic.setText(subject);
          appendToChatHistory(from,"changed subject to: " + subject,false,"","* ");
        }});
      }
    };
    //muc.addSubjectUpdatedListener(mucSubjectUpdateListener);
    try {
      RoomInfo roomInfo = MultiUserChat.getRoomInfo(account.xmpp.getConnection(),muc.getRoom());
      if(roomInfo.getSubject() != null && txtTopic.getText().equals(""))
        txtTopic.setText(roomInfo.getSubject());
    } catch (XMPPException e) {
      e.printStackTrace();
    }
   
    mucMessageListener = new PacketListener() {
      public void processPacket(Packet packet) {
        //processMessage((Message) packet);
      }
    };
    muc.addMessageListener(mucMessageListener);
    participantListener = new PacketListener() {
      public void processPacket(Packet packet) {
      }
    };
    muc.addParticipantListener(participantListener);
    participantStatusListener = new ParticipantStatusListener() {
      public void joined(String participant) {
        asyncAppendToChatHistory(participant, "Joined Room.", false,
            null, "--- ");
        addUser(participant);
      }

      public void left(String participant) {
        if (sashForm != null && !sashForm.isDisposed()) {
          asyncAppendToChatHistory(participant, "Left Room.", false,
              null, "--- ");
          removeUser(participant);
        }
      }

      public void kicked(String participant, String actor, String reason) {
        asyncAppendToChatHistory(participant, "was kicked by " + actor + ": " + reason, false,
            null, "--- ");
        left(participant);
      }

      public void banned(String participant,String actor, String reason) {
        asyncAppendToChatHistory(participant, "was banned by " + actor + ": "+ reason, false,
            null, "--- ");
        left(participant);
      }

      public void voiceGranted(String participant) {
        asyncAppendToChatHistory(participant, "was granted voice.",
            false, null, "--- ");
        giveVoice(participant, true);
      }

      public void voiceRevoked(String participant) {
        asyncAppendToChatHistory(participant, "was removed voice.",
            false, null, "--- ");
        giveVoice(participant, false);
      }

      public void membershipGranted(String participant) {
        asyncAppendToChatHistory(participant, "was granted membership",
            false, null, "--- ");
        makeMember(participant, true);
      }

      public void membershipRevoked(String participant) {
        asyncAppendToChatHistory(participant, "was revoked membership",
            false, null, "--- ");
        makeMember(participant, false);
      }

      public void moderatorGranted(String participant) {
        asyncAppendToChatHistory(participant,
            "was granted moderator access", false, null, "--- ");
        makeMod(participant, true);

      }

      public void moderatorRevoked(String participant) {
        asyncAppendToChatHistory(participant,
            "was revoked moderator access", false, null, "--- ");
        makeMod(participant, false);
      }

      public void ownershipGranted(String participant) {
        asyncAppendToChatHistory(participant, "was granted ownership",
            false, null, "--- ");
        makeOwner(participant, true);
      }

      public void ownershipRevoked(String participant) {
        asyncAppendToChatHistory(participant, "was revoked ownership",
            false, null, "--- ");
        makeOwner(participant, false);
      }

      public void adminGranted(String participant) {
        asyncAppendToChatHistory(participant,
            "was granted admin access", false, null, "--- ");
        makeAdmin(participant, true);
      }

      public void adminRevoked(String participant) {
        asyncAppendToChatHistory(participant,
            "was revoked admin access", false, null, "--- ");
        makeAdmin(participant, false);
      }

      public void nicknameChanged(String nickname, String newNickname) {
        asyncAppendToChatHistory(nickname, " changed his nickname to " + newNickname,
            false, null, "--- ");

      }
    };
    muc.addParticipantStatusListener(participantStatusListener);
    addListener(SWT.Dispose, new Listener(){
      public void handleEvent(Event event) {
        muc.removeMessageListener(mucMessageListener);
        muc.removeParticipantListener(participantListener);
        muc.removeParticipantStatusListener(participantStatusListener);
        muc.removeSubjectUpdatedListener(mucSubjectUpdateListener);
      }});
    initMUCOccupantList();
    generalInit();
    //while (pollMUC())
    //  ;
  }
 
  protected void generalInit() {
    super.generalInit();
    final SpheneListener<StatusChangedEvent> ownPresenceChangeListener = new SpheneListener<StatusChangedEvent>() {
      public void handleEvent(StatusChangedEvent event) {
        if(event.previousPresence == null) {
          // we need to recover the chat session ...
          account.xmpp.getConnection().addConnectionListener(mucConnectionListener);
          if(muc != null) {
            String nickname = muc.getNickname();
            muc = new MultiUserChat(account.xmpp.getConnection(),muc.getRoom());
            try {
              muc.join(nickname);
            } catch (XMPPException e) {
              e.printStackTrace();
              throw new RuntimeException(e);
            }
            try {
              Thread.sleep(500);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            muc.addMessageListener(mucMessageListener);
            muc.addParticipantListener(participantListener);
            muc.addParticipantStatusListener(participantStatusListener);
            initMUCOccupantList();
          }
        }
        asyncAppendToChatHistory(account.jid,"- You changed your status to " + GOIMIcons.getShowTextForPresence(account.xmpp.getOwnPresence()),false,"","* ");
      } };
    mucConnectionListener = new ConnectionListener() {
      public void connectionClosed() {
        getDisplay().asyncExec(new Runnable() { public void run() {
          getModeratorsItem().removeAll();
          getParticipantsItem().removeAll();
          getVisitorsItem().removeAll();
          appendToChatHistory(account.jid," - You disconnected from the Jabber Server",false,"","* "); // - You will need to reopen this Window when reconnecting.",false,"","* ");
        }});
      }
      public void connectionClosedOnError(Exception e) {
        connectionClosed();
      }
    };
    account.xmpp.getConnection().addConnectionListener(connectionListener);
    addListener(SWT.Dispose, new Listener() {
      public void handleEvent(Event event) {
        if(account != null && account.xmpp != null) {
          if(account.xmpp.getConnection() != null) {
            account.xmpp.getConnection().removeConnectionListener(connectionListener);
          }
          account.xmpp.ownPresenceChanged.removeListener(ownPresenceChangeListener);
        }
      }
    });

  }
 
  protected void initMUCOccupantList() {
    Iterator occupants = muc.getOccupants();
    while (occupants.hasNext()) {
      addUser((String) occupants.next());
    }
  }
  /**
   * Removes a user from the userlist.
   *
   * @param participant
   *            The name of the user to be removed
   *           
   * @deprecated use getTreeItem() instead
   */
  private void removeUser(final String occupant) {
    userList.getDisplay().asyncExec(new Runnable() {
      public void run() {

        System.out.println("occupant: " + occupant);
        String nick = StringUtils.parseResource(occupant);

        // check if user is in moderators group
        TreeItem t = getModeratorsItem();
        if (removeUser(nick, t)) {
          return;
        }

        // check if user is in participants group
        t = getParticipantsItem();
        if (removeUser(nick, t)) {
          return;
        }

        // check if user is in visitors group
        t = getVisitorsItem();
        if (removeUser(nick, t)) {
          return;
        }
      };
    });

  }

  /**
   * Remove a user from a certain subtree (moderators/participants/visitors)
   *
   * @param occupant
   *            The user to remove
   * @param t
   *            The subtree it should be in
   * @return true if removed false otherwise
   *
   * @deprecated use checkSubTree() instead
   */
  private boolean removeUser(String occupant, TreeItem t) {

    if (t != null && t.getItemCount() > 0) {
      TreeItem[] children = t.getItems();
      for (int i = 0; i < children.length; i++) {
        if (children[i].getText().equals(occupant)) {
          System.out.println("User removed from "
              + children[i].getParentItem().getText() + "group.");
          children[i].dispose();
          return true;
        }
      }
    }
    return false;
  }

  /**
   * Adds a user to the userlist.
   *
   * @param occupant
   *            The user to add
   */
  private void addUser(final String occupant) {
    userList.getDisplay().asyncExec(new Runnable() {

      public void run() {
        Presence presence = getPresence(occupant);
        MUCUser mucUser = (MUCUser) presence.getExtension("x",
            "http://jabber.org/protocol/muc#user");
        MUCUser.Item item = mucUser.getItem();
        final String nick = StringUtils.parseResource(presence.getFrom());
        String role = item.getRole();
        TreeItem occupantItem;
        //Do this here so the suubtrees are in the right order
        getModeratorsItem();
        getParticipantsItem();
        getVisitorsItem();

        if (role.equals("moderator")) {
          TreeItem mod = getModeratorsItem();
          occupantItem = new TreeItem(mod, SWT.NONE);
          setTItemColor(item, occupantItem);
        } else if (role.equals("participant")) {
          TreeItem par = getParticipantsItem();
          occupantItem = new TreeItem(par, SWT.NONE);
          setTItemColor(item, occupantItem);
        } else if (role.equals("visitor")) {
          TreeItem vis = getVisitorsItem();
          occupantItem = new TreeItem(vis, SWT.NONE);
          setTItemColor(item, occupantItem);
        } else {
          throw new RuntimeException("No role ?! " + occupant
              + " .. " + role);
        }
        occupantItem.setData("user",nick);
        occupantItem.setText(nick);
        occupantItem.setImage(GOIMIcons.getImageForPresence(null,
            presence));
        //set selectedUser to nick
        Listener listener = null;
        occupantItem.addListener( SWT.BUTTON2, listener = new Listener() {
          public void handleEvent(Event event) {
            System.out.println("Setting selectedUser to " + nick);
            selectedUser = nick;
          }
        });
        occupantItem.addListener( SWT.Selection, listener);
        occupantItem.getParentItem().setExpanded(true);
      }
    });
  }

  /**
   * Color changing according to affiliation
   *
   * @param item
   * @param occupantItem
   */
  private void setTItemColor(Item item, TreeItem occupantItem) {
    if (item.getAffiliation().equals("owner"))
      occupantItem.setForeground(new Color(getDisplay(), 255, 0,
          0));
    // red for owners
    if (item.getAffiliation().equals("admin"))
      occupantItem.setForeground(new Color(getDisplay(), 0, 255,
          0));
    // green for admins
    if (item.getAffiliation().equals("member"))
      occupantItem.setForeground(new Color(getDisplay(), 0, 0,
          255));
    // blue for members
    if (item.getAffiliation().equals("none"))
      occupantItem.setForeground(new Color(getDisplay(), 255, 0,
          255));
    // purple for testing purposes, think should leave black?
   
    // outcast should never occur
  }
 
  /**
   * Get the moderators subtree
   *
   * @return the moderators subtree
   */
  private TreeItem getModeratorsItem() {
    if (moderators != null)
      return moderators;
    moderators = new TreeItem(userList, SWT.NONE);
    moderators.setText("Moderators");
    return moderators;
  }

  /**
   * Get the participants subtree
   *
   * @return the participants subtree
   */
  private TreeItem getParticipantsItem() {
    if (participants != null)
      return participants;
    participants = new TreeItem(userList, SWT.NONE);
    participants.setText("Participants");
    return participants;
  }

  /**
   * Get the visitors subtree
   *
   * @return the visitors subtree
   */
  private TreeItem getVisitorsItem() {
    if (visitors != null)
      return visitors;
    visitors = new TreeItem(userList, SWT.NONE);
    visitors.setText("Visitors");
    return visitors;
  }

  /**
   * Get the MUCUser.Item pertaining to an occupant
   *
   * @param occupant
   * @return
   */
  private MUCUser.Item getMUCItem(String occupant) {
    MUCUser mucUser = (MUCUser) getPresence(occupant)
      .getExtension("x", "http://jabber.org/protocol/muc#user");
    return mucUser.getItem();
  }
 
  /**
   * Get the Presence of an occupant
   *
   * @param occupant
   * @return
   */
  private Presence getPresence(String occupant) {
    return muc.getOccupantPresence(occupant);
  }
 
  /**
   * Checks the entire tree for TreeItems matching occupant
   * @param occupant
   * @param remove
   * @return null if not found
   */
  private TreeItem getTreeItem(String occupant, boolean remove) {
   
    final String nick = StringUtils.parseResource(getPresence(occupant).getFrom());
   
    TreeItem t = checkSubTree(nick, getParticipantsItem(), remove);
    if ( t != null )
      return t;
   
    t = checkSubTree(nick, getModeratorsItem(), remove);
    if ( t != null )
      return t;
   
    t = checkSubTree(nick, getVisitorsItem(), remove);
    if ( t != null )
      return t;
   
    return null;
   
   
  }
 
  /**
   * Checks the given subtree t for child TreeItems with name nick,
   * removes from t if remove == true
   *
   * @param t
   * @param nick
   * @param remove
   * @return null if not found
   */
  private TreeItem checkSubTree (String nick, TreeItem t, boolean remove) {
    if (t.getItemCount() > 0) {
      TreeItem[] treeItems = t.getItems();
      for (int i = 0; i < treeItems.length; i++) {
        if (treeItems[i].getText().equals(nick)) {
          TreeItem result = treeItems[i];
          if (remove)
            treeItems[i].dispose();
          return result;
        }
      }
    }
    return null;
  }
 
  /**
   * ?
   *
   * @return
   */
  protected boolean pollMUC() {
    if (muc == null)
      return false;
    Message msg = muc.pollMessage();
    if (msg == null)
      return false;
    processMessage(msg, false);
    return true;
  }


  public boolean isMe(String jid) {
    return jid.equals(muc.getNickname());
  }

 
  protected void initialize() {
    System.out.println("MUCBrowserGUI initialize ...");
    this.setLayout(new FillLayout());
    rootSashForm = new SashForm(this, SWT.HORIZONTAL);
    rootSashForm.setLayout(new FillLayout());
    rootSashForm.addListener(SWT.FocusIn, focusInListener);
    createChatGUI(rootSashForm);
    createUserList();
    rootSashForm.setWeights(new int[] { 75, 25 });
    //this.getParent().layout(true);
    setSize(new Point(600, 200));
    this.layout(true);
  }

  protected void createUserList() {
    userList = new Tree(rootSashForm, SWT.BORDER);
    userList.addListener(SWT.MouseDown, new Listener() {
      public void handleEvent(Event event) {
        TreeItem item = userList.getItem(new Point(event.x,event.y));
        if(item == null) return;
        userList.setSelection(new TreeItem[]{item});
        String user = (String)item.getData("user");
        selectedUser = user;
      }
    });
    userList.addListener(SWT.FocusIn, focusInListener);
    createUserListContextMenu();
  }
  protected void createUserListContextMenu() {
    // add the right click menu
    Menu contextMenu = new Menu(userList);
    userList.setMenu(contextMenu);

    MenuItem chatWith = new MenuItem(contextMenu, SWT.PUSH);
    chatWith.setText("Chat With..");
    chatWith.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        System.out.println("Open chat with: " + selectedUser);
        account.chatWindowExtensionManager.openChatWindow(selectedUser,false);
      }
    });

    MenuItem viewCard = new MenuItem(contextMenu, SWT.PUSH);
    viewCard.setText("View VCard");
    viewCard.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        new vCardGUI(account, muc.getRoom() + "/" + selectedUser);
      }
    });

    MenuItem mucItem = new MenuItem(contextMenu, SWT.CASCADE);
    mucItem.setText("MUC");
    Menu mucMenu = new Menu(mucItem);
    mucItem.setMenu(mucMenu);

    MenuItem kick = new MenuItem(mucMenu, SWT.PUSH);
    kick.setText("Kick");
    kick.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        // TODO finish this
        try {
          muc.kickParticipant(selectedUser, "");
        } catch (XMPPException e) {
         
        }
      }
    });

    MenuItem ban = new MenuItem(mucMenu, SWT.PUSH);
    ban.setText("Ban");
    ban.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        // TODO finish this

      }
    });

    MenuItem grantVoice = new MenuItem(mucMenu, SWT.PUSH);
    grantVoice.setText("Grant Voice");
    grantVoice.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        // TODO finish this

      }
    });

    MenuItem revokeVoice = new MenuItem(mucMenu, SWT.PUSH);
    revokeVoice.setText("Revoke Voice");

    MenuItem grantMembership = new MenuItem(mucMenu, SWT.PUSH);
    grantMembership.setText("Grant Membership");
    MenuItem revokeMembership = new MenuItem(mucMenu, SWT.PUSH);
    revokeMembership.setText("Revoke Membership");

    MenuItem grantMod = new MenuItem(mucMenu, SWT.PUSH);
    grantMod.setText("Grant Mod");
    grantMod.addListener(SWT.PUSH, new Listener() {
      public void handleEvent(Event event) {
        makeMod(selectedUser, true);
      }
    });
    MenuItem revokeMod = new MenuItem(mucMenu, SWT.PUSH);
    revokeMod.setText("Revoke Mod");
    revokeMod.addListener(SWT.PUSH, new Listener() {
      public void handleEvent(Event event) {
        makeMod(selectedUser, false);
      }
    });

    MenuItem grantAdmin = new MenuItem(mucMenu, SWT.PUSH);
    grantAdmin.setText("Grant Admin");
    grantAdmin.addListener(SWT.PUSH, new Listener() {
      public void handleEvent(Event event) {
        makeAdmin(selectedUser, true);
      }
    });
    MenuItem revokeAdmin = new MenuItem(mucMenu, SWT.PUSH);
    revokeAdmin.setText("Revoke Admin");
    revokeAdmin.addListener(SWT.PUSH, new Listener() {
      public void handleEvent(Event event) {
        makeAdmin(selectedUser, false);
      }
    });
  }
 
 
 
 
 
 
  protected Message createMessage() {
    if(muc == null) return null;
    return muc.createMessage();
  }
  protected void sendMessage(Message msg) throws XMPPException {
    if(muc != null)
      muc.sendMessage(msg);
  }

  ///////////////////////////
  /// MUC methods         ///
  ///////////////////////////
 
  /**
   * Make an occupant voiced or non-voiced
   *
   * @param occupant
   *            The occupant to make changes to
   * @param b
   *            true to make the occupant voiced false to make the occupant
   *            non-voiced
   */
  private void giveVoice(String occupant, boolean b) {
    // TODO Auto-generated method stub
    //MUST be a moderator to do this
    // differentiate between voiced and non-voiced users somehow?

  }

  /**
   * Make an occupant a member or a non-member
   *
   * @param occupant
   *            The occupant to make changes to
   * @param b
   *            true to make the occupant a member false to make the occupant
   *            a non-member
   */
  private void makeMember(String occupant, boolean b) {
    // TODO test
    /*
    if (!b) {
      if (removeUser(occupant, getParticipantsItem()))
        addUser(occupant);
      else
        System.out.println("User " + occupant + " is not already a member.");
    } else {
      if (removeUser(occupant, getVisitorsItem()))
        addUser(occupant);
      else
        System.out.println("User " + occupant + " is already a member.");     
    }
    */
    setTItemColor(getMUCItem(occupant), getTreeItem(occupant, false));
   
  }

  /**
   * Make an occupant an owner or a non-owner
   *
   * @param occupant
   *            The occupant to make changes to
   * @param b
   *            true to make the occupant an owner false to make the occupant
   *            a non-owner
   */
  private void makeOwner(String occupant, boolean b) {
    // TODO finish
    // MUST be an owner to do this
    TreeItem t = getTreeItem(occupant, true);
    if (t == null) {
      System.out.println("user " + occupant + " not in list!?");
    } else {
      addUser(occupant);
    }
   
   
   
  }

  /**
   * Make an occupant an admin or a non-admin
   *
   * @param occupant
   *            The occupant to make changes to
   * @param b
   *            true to make the occupant an admin false to make the occupant
   *            a non-admin
   */
  private void makeAdmin(String occupant, boolean b) {
    // TODO finish
    //MUST be an owner to do this
    setTItemColor(getMUCItem(occupant), getTreeItem(occupant, false));
  }

  /**
   * Moves a room occupant into or out of the moderator subtree
   *
   * @param participant
   *            The occupant to move
   * @param b
   *            true to move into false to move out of
   */
  private void makeMod(final String occupant, final boolean b) {

    // TODO fix this
    //MUST be an owner or admin to do this
    // manually move the MUCUser.Item to another tree?

    userList.getDisplay().asyncExec(new Runnable() {
      public void run() {

        if (!b) {
          if ( checkSubTree(occupant, getModeratorsItem(), true) != null )
            addUser(occupant);
          else {
            System.out.println("" + occupant
                + " is not a moderator.");
          }
        } else {
          if ( checkSubTree(occupant, getParticipantsItem(), true) != null
              || checkSubTree(occupant, getVisitorsItem(), true) != null)
            addUser(occupant);
          else
            System.out.println("" + occupant
                + " is already a moderator"
                + " or is not in the room.");
        }
      }
    });
  }

  public String getJID() {
    return muc.getRoom();
  }


  @Override
  public void processMessage(final Message message, boolean alreadyHandled) {
    // Overloaded to fix bug
     if(message.getSubject() != null) {
       txtTopic.getDisplay().asyncExec( new Runnable() { public void run() { txtTopic.setText(message.getSubject() ); } } );
     }
    super.processMessage(message, alreadyHandled);
  }
}
TOP

Related Classes of net.sphene.goim.rcp.ui.MUCBrowserGUI

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.