Package net.sphene.goim.rcp.ui

Source Code of net.sphene.goim.rcp.ui.ServiceDiscoveryUI$FormAnswerDialog

/*
* File    : ServiceDiscoveryUI.java
* Created : 06.08.2005
* By      : kahless
*
* Gamer's Own Instant Messenger
* Copyright (C) 2005 Herbert Poul (kahless@sphene.net)
* 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.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.sphene.goim.rcp.GOIMPlugin;
import net.sphene.goim.rcp.beans.GOIMAccount;
import net.sphene.goim.rcp.xmpp.BrowseIQ;
import net.sphene.goim.rcp.xmpp.GOIMPacketListener;
import net.sphene.goim.rcp.xmpp.Task;
import net.sphene.goim.rcp.xmpp.TaskObserver;
import net.sphene.goim.rcp.xmpp.BrowseIQ.BrowseIQProvider;
import net.sphene.goim.rcp.xmpp.TaskObserver.TaskObserverEvent;
import net.sphene.libs.SpheneListener;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
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.Control;
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.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.packet.DiscoverInfo;
import org.jivesoftware.smackx.packet.DiscoverItems;
import org.jivesoftware.smackx.packet.DiscoverInfo.Identity;

public class ServiceDiscoveryUI {

  private Shell sShell = null; // @jve:decl-index=0:visual-constraint="10,10"
  private Composite compositeChooseAddress = null;
  private Label lblAddress = null;
  private Text address = null;
  private Button buttonDiscover = null;
  private Tree discovered = null;
  private Composite compositeButtons = null;
  private Label status = null;
  private Button buttonClose = null;
  private GOIMAccount account;
  Menu contextMenu;
  MenuItem registerItem;
  private TreeItem selectedItem;
 
  private TaskObserver taskObserver;
  private MenuItem multiUserChat;
  private MenuItem multiUserChatListRooms;
  private MenuItem multiUserChatCreateRoom;
  private MenuItem multiUserChatJoinRoom;
  private MenuItem searchItem;
  private MenuItem vCardItem;

  private ServiceDiscoveryUI() {
  }

  public ServiceDiscoveryUI(GOIMAccount account, String addressid) {
    this.account = account;
    createSShell();
    createMenu();
    openAndDiscover(addressid);
  }

  protected void openAndDiscover(String addressid) {
    sShell.open();
    address.setText(addressid);
    discover(addressid);
  }

  protected void discoverInfos(final TreeItem item, final String addressid) {
    DiscoverInfo disco = new DiscoverInfo();
    disco.setType(IQ.Type.GET);
    disco.setTo(addressid);
    disco.setNode(null);
    //DiscoverInfo info = disco.discoverInfo(addressid);
    new GOIMPacketListener(account.xmpp.getConnection(),new PacketIDFilter(disco.getPacketID()),taskObserver){
      public void processPacket(final Packet packet) {
        unregisterListener(false);
        final Task task = this;
        if(packet.getError() != null &&
            (packet.getError().getCode() == 404 || // not found
             packet.getError().getCode() == 501)) { // not implemented)
          sendBrowseIQ();
        }
        if(!(packet instanceof DiscoverInfo)) {
          System.err.println("Error during service discovery. Got wrong packet: " + packet.getClass().toString());
          taskObserver.finishedTask(task);
          return;
        }
        item.getDisplay().asyncExec(new Runnable() { public void run(){
          DiscoverInfo info = (DiscoverInfo)packet;
          Iterator i = info.getIdentities();
          while (i.hasNext()) {
            DiscoverInfo.Identity identity = (Identity) i.next();
            if(identity.getName() != null)
              item.setText(0, identity.getName());
            if (identity.getCategory() != null)
              item.setText(2, identity.getCategory());
            if (identity.getType() != null)
              item.setText(3, identity.getType());
          }
          if (info.containsFeature("jabber:iq:register")) {
            //System.out.println(addressid + " supports registration .. ");
            item.setData("supportsRegister",true);
          }
          if (info.containsFeature("jabber:iq:search")) {
            item.setData("supportsSearch",true);
          }
          if(info.containsFeature("http://jabber.org/protocol/muc")) {
            item.setData("supportsMUC",true);
          }
          item.setData("info", info);
          item.setBackground(null);
          taskObserver.finishedTask(task);
        }});
      }
      public void sendBrowseIQ() {
        try {
          final BrowseIQ browseIQ = BrowseIQProvider.retrieveBrowseRequest(account.xmpp.getConnection(),addressid);
          item.getDisplay().asyncExec(new Runnable() { public void run(){
            for(String ns : browseIQ.getNamespaces()) {
              if(ns.equals("jabber:iq:register"))
                item.setData("supportsRegister",true);
            }
            item.setBackground(null);
          }});
        } catch (XMPPException e) {
          e.printStackTrace();
        }
        taskObserver.finishedTask(this);
      }
    }.registerListener();
    account.xmpp.getConnection().sendPacket(disco);
  }

  protected void discover(final String addressid) {
    discovered.removeAll();
    status.setText("Trying to discover Services...");
    final TreeItem root = new TreeItem(discovered, SWT.NULL);
    root.setText(1, addressid);
    root.setData("address", addressid);
   
    if(taskObserver != null) taskObserver.cancel();
    taskObserver = new TaskObserver();
    taskObserver.addObserverListener(new SpheneListener<TaskObserverEvent>() {
      public void handleEvent(final TaskObserverEvent event) {
        discovered.getDisplay().asyncExec(new Runnable(){public void run(){
          switch(event.type) {
          case TaskObserverEvent.TYPE_ALL_FINISHED:
            status.setText("Finished discovering.");
            break;
          case TaskObserverEvent.TYPE_FINISHED:
          case TaskObserverEvent.TYPE_NEW_TASK:
            status.setText("Discovering Services ... (" + event.getObserver().getRemainingTaskCount() + " left)");
            break;
          }
        }});
      }});

    discoverInfos(root, addressid);

    discoverItems(root, addressid);
  }

  private void discoverItems(final TreeItem parent, final String addressid) {
    parent.removeAll();
    final Color gray = status.getDisplay().getSystemColor(SWT.COLOR_GRAY);
    DiscoverItems disco = new DiscoverItems();
    disco.setType(IQ.Type.GET);
    disco.setTo(addressid);
    disco.setNode(null);
   
    new GOIMPacketListener(account.xmpp.getConnection(),new PacketIDFilter(disco.getPacketID()),taskObserver) {
      public void processPacket(final Packet packet) {
        final Task task = this;
        unregisterListener(false);
        parent.getDisplay().asyncExec(new Runnable() { public void run() {
          if(packet.getError() != null) {
            MessageDialog.openError(sShell,"Error while discovering Services.","Error while discovering services: " + packet.getError().toString());
            return;
          }
          DiscoverItems discoItems = (DiscoverItems)packet;
          //status.setText("Retrieved Items, Getting Infos");
          Iterator i = discoItems.getItems();
          while (i.hasNext()) {
            final DiscoverItems.Item item = (DiscoverItems.Item) i.next();
//            System.out.println("=========================");
//            System.out.println("- " + item.getEntityID());
//            System.out.println("- " + item.getNode());
//            System.out.println("- " + item.getName());
            TreeItem subitem = new TreeItem(parent, SWT.NULL);
            subitem.setBackground(gray);
            parent.setExpanded(true);
            if(item.getName() != null)
              subitem.setText(0, item.getName());
            subitem.setText(1, item.getEntityID());
            subitem.setData("item", item);
            subitem.setData("address", item.getEntityID());
            discoverInfos(subitem, item.getEntityID());
          }
          taskObserver.finishedTask(task);
        }});
      }
    }.registerListener();
    account.xmpp.getConnection().sendPacket(disco);
  }

  protected void createMenu() {
    contextMenu = new Menu(sShell, SWT.POP_UP);
    //sShell.setMenu(contextMenu);
    registerItem = new MenuItem(contextMenu, SWT.PUSH);
    registerItem.setText("Register");
    searchItem = new MenuItem(contextMenu, SWT.PUSH);
    searchItem.setText("Search");
    multiUserChat = new MenuItem(contextMenu,SWT.CASCADE);
    multiUserChat.setText("Multi User Chat");
    Menu multiUserChatMenu = new Menu(multiUserChat);
    multiUserChat.setMenu(multiUserChatMenu);
    multiUserChatCreateRoom = new MenuItem(multiUserChatMenu,SWT.PUSH);
    multiUserChatCreateRoom.setText("Create New Room");
    multiUserChatJoinRoom = new MenuItem(multiUserChatMenu,SWT.PUSH);
    multiUserChatJoinRoom.setText("Join Room");
    multiUserChatListRooms = new MenuItem(multiUserChatMenu,SWT.PUSH);
    multiUserChatListRooms.setText("List Rooms");
   
    new MenuItem(contextMenu,SWT.SEPARATOR);
    vCardItem = new MenuItem(contextMenu,SWT.PUSH);
    vCardItem.setText("Show vCard");
    vCardItem.setImage(GOIMIcons.getImage(GOIMIcons.CONTACT_VCARD));

    registerItem.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        DiscoverInfo info = (DiscoverInfo) selectedItem.getData("info");
        String addressid = (String) selectedItem.getData("address");
        if (info == null)
          return;
        if (addressid == null)
          return;
        if (!info.containsFeature("jabber:iq:register"))
          return;
        Registration reg = new Registration();
        reg.setTo(addressid);
        IQ result;
        try {
          result = account.xmpp.sendIQPacketAndWaitForReply(reg);
        } catch (XMPPException e) {
          e.printStackTrace();
          ErrorDialog.openError(sShell,"Error while retrieving registration information","Could not retrieve registration information from " + reg.getFrom() + ": " + e.getLocalizedMessage(),new Status(IStatus.ERROR,GOIMPlugin.ID,IStatus.OK,"Error while retrieving registration information.",e));
          return;
        }
        Form form = Form.getFormFrom(result);
        new FormAnswerDialog(sShell, (Registration)result, form).open();
      }
    });
    searchItem.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        String addressid = (String) selectedItem.getData("address");
        new SearchUI(account,addressid);
      }
    });
    multiUserChatCreateRoom.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        String addressid = (String) selectedItem.getData("address");
        if (addressid == null)
          return;
        InputDialog dialog = new InputDialog(sShell,
            "Creating MUC Room",
            "Enter the name for the New Room (will be known as yourinput@" + addressid + ")",
            null,null);
        int r = dialog.open();
        if(r != InputDialog.OK) return;
        String room = dialog.getValue();
        String froom = room + "@" + addressid;
        MultiUserChat muc = new MultiUserChat(account.xmpp.getConnection(),froom);
        try {
          muc.create(account.getUsername());
          account.chatWindowExtensionManager.openMUCWindow(froom,muc);
          Form form = muc.getConfigurationForm();
          FormAnswerDialog d = new FormAnswerDialog(sShell, null, form);
          r = d.open();
          if(r != FormAnswerDialog.OK) {
            // Creating instant room
            muc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
          } else {
            muc.sendConfigurationForm(d.getResultForm());
          }
          MessageDialog.openInformation(sShell,"Successfully created Room.","Successfully created and joined room: " + froom);
        } catch (XMPPException e) {
          ErrorDialog.openError(sShell,"Can't Create Room","Error while trying to create room: " + e.toString(),new Status(IStatus.ERROR,GOIMPlugin.ID,IStatus.OK,"Error while creating room",e));
          e.printStackTrace();
        }
       
      }});
    multiUserChatListRooms.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        String addressid = (String) selectedItem.getData("address");
        if (addressid == null)
          return;
        discoverItems(selectedItem,addressid);
      }});
    multiUserChatJoinRoom.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        String addressid = (String) selectedItem.getData("address");
        if (addressid == null)
          return;
        joinMUCRoom(addressid);
      }});
   
    vCardItem.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        String addressid = (String) selectedItem.getData("address");
        new vCardGUI(account,addressid);
      }
    });
  }

  protected class FormAnswerDialog extends Dialog {
    @SuppressWarnings("unused")
    private Button okButton;

    private Form form;

    Composite dialogArea;

    private Registration reg;

    protected FormAnswerDialog(Shell parentShell, Registration reg, Form form) {
      super(parentShell);
      this.reg = reg;
      this.form = form;
    }
    public final String[] validRegisterFields = new String[] {
        "username",   "Username",
        "nick",      "Nick name",
        "password",    "Password",
        "name",      "Full Name",
        "first",    "First Name",
        "last",      "Last Name",
        "email",    "Email Address",
        "address",    "Address",
        "city",      "City",
        "state",    "State",
        "zip",      "ZIP",
        "phone",    "Phone Number",
        "url",      "URL",
        "misc",      "Misc",
//        "date",      "Date",  ????????????
//        "text",      "Text",
//        "key",      "Key",
    };

    private Form replyValue;

    @Override
    protected void configureShell(Shell newShell) {
      super.configureShell(newShell);
      newShell.setText((form == null ? "Registration with " + reg.getFrom() :form.getTitle()));
    }
   
    @SuppressWarnings("unchecked")
    @Override
    protected Control createDialogArea(Composite parent) {
      String instructionsstr = (form == null ? reg.getInstructions() : form.getInstructions());
      dialogArea = (Composite) super.createDialogArea(parent);
      Label instructions = new Label(dialogArea,SWT.NULL);
      instructions.setText(instructionsstr);
      instructions.setLayoutData(new GridData(SWT.FILL,SWT.NULL,true,false));
     
      Composite composite = new Composite(dialogArea,SWT.NULL);
      composite.setLayout(new GridLayout(2,false));
      composite.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
     
      if(form != null) {
        Iterator i = form.getFields();
        while(i.hasNext()) {
          FormField field = (FormField)i.next();
          if(field.getType().equals(FormField.TYPE_HIDDEN)) continue;
         
          GridData defaultLayoutData = new GridData(SWT.FILL,SWT.NULL,false,false);
          Object toAdd = null;
          if(field.getType().equals(FormField.TYPE_TEXT_SINGLE)) {
            createFieldLabel(composite, field);
            Text inputText = new Text(composite,SWT.BORDER);
            inputText.setLayoutData(defaultLayoutData);
            String val = getFirstValueOfField(field);
            if(val != null) inputText.setText(val);
            toAdd = inputText;
          } else if(field.getType().equals(FormField.TYPE_TEXT_PRIVATE)) {
            createFieldLabel(composite, field);
            Text inputText = new Text(composite,SWT.BORDER);
            inputText.setLayoutData(defaultLayoutData);
            toAdd = inputText;
            inputText.setEchoChar('*');
            String val = getFirstValueOfField(field);
            if(val != null) inputText.setText(val);
          } else if(field.getType().equals(FormField.TYPE_BOOLEAN)) {
            Button button = new Button(composite,SWT.CHECK);
            button.setText(field.getLabel());button.setToolTipText(field.getDescription());
            button.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,false,2,1));
            toAdd = button;
            String val = getFirstValueOfField(field);
            if(val != null) button.setSelection(val.equals("1"));
          } else {
            System.out.println("Field not supported: " + field.getLabel() + " (" + field.getType() + ")");
          }
         
          dialogArea.setData(field.getVariable(),toAdd);
        }
      } else {
        GridData layoutData = new GridData(SWT.FILL,SWT.NULL,false,false);
        Map attributes = reg.getAttributes();
        Map<String,String> atts = attributes;
        for(int i = 0 ; i < validRegisterFields.length ; i+=2) {
          String key = validRegisterFields[i];
          String value = atts.get(key); if(value == null) continue;

          Label label = new Label(composite,SWT.NULL);
          label.setText(validRegisterFields[i+1]);
          Text input = new Text(composite,SWT.BORDER);
          input.setText(value);
          if(key.equals("password"))
            input.setEchoChar('*');
          input.setLayoutData(layoutData);
          dialogArea.setData(key,input);
        }
//        Label lblusername = new Label(composite,SWT.NULL);
//        lblusername.setText("Username");
//        Text username = new Text(composite,SWT.BORDER);
//        username.setLayoutData(layoutData);
//        dialogArea.setData("username",username);
//        Label lblpassword = new Label(composite,SWT.NULL);
//        lblpassword.setText("Password");
//        Text password = new Text(composite,SWT.BORDER);
//        password.setEchoChar('*');
//        password.setLayoutData(layoutData);
//        dialogArea.setData("password",password);
      }
     
      return dialogArea;
    }

    private String getFirstValueOfField(FormField field) {
      Iterator vals = field.getValues();
      while(vals.hasNext()) {
        return (String)vals.next();
      }
      return null;
    }

    private void createFieldLabel(Composite parent, FormField field) {
      Label fieldLabel = new Label(parent,SWT.NULL);
      fieldLabel.setText(field.getLabel() + (field.isRequired() ? " *" : ""));
      fieldLabel.setToolTipText(field.getDescription());
    }    @Override
    protected void createButtonsForButtonBar(Composite parent) {
      okButton = createButton(parent, IDialogConstants.OK_ID,
          IDialogConstants.OK_LABEL, true);
      createButton(parent, IDialogConstants.CANCEL_ID,
          IDialogConstants.CANCEL_LABEL, false);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void okPressed() {
      setReturnCode(OK);
      Registration registration = new Registration();
      registration.setType(IQ.Type.SET);
      HashMap attributes = new HashMap();
      if(reg != null)
        registration.setTo(reg.getFrom());
      if(form == null) {
//        Text username = (Text)dialogArea.getData("username");
//        Text password = (Text)dialogArea.getData("password");
//        registration.setUsername(username.getText());
//        registration.setPassword(password.getText());
        Map<String,String> atts = reg.getAttributes();
        for(String key : atts.keySet()) {
          Text input = (Text)dialogArea.getData(key);
          if(input != null)
            attributes.put(key,input.getText());
        }
      } else {
        Form reply = form.createAnswerForm();
        Iterator i = reply.getFields();
        while(i.hasNext()) {
          FormField field = (FormField)i.next();
          if(field.getType().equals(FormField.TYPE_HIDDEN)) continue;
          Object obj = (Control)dialogArea.getData(field.getVariable());
          if(obj instanceof Text) {
            String val;
            reply.setAnswer(val = field.getVariable(),((Text)obj).getText());
//            if(field.getVariable().equals("username"))
//              registration.setUsername(val);
//            else if(field.getVariable().equals("password"))
//              registration.setPassword(val);
            if(reg != null && reg.getAttributes().containsKey(field.getVariable()))
              attributes.put(field.getVariable(),val);
          } else if(obj instanceof Button) {
            reply.setAnswer(field.getVariable(),((Button)obj).getSelection());
          }
        }
        replyValue = reply;
        if(reg != null)
          registration.addExtension(reply.getDataFormToSend());
      }
      if(reg == null) { close(); return; }
      registration.setAttributes(attributes);
      @SuppressWarnings("unused") IQ result;
      try {
        result = account.xmpp.sendIQPacketAndWaitForReply(registration);
      } catch (XMPPException e) {
        e.printStackTrace();
        ErrorDialog.openError(dialogArea.getShell(),"Error while registering","Could not register with " + reg.getFrom() + ": " + e.getLocalizedMessage(),new Status(IStatus.ERROR,GOIMPlugin.ID,IStatus.OK,"Error while registering",e));
        close();
        return;
      }
      MessageDialog.openInformation(dialogArea.getShell(),"Registration Successful","Successfully registered with " + reg.getFrom());
      close();
    }
    public Form getResultForm() {
      return replyValue;
    }
  }

  protected void showMenu(TreeItem item) {
    selectedItem = item;
    //DiscoverInfo info = (DiscoverInfo) item.getData("info");
    Boolean supportsRegister = (Boolean)item.getData("supportsRegister");
    boolean supportsMUC = item.getData("supportsMUC") == null ? false : (Boolean)item.getData("supportsMUC");
    registerItem.setEnabled(supportsRegister != null && supportsRegister);
    multiUserChat.setEnabled(supportsMUC);
    String addressid = (String) item.getData("address");
    vCardItem.setEnabled(addressid != null);
    if(supportsMUC) {
      boolean isChannel = addressid.contains("@");
      multiUserChatCreateRoom.setEnabled(!isChannel);
      multiUserChatJoinRoom.setEnabled(isChannel);
      multiUserChatListRooms.setEnabled(!isChannel);
    }
    //System.out.println("Showing context Menu");
    contextMenu.setVisible(true);
  }

  /**
   * This method initializes sShell
   */
  private void createSShell() {
    sShell = new Shell();
    sShell.setText("Service Discovery");
    sShell.setLayout(new GridLayout());
    createCompositeChooseAddress();
    createDiscovered();
    createCompositeButtons();
    sShell.setSize(new org.eclipse.swt.graphics.Point(483, 280));
  }

  /**
   * This method initializes compositeChooseAddress
   *
   */
  private void createCompositeChooseAddress() {
    GridData gridData1 = new org.eclipse.swt.layout.GridData();
    gridData1.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
    gridData1.grabExcessHorizontalSpace = true;
    gridData1.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER;
    GridLayout gridLayout = new GridLayout();
    gridLayout.numColumns = 3;
    GridData gridData = new org.eclipse.swt.layout.GridData();
    gridData.grabExcessHorizontalSpace = true;
    gridData.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER;
    gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
    compositeChooseAddress = new Composite(sShell, SWT.NONE);
    compositeChooseAddress.setLayoutData(gridData);
    compositeChooseAddress.setLayout(gridLayout);
    lblAddress = new Label(compositeChooseAddress, SWT.NONE);
    lblAddress.setText("Address");
    address = new Text(compositeChooseAddress, SWT.BORDER);
    address.setLayoutData(gridData1);
    buttonDiscover = new Button(compositeChooseAddress, SWT.NONE);
    buttonDiscover.setText("Discover");
    buttonDiscover
        .addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
          public void widgetSelected(
              org.eclipse.swt.events.SelectionEvent e) {
            discover(address.getText());
          }
        });
  }

  /**
   * This method initializes discovered
   *
   */
  private void createDiscovered() {
    GridData gridData2 = new org.eclipse.swt.layout.GridData();
    gridData2.grabExcessHorizontalSpace = true;
    gridData2.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
    gridData2.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;
    gridData2.grabExcessVerticalSpace = true;
    discovered = new Tree(sShell, SWT.FULL_SELECTION);
    discovered.setLayoutData(gridData2);
    discovered.setHeaderVisible(true);
    TreeColumn name = new TreeColumn(discovered, SWT.LEFT);
    name.setText("Name");
    TreeColumn jid = new TreeColumn(discovered, SWT.LEFT);
    jid.setText("JID");
    TreeColumn category = new TreeColumn(discovered, SWT.LEFT);
    category.setText("Category");
    TreeColumn type = new TreeColumn(discovered, SWT.LEFT);
    type.setText("Type");
    name.pack();
    jid.pack();
    category.pack();
    type.pack();
    name.setWidth(160);
    jid.setWidth(160);
    discovered.addMouseListener(new MouseAdapter() {
      @Override
      public void mouseDoubleClick(MouseEvent e) {
        TreeItem items[] = discovered.getSelection();
        if (items.length < 0)
          return;
        TreeItem item = items[0];
        selectedItem = item;
        Boolean supportsMUC = (Boolean)item.getData("supportsMUC");
        if(supportsMUC != null && supportsMUC) {
          String addressid = (String) item.getData("address");
          if (addressid == null)
            return;
          if(StringUtils.parseName(addressid).equals(""))
            discoverItems(selectedItem,addressid);
          else
            joinMUCRoom(addressid);
        }
      }

      @Override
      public void mouseUp(MouseEvent e) {
        TreeItem gitem = discovered.getItem(new Point(e.x,e.y));
        if(gitem == null) return;
        discovered.setSelection(new TreeItem[] { gitem });
        TreeItem items[] = discovered.getSelection();
        if (items.length < 0)
          return;
        TreeItem item = items[0];
        selectedItem = item;
        if ((e.stateMask & SWT.BUTTON3) != 0
            || (e.stateMask & SWT.BUTTON2) != 0) {
          showMenu(item);
        }
      }
    });
  }

  /**
   * This method initializes compositeButtons
   *
   */
  private void createCompositeButtons() {
    GridData gridData4 = new org.eclipse.swt.layout.GridData();
    gridData4.grabExcessHorizontalSpace = true;
    gridData4.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER;
    gridData4.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
    GridData gridData3 = new org.eclipse.swt.layout.GridData();
    gridData3.grabExcessHorizontalSpace = true;
    gridData3.verticalAlignment = org.eclipse.swt.layout.GridData.CENTER;
    gridData3.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
    GridLayout gridLayout1 = new GridLayout();
    gridLayout1.numColumns = 2;
    compositeButtons = new Composite(sShell, SWT.NONE);
    compositeButtons.setLayout(gridLayout1);
    compositeButtons.setLayoutData(gridData4);
    status = new Label(compositeButtons, SWT.NONE);
    status.setText("Enter Address and click Discover");
    status.setLayoutData(gridData3);
    buttonClose = new Button(compositeButtons, SWT.NONE);
    buttonClose.setText("Close");
    buttonClose
        .addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
          public void widgetSelected(
              org.eclipse.swt.events.SelectionEvent e) {
            sShell.close();
          }
        });
  }

  private void joinMUCRoom(String addressid) {
    String name = StringUtils.parseName(addressid);
    if(name.equals("")) {
      InputDialog dialog = new InputDialog(sShell,"Join Room","Enter Name of the room you want to join on service: " + addressid,"",new IInputValidator(){
        public String isValid(String newText) {
          if(newText.equals("") ||
              newText.indexOf('@')>-1)
            return "Enter a valid room name. e.g: myroomname";
          return null;
        }});
      if(dialog.open() != InputDialog.OK) return;
      name = dialog.getValue() + "@" + addressid;
    } else
      name = addressid;
    MultiUserChat muc = new MultiUserChat(account.xmpp.getConnection(),name);
    try {
      muc.join(account.getUsername());
    } catch (XMPPException e) {
      ErrorDialog.openError(sShell,"Error while Joining room","Error while trying to join Room: " + e.toString(),new Status(Status.ERROR,GOIMPlugin.ID,Status.OK,"Error while trying to join MUC room",e));
      e.printStackTrace();
      return;
    }
    account.chatWindowExtensionManager.openMUCWindow(name,muc);
  }

}
TOP

Related Classes of net.sphene.goim.rcp.ui.ServiceDiscoveryUI$FormAnswerDialog

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.