--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/de/unixwork/im/App.java Wed Dec 25 21:49:48 2024 +0100 @@ -0,0 +1,84 @@ +package de.unixwork.im; + +import javax.swing.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.jivesoftware.smack.roster.RosterEntry; +import org.jxmpp.jid.Jid; + +public class App { + + private static App instance; + + private final ContactListFrame contactListFrame; + private final Map<String, ConversationFrame> conversations; + + private final Xmpp xmpp; + + public App(Xmpp xmpp) throws Exception { + if(instance != null) { + throw new Exception("App already initilized"); + } + App.instance = this; + conversations = new HashMap<>(); + this.xmpp = xmpp; + + // Create the contact list window + contactListFrame = new ContactListFrame(); + contactListFrame.setContactClickListener(contact -> { + openConversation(contact.getJid().asUnescapedString()); + }); + contactListFrame.setVisible(true); + } + + public static App getInstance() { + return instance; + } + + public Xmpp getXmpp() { + return xmpp; + } + + // Method to open a conversation window + public void openConversation(String xid) { + SwingUtilities.invokeLater(() -> { + if (!conversations.containsKey(xid)) { + ConversationFrame conversationFrame = new ConversationFrame(xid); + conversations.put(xid, conversationFrame); + conversationFrame.setVisible(true); + } else { + conversations.get(xid).toFront(); + } + }); + } + + public void dispatchMessage(Jid from, String msg, boolean secure) { + SwingUtilities.invokeLater(() -> { + // add message to the correct conversation + // if no conversation exists yet, create a new window + String xid = from.asBareJid().toString(); + //String resource = from.getResourceOrNull(); + ConversationFrame conversation = conversations.get(xid); + if(conversation == null) { + conversation = new ConversationFrame(xid); + conversations.put(xid, conversation); + } + + conversation.addToLog(msg, true, false); + + conversation.setVisible(true); + }); + } + + public void setContacts(List<RosterEntry> contacts) { + SwingUtilities.invokeLater(() -> { + contactListFrame.setContacts(contacts); + }); + } + + // Method to perform actions in the GUI thread from other threads + public void runOnUiThread(Runnable action) { + SwingUtilities.invokeLater(action); + } +}