source: trunk/jabberit_messenger/java_source/src/nu/fw/jeti/ui/ChatSplitPane.java @ 1001

Revision 1001, 26.8 KB checked in by alexandrecorreia, 15 years ago (diff)

Ticket #552 - Inclusão do projeto Java referente ao applet do módulo.

Line 
1/*
2 *      Jeti, a Java Jabber client, Copyright (C) 2003 E.S. de Boer 
3 *
4 *  This program is free software; you can redistribute it and/or modify
5 *  it under the terms of the GNU General Public License as published by
6 *  the Free Software Foundation; either version 2 of the License, or
7 *  (at your option) any later version.
8 *
9 *  This program is distributed in the hope that it will be useful,
10 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
11 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 *      GNU General Public License for more details.
13 *
14 *  You should have received a copy of the GNU General Public License
15 *  along with this program; if not, write to the Free Software
16 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17 *
18 *      For questions, comments etc,
19 *      use the website at http://jeti.jabberstudio.org
20 *  or mail/IM me at jeti@jabber.org
21 *
22 *      Created on 28-apr-2003
23 */
24
25package nu.fw.jeti.ui;
26
27import java.awt.*;
28import java.awt.event.*;
29import java.text.DateFormat;
30import java.text.MessageFormat;
31import java.util.*;
32import java.util.List;
33
34import javax.swing.Timer;
35import javax.swing.*;
36import javax.swing.event.ChangeEvent;
37import javax.swing.event.ChangeListener;
38import javax.swing.text.*;
39import javax.swing.border.*;
40import javax.swing.ImageIcon;
41
42import nu.fw.jeti.events.ChatEndedListener;
43import nu.fw.jeti.jabber.Backend;
44import nu.fw.jeti.jabber.JID;
45import nu.fw.jeti.jabber.JIDStatus;
46import nu.fw.jeti.jabber.elements.*;
47import nu.fw.jeti.plugins.*;
48import nu.fw.jeti.util.Base64;
49import nu.fw.jeti.util.I18N;
50import nu.fw.jeti.util.Preferences;
51import nu.fw.jeti.util.JavaScriptServerExpresso;
52import nu.fw.jeti.util.ServerExpresso;
53
54/**
55 * @Author : Alexandre Correia - alexandrecorreia@celepar.pr.gov.br
56 * @Date : 05/11/2008
57 * @Brief : classe focusWindow, faz com que o titulo fique piscando.
58 */
59
60class focusWindow implements ActionListener
61{
62        private boolean flag = false;
63        private JFrame window;
64        private String title;
65        private Timer timer = new Timer(1000, this);
66        private String name;
67       
68        public focusWindow()
69        {
70                timer.start();
71        }
72       
73        public void load(JFrame window, String name)
74        {
75                this.window = window;
76                this.title = window.getTitle();
77                this.name = name;
78               
79        }
80    public void actionPerformed(ActionEvent evt)
81    {
82        if( window.getExtendedState() == window.ICONIFIED )
83        {
84                if(flag)
85                        window.setTitle("## " + this.name + " fala...");
86                else
87                        window.setTitle(this.title);
88                flag = !flag;
89        }
90        else
91        {
92                timer.stop();
93                window.setTitle(this.title);
94        }
95    }
96}
97
98/**
99 * class defining basic feature of a chat window
100 * used by groupchatwindow and chatwindow
101 * @author E.S. de Boer
102 *
103 */
104
105//Do not add text to txtUitvoer outside this class, otherwise the text will
106//not scroll to the end
107
108public class ChatSplitPane extends JSplitPane
109{
110        private JID contactJID;
111        private String me;
112        private Backend backend;
113        private JScrollPane scrlInvoer = new JScrollPane();
114        private JTextPane txtInvoer = new JTextPane();
115        private JScrollPane scrlUitvoer = new JScrollPane();
116        private JTextPane txtUitvoer = new ToolTipTextpane();
117        private String contactName;
118        private String thread;
119        private boolean enterSends = false;
120        private boolean showTimestamp = false;
121        private Emoticons emoticons;
122        private JPanel pnlBottom = new JPanel();
123        private BorderLayout borderLayout1 = new BorderLayout();
124        private JPanel pnlControl = new JPanel();
125        private JPopupMenu popupMenu = new JPopupMenu();
126        private JPopupMenu popupSelectedMenu = new JPopupMenu();
127        private String composingID;
128        private boolean typing = false;
129        private FormattedMessage xhtml;
130        private boolean groupChat;
131        private Spell spell;
132        private OpenPGP openPGP;
133        private Translator translator;
134        private Translator links;
135        private Translator xmppuri;
136        private Translator colormessages;
137        private Notifiers titleTimer;
138        private Notifiers titleFlash;
139        private SimpleAttributeSet colorAttributeSet = new SimpleAttributeSet();
140        private boolean toFrontOnNewMessage=false;
141        private static DateFormat dateFormat = DateFormat.getTimeInstance();
142        DateFormat shortDate= DateFormat.getDateInstance(DateFormat.SHORT);
143        DateFormat shortTime= DateFormat.getTimeInstance(DateFormat.SHORT);
144        private volatile boolean scrolls=true;
145        private volatile boolean systemScroll=true;
146        private Date date = new Date();
147        private ImageIcon avatar;
148    //private boolean sendEnabled=true;
149       
150        class ToolTipTextpane extends JTextPane
151        {//Tooltip on textpane, show time of message
152                public String getToolTipText(MouseEvent e)
153                {
154                        int location = txtUitvoer.viewToModel(e.getPoint());
155                        StyledDocument doc = (StyledDocument) txtUitvoer.getDocument();
156                        AttributeSet set = doc.getCharacterElement(location).getAttributes();
157                        return (String) set.getAttribute("time");       
158                }
159        }
160       
161        /**
162         * Groupchat splitpane constructor
163         * @param backend
164         * @param to
165         * @param toName
166         * @param me
167         * @param thread
168         * @param groupChat
169         * @param type
170         * @param menu
171         * @param frame
172         *
173         */
174        public ChatSplitPane(Backend backend, JID to,String toName,String me,JMenu menu,JFrame frame)
175        {
176                groupChat = true;
177                contactJID = to;
178        contactName = toName;
179                this.backend = backend;
180                this.me = me;
181                toFrontOnNewMessage = Preferences.getBoolean("groupchat", "toFrontOnNewMessage", false);
182                init("groupchat",menu);
183                setParentFrame(frame);
184        }
185       
186        /**
187         * 1-1 chat splitpane constructor
188         * @param backend
189         * @param to
190         * @param me
191         * @param thread
192         * @param menu
193         * @param frame
194         */
195        public ChatSplitPane(Backend backend, JIDStatus jidStatus,String me,String thread,JMenu menu,JFrame frame)
196        {
197                this.groupChat = false;
198                contactJID = jidStatus.getCompleteJID();
199        contactName = jidStatus.getNick();
200                avatar = jidStatus.getAvatar();
201                this.backend = backend;
202                this.me = me;
203                this.thread = thread;
204                toFrontOnNewMessage = Preferences.getBoolean("jeti", "toFrontOnNewMessage", false);
205                init(jidStatus.getType(),menu);
206                setParentFrame(frame);
207        }
208       
209        /**
210         * Add a menu to the menu invoked when the user presses on
211         * the right mousebutton and there is text selected
212         * @param submenu The menu to add
213         */
214        public void addToSelectedTextPopupMenu(JMenu submenu)
215        {
216                popupSelectedMenu.add(submenu);
217        }
218       
219        public String getSelectedText()
220        {
221                String text = txtUitvoer.getSelectedText();
222                if(text!=null) return text;
223                else return txtInvoer.getSelectedText();
224        }
225       
226        public void init(String type,JMenu menu)
227        {
228                JCheckBoxMenuItem chkItem = new JCheckBoxMenuItem(I18N.gettext("main.chat.menu.To_front_on_new_message"));
229                chkItem.setSelected(toFrontOnNewMessage);
230                chkItem.addActionListener(new ActionListener()
231                {
232                        public void actionPerformed(ActionEvent e)
233                        {
234                                toFrontOnNewMessage= ((JCheckBoxMenuItem)e.getSource()).isSelected();
235                        }
236                });
237                menu.add(chkItem);
238                if (PluginsInfo.isPluginLoaded("emoticons"))
239                {
240                        initEmoticons(type,menu);
241                }
242                               
243                if (!groupChat && PluginsInfo.isPluginLoaded("openpgp"))
244                {
245                        openPGP =  (OpenPGP)PluginsInfo.getPluginInstance("openpgp");
246                        if(openPGP.canEncrypt(contactJID))
247                        {
248                                Document doc = txtUitvoer.getDocument();
249                                SimpleAttributeSet sas = new SimpleAttributeSet();
250                                StyleConstants.setForeground(sas, Color.blue);
251                                try
252                                {
253                                        doc.insertString(doc.getLength(),"Encrypted Converstation\n", sas);
254                                } catch (BadLocationException e1)
255                                {
256                                        e1.printStackTrace();
257                                }
258                        }
259                }
260               
261                Translate translate=null;
262                if (PluginsInfo.isPluginLoaded("translate"))
263                {
264                        translate = (Translate) PluginsInfo.newPluginInstance("translate");
265                        translate.init(this,txtInvoer);
266                        txtUitvoer.addMouseListener(new MouseAdapter()
267                        {
268                                public void mouseClicked(MouseEvent e)
269                                {       
270                                        if(SwingUtilities.isRightMouseButton(e))
271                                        {
272                                                if(txtUitvoer.getSelectedText()!=null)
273                                                {
274                                                        popupSelectedMenu.show(e.getComponent(), e.getX(), e.getY());
275                                                }
276                                        }
277                                }
278                        });
279                }
280                if (PluginsInfo.isPluginLoaded("spell"))
281                {
282                        spell = (Spell) PluginsInfo.newPluginInstance("spell");
283                        spell.addChangeDictoryMenuEntry(menu);
284                }
285                if (PluginsInfo.isPluginLoaded("links"))
286                {
287                        links = (Translator) PluginsInfo.newPluginInstance("links");
288                        links.init(txtUitvoer);
289                }
290                if (PluginsInfo.isPluginLoaded("xmppuri"))
291                {
292                        xmppuri = (Translator) PluginsInfo.newPluginInstance("xmppuri");
293                        xmppuri.init(txtUitvoer);
294                }
295                if (PluginsInfo.isPluginLoaded("colormessages"))
296                {
297                        colormessages = (Translator) PluginsInfo.newPluginInstance("colormessages");
298                }
299                if (PluginsInfo.isPluginLoaded("titlescroller"))
300                {
301                        titleTimer = (Notifiers) PluginsInfo.newPluginInstance("titlescroller");
302                }
303                if (PluginsInfo.isPluginLoaded("titleflash"))
304                {
305                        titleFlash = (Notifiers) PluginsInfo.newPluginInstance("titleflash");
306                }
307                if(PluginsInfo.isPluginLoaded("windowsutils"))
308                {
309                        NativeUtils util =(NativeUtils)PluginsInfo.newPluginInstance("windowsutils");
310                        util.addChatMenus(menu,this);
311                }
312               
313                translator = PluginsInfo.getTranslator();
314                if(emoticons != null || spell != null || translate!=null) 
315                {       
316                        txtInvoer.addMouseListener(new MouseAdapter()
317                        {
318                                public void mousePressed(MouseEvent e)
319                                {
320                                        if (SwingUtilities.isRightMouseButton(e))
321                                        {
322                                                if(txtInvoer.getSelectedText()!=null)
323                                                {
324                                                        popupSelectedMenu.show(e.getComponent(), e.getX(), e.getY());
325                                                }
326                                                else if(spell != null)
327                                                {
328                                                        if(!spell.rightClick(txtInvoer,e) && emoticons != null) popupMenu.show(e.getComponent(), e.getX(), e.getY());
329                                                }
330                                                else popupMenu.show(e.getComponent(), e.getX(), e.getY());
331                                        }
332                                }
333                        });
334                }
335               
336                ToolTipManager.sharedInstance().registerComponent(txtUitvoer);
337                       
338                enterSends = Preferences.getBoolean("jeti","enterSends",true);
339                showTimestamp = Preferences.getBoolean("jeti","showTimestamp",true);
340               
341                try
342                {
343                        jbInit();
344                }
345                catch (Exception e)
346                {
347                        e.printStackTrace();
348                }
349                if (PluginsInfo.isPluginLoaded("xhtml"))
350                {
351                        //String contactJid = contactJID.toString();
352                        xhtml = (FormattedMessage) PluginsInfo.newPluginInstance("xhtml");
353                        xhtml.initXHTML(this, txtInvoer, pnlControl, contactJID );
354                }
355               
356                String t = "";
357                //if(!groupChat)       
358                //notify();
359                if (thread == null)t = "no id - ";
360                Document doc = txtUitvoer.getDocument();
361                try
362                {
363                        SimpleAttributeSet sas = new SimpleAttributeSet();
364                        StyleConstants.setForeground(sas, Color.gray);
365                        doc.insertString(doc.getLength(), t + I18N.gettext("main.chat.Chat_started_on") + " " + DateFormat.getDateTimeInstance().format(new Date()), sas);
366                }
367                catch (BadLocationException e)
368                {
369                        e.printStackTrace();
370                }
371               
372                //solves bug iconofied frame then no system message and wrong layout
373                //pack();
374               
375                setBorder(null);               
376                setSize(300, 350);
377        }
378       
379        public JTextPane getTextInput()
380        {
381                return txtInvoer;
382        }
383
384       
385        public void setParentFrame(JFrame frame)
386        {
387                if (titleTimer !=null)
388                {
389                        titleTimer.init(frame,contactName);
390                }
391                if (titleFlash != null)
392                {
393                        titleFlash.init(frame, contactName);
394                }
395        }
396       
397        private void initEmoticons(String type,JMenu menu)
398        {
399                //showEmoticons = true;
400                emoticons = (Emoticons) PluginsInfo.newPluginInstance("emoticons");
401                try
402                {
403                        emoticons.init(txtUitvoer, pnlControl, txtInvoer, popupMenu,type,menu);
404                }
405                catch (IllegalStateException ex)
406                {
407                        ex.printStackTrace();
408                        //showEmoticons = false;
409                        PluginsInfo.unloadPlugin("emoticons");
410                        emoticons = null;
411                        return;
412                }
413        }
414       
415        public void close()
416        {
417                if(groupChat)contactJID = new JID(contactJID.getUser(),contactJID.getDomain(),me);
418                for(Iterator j = backend.getListeners(ChatEndedListener.class);j.hasNext();)
419                {//exit
420                        ((ChatEndedListener)j.next()).chatEnded(contactJID);
421                }
422        }
423       
424//      public boolean compareJID(JID jid)
425//      {
426//              return from.equals(jid);
427//      }
428//     
429//      public String getThread()
430//      {
431//              return thread;
432//      }
433
434        public void appendMessage(Message message,String name)
435        {
436                if (name == null)
437                {
438                        appendSystemMessage(message.getBody());
439                }
440                else if(name.equals(me))
441                {
442                        showMessage(message,new Color(156, 23, 23),Preferences.getString("jeti", "ownName", me));
443                }
444                else
445                {
446                        if(titleTimer!=null )
447                        {
448                titleTimer.start(
449                    MessageFormat.format(
450                        I18N.gettext("main.chat.{0}_says_{1}"),
451                        new Object[] {name,message.getBody()}));
452            }
453                       
454                        if(titleFlash!=null)
455                        {
456                titleFlash.start("");
457            }
458                       
459                        if(!groupChat)contactJID = message.getFrom();
460                       
461                        showMessage(message, new Color(17, 102, 6), name);
462                }
463        }
464       
465        public  void appendSystemMessage(final String message)
466        {
467                SwingUtilities.invokeLater(new Runnable()
468                {
469                        public void run()
470                        {
471                                final Document doc = txtUitvoer.getDocument();
472                                final Point  viewPos = scrlUitvoer.getViewport().getViewPosition();
473                                final boolean scroll = scrolls;//cache scroll value because insertstring will update it
474                                systemScroll=true;
475                                SimpleAttributeSet sas = new SimpleAttributeSet();
476                                StyleConstants.setForeground(sas, Color.gray);
477                                String timeStamp;
478                                if (showTimestamp)      timeStamp = formatTime(new Date()) + " ";
479                                else timeStamp = "";
480                                try
481                                {
482                                        doc.insertString(doc.getLength(), "\n"+ timeStamp + message, sas);
483                                }
484                                catch (BadLocationException e)
485                                {
486                                        e.printStackTrace();
487                                }
488                               
489                                if(scroll)
490                                {
491                                        txtUitvoer.setCaretPosition(doc.getLength());
492                                        scrolls=true;
493                                }
494                                else
495                                {
496                                        scrlUitvoer.getViewport().setViewPosition(viewPos);
497                                }
498                        }
499                });
500        }
501       
502        private void showMessage(final Message message,final Color color,final String name)
503        {//two threads can write to display (typing & receiving)
504                       
505                SwingUtilities.invokeLater(new Runnable()
506                {
507                        public void run()
508                        {
509                                String text = message.getBody();
510                        Date tempdelay =null;
511                                List tempWordList=null;
512                                date.setTime(System.currentTimeMillis());
513                               
514                                // Loop through extensions
515                                if (message.hasExtensions())
516                                {
517                                        for (Iterator i = message.getExtensions(); i.hasNext();)
518                                        {
519                                                Extension extension = (Extension) i.next();
520                                                if (extension instanceof XDelay)
521                                                {
522                                                        tempdelay = ((XDelay) extension).getDate();
523                                                }
524                                                else if(openPGP!=null && openPGP.canEncrypt(contactJID))
525                                                {
526                                                        if(tempWordList==null)
527                                                        {
528                                                                String temp =  openPGP.decrypt(extension);
529                                                                if(temp!=null) text = temp;
530                                                        }
531                                                }
532                                                else if(xhtml!=null)
533                                                {
534                                                        if(tempWordList==null) tempWordList = xhtml.getWordList(extension);
535                                                }
536                                        }
537                                }
538                                if (xhtml!=null && !name.equals(me) && !groupChat) {
539                            xhtml.useXHTML(tempWordList!=null, name);
540                        }
541                               
542                                if (tempWordList==null) {
543                                        tempWordList = createWordList(text);
544                        }
545
546                        // Mark eventual weblinks (if links extension is active)
547                                if(links!=null) {
548                            links.translate(tempWordList);
549                        }
550                               
551                                if(xmppuri!=null) {
552                            xmppuri.translate(tempWordList);
553                        }
554                                if(groupChat) {//me replace with nick
555                                        for(Iterator i = tempWordList.iterator();i.hasNext();) {
556                                                Word w = (Word) i.next();
557                                                if(w.word.equals("/me")) {
558                                    w.word = name;
559                                }
560                                        }
561                                }
562
563                                // Handle error messages
564                                if (message.getType().equals("error")) {
565                            insertError(tempWordList, message);
566                                }
567
568                                // Insert eventual emoticons
569                                if (emoticons != null) {
570                            emoticons.insertEmoticons(tempWordList);
571                        }
572
573                                //TODO make a new translator thing for here and below
574                                if (translator != null) translator.translate(tempWordList);
575
576                                final Date delay = tempdelay;
577                                final List wordList = tempWordList;
578                               
579                               
580                                Point  viewPos = scrlUitvoer.getViewport().getViewPosition();
581                                boolean scroll = scrolls;//cache scroll value because insertstring will update it
582                                systemScroll=true;
583                                Document doc = txtUitvoer.getDocument();
584                                try
585                                {
586                                        doc.insertString(doc.getLength(),"\n",null);
587                            if (delay != null)
588                            {
589                                SimpleAttributeSet sas = new SimpleAttributeSet();
590                                StyleConstants.setForeground(sas, Color.darkGray);
591                                doc.insertString(doc.getLength(), formatTime(delay) + " ", sas);
592                            }
593                                        else if (showTimestamp)
594                                        {// Eventual timestamp
595                                SimpleAttributeSet sas = new SimpleAttributeSet();
596                                StyleConstants.setForeground(sas, Color.gray);
597                                doc.insertString(doc.getLength(), formatTime(date) + " ", sas);
598                            }
599                                       
600                            StyleConstants.setForeground(colorAttributeSet, color);
601               
602                            // Print originator if not error
603                            if (!message.getType().equals("error")) {
604                                                colorAttributeSet.addAttribute("time",dateFormat.format(date));
605                                                doc.insertString(doc.getLength(),name+ ": ",colorAttributeSet);
606                                        }
607                                       
608                            // Insert words from wordlist
609                                        for(Iterator i = wordList.iterator();i.hasNext();) {
610                                                Word w = (Word) i.next();
611                                                doc.insertString(doc.getLength(),w.toString(),
612                                                 w.getAttributes());
613                                        }
614               
615                                        if (scroll)     {
616                                txtUitvoer.setCaretPosition(doc.getLength());
617                                scroll=true;
618                            } else {
619                                                scrlUitvoer.getViewport().setViewPosition(viewPos);
620                                        }
621                                }
622                                catch (BadLocationException e)
623                                {
624                                        e.printStackTrace();
625                                }
626
627                                /**
628                                 * @Author : Alexandre Correia - alexandrecorreia@celepar.pr.gov.br
629                                 * @Date : 04/11/2008
630                                 * @Brief : Trecho de codigo abaixo, faz com que a janela fique piscando caso esta esteja
631                                 * minimizada na barra de tarefas. Criada a classe focusWindow.
632                                 */
633
634                                JFrame frame = (JFrame)getTopLevelAncestor();
635
636                                if(toFrontOnNewMessage)
637                                {
638                                        if(!getTopLevelAncestor().isFocusOwner())
639                                        {
640                                                if(getTopLevelAncestor() instanceof JFrame)
641                                                {
642                                                        if( frame.getExtendedState() == Frame.ICONIFIED )
643                                                        {
644                                                                frame.setState(Frame.NORMAL);
645                                                        }
646                                                        frame.toFront();
647                                                }
648                                                else txtInvoer.requestFocus();
649                                        }
650                                }
651                               
652                                if( frame.getExtendedState() == Frame.ICONIFIED )
653                                {
654                                        frame.setVisible(true);
655                                        focusWindow focusW = new focusWindow();
656                                        focusW.load(frame, name);
657                                }
658                        }
659                });
660        }
661       
662        /**
663     * Format a timestamp for display.
664     */
665    private String formatTime(Date date) {
666                String result = "";
667               
668                if((System.currentTimeMillis() -date.getTime())> 600000)
669                {//message is older then 10 min
670                        Calendar cal = Calendar.getInstance();
671                        cal.set(Calendar.HOUR, 0);
672                    cal.set(Calendar.MINUTE, 0);
673                    cal.set(Calendar.SECOND, 0);
674                    cal.set(Calendar.AM_PM, Calendar.AM);
675                    if(date.before(cal.getTime()))
676                    {//print date if it is the previous day
677                        result += shortDate.format(date)+ " ";
678                    }
679                }
680                result+="["+shortTime.format(date)+"]";
681                return result;
682    }
683
684    // Insert error message into wordList
685    private void insertError(List wordList, Message message) {
686        String error;
687        boolean replace = false;
688
689        switch (message.getErrorCode()) {
690        case 404:
691            error = MessageFormat.format(
692                I18N.gettext("main.error.User_{0}_could_not_be_found"),
693                new Object[] {message.getFrom()});
694            replace = true;
695            break;
696        default:
697            error = I18N.gettext("main.error.Error_in_chat");
698            break;
699        }
700
701        // Create list of error words and make them red
702        List errorWords = createWordList(error);
703        SimpleAttributeSet sas = new SimpleAttributeSet();
704        StyleConstants.setForeground(sas, Color.red);
705        for(Iterator i = errorWords.iterator();i.hasNext();) {
706            ((Word)i.next()).addAttributes(sas);
707        }
708       
709        if (!replace) {
710            errorWords.addAll(wordList);
711        }
712        wordList.clear();
713        wordList.addAll(errorWords);
714        }
715
716    //TODO move to util??
717        public static List createWordList(String text)
718        {
719                List wordList = new ArrayList();
720                StringBuffer temp = new StringBuffer();
721                for(int i = 0;i<text.length();i++)
722                {//split text up in words
723                        char c = text.charAt(i);
724                        switch (c)
725                        {
726                                case ' ':       addWordFromTemp(temp, wordList);
727                                                        wordList.add(new Word(" "));
728                                                        temp = new StringBuffer(); break;
729                                case '\n':      addWordFromTemp(temp, wordList);
730                                                        wordList.add(new Word("\n"));
731                                                        temp = new StringBuffer(); break;
732                                case '\t':      addWordFromTemp(temp, wordList);
733                                                        wordList.add(new Word("\t"));
734                                                        temp = new StringBuffer();break;
735                                default: temp.append(c);
736                        }
737                }
738                addWordFromTemp(temp, wordList);
739                return wordList;
740        }
741       
742        private static void addWordFromTemp(StringBuffer temp, List wordList)
743        {
744                if(temp.length()>0)wordList.add(new Word(temp));
745        }
746
747        private String getPhotoExpresso(String Jid)
748        {
749                ServerExpresso JidPhoto = new ServerExpresso();
750                return JidPhoto.PhotoUid(Jid);
751        }
752       
753        private void jbInit() throws Exception
754        {
755                Color c = UIManager.getColor("TextPane.foreground");
756                txtInvoer.setForeground(c);
757                txtUitvoer.setForeground(c);
758                setResizeWeight(0.9);
759                setOrientation(JSplitPane.VERTICAL_SPLIT);
760                setBottomComponent(pnlBottom);
761                scrlInvoer.setPreferredSize(new Dimension(100, 100));
762
763                txtInvoer.addKeyListener(new java.awt.event.KeyAdapter()
764                {
765                        public void keyPressed(KeyEvent e)
766                        {
767                                txtInvoer_keyPressed(e);
768                        }
769                       
770                        public void keyReleased(KeyEvent e)
771                        {
772                                if(spell!=null)spell.keyReleased(e,txtInvoer);
773                        }
774                });
775                txtUitvoer.setEditable(false);
776                txtUitvoer.getDocument().putProperty( DefaultEditorKit.EndOfLineStringProperty, "\n" );
777                txtInvoer.getDocument().putProperty( DefaultEditorKit.EndOfLineStringProperty, "\n" );
778                addFocusListener(new FocusAdapter()
779                {
780                        public void focusGained(FocusEvent e)
781                        {
782                                txtInvoer.requestFocusInWindow();
783                        }
784                });
785
786                /**
787                 * @Author : Rodrigo Souza
788                 * @Date : 15/10/2008
789                 * @Description : Trecho de codigo abaixo ajusta as dimensoes da foto (avatar)
790                 *                                e demais paineis dentro da janela de conversa.
791                 */
792
793                pnlBottom.setLayout(borderLayout1);
794
795                JPanel text = new JPanel();
796                text.setLayout(new BoxLayout(text,BoxLayout.PAGE_AXIS));
797                text.add(pnlControl);
798                text.add(scrlInvoer);
799                pnlBottom.add(text, BorderLayout.CENTER);
800
801                /**
802                 * @Author : Alexandre Luiz Correia - alexandrecorreia@celepar.pr.gov.br
803                 * @Date : 10/09/2008
804                 * @Description : Avatar - Carrega as Photos do Ldap
805                 */
806
807                // Border
808                Border raisedetched;
809                raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
810
811                // String
812                String userJid = contactJID.toString();
813               
814                /**
815                 *  @Author : Alexandre Correia / Rodrigo Souza
816                 *  @Date : 04/03/2009
817                 *  @Description : Conecta com a classe ServerExpresso(nu.fw.jeti.util.ServerExpresso) no Expresso e passa
818                 *  a variavel userJid(Ex.: teste@nome_maquina), recebendo uma string em base64.
819                 */
820
821                String imgUser = getPhotoExpresso(userJid);
822                byte[] data = Base64.decode(imgUser);
823                ImageIcon icon = new ImageIcon(data);
824                JLabel avatar = new JLabel(icon);
825
826                avatar.setBorder(raisedetched);
827                pnlBottom.add(avatar, BorderLayout.EAST);
828
829                add(pnlBottom, JSplitPane.BOTTOM);
830                add(scrlUitvoer, JSplitPane.TOP);
831
832                scrlUitvoer.getViewport().add(txtUitvoer, null);
833                scrlInvoer.getViewport().add(txtInvoer, null);
834                scrlUitvoer.getVerticalScrollBar().getModel().addChangeListener(new ChangeListener()
835                {
836                        public void stateChanged(ChangeEvent e)
837                        {
838                                BoundedRangeModel model =(BoundedRangeModel)e.getSource();
839                                if(!model.getValueIsAdjusting())
840                                {
841                                        if(!systemScroll)
842                                        {//only update if scroll is performed by the user
843                                                if(model.getMaximum()-model.getExtent()-model.getValue()>10)
844                                                {
845                                                        scrolls=false;
846                                                }
847                                                else scrolls=true;
848                                        }
849                                        systemScroll=false;
850                                }
851                        }
852                });
853
854                setOneTouchExpandable(true);           
855                setDividerLocation(170);
856        }
857
858        public void send()
859        {
860                if (txtInvoer.getText().length()==0)return;
861                boolean sendXHTML = false;
862                XExtension html = null;
863                XExtension ownHtml = null;
864                List wordList=null;
865                if(xhtml != null)wordList = xhtml.makeWordListFromDocument();
866                if(wordList==null)wordList=createWordList(txtInvoer.getText());
867                StringBuffer temp = new StringBuffer();
868                //TODO Translator
869                //if (translator != null) translator.translate(wordList);
870               
871                for(Iterator i = wordList.iterator();i.hasNext();)
872                {
873                        temp.append(i.next());
874                }
875                String text = temp.toString();
876                if(colormessages!=null)
877                {
878                        colormessages.translate(wordList);
879                }
880                if(xhtml != null)
881                {       
882                        html = xhtml.getXHTMLExtension(wordList);
883                        //ownwordlist will be edited so make deep copy
884                        ArrayList tempList = new ArrayList();
885                        try
886                        {
887                                for(Iterator i = wordList.iterator();i.hasNext();)
888                                {
889                                        tempList.add(((Word)i.next()).clone());
890                                }
891                        }
892                        catch (CloneNotSupportedException e)
893                        {
894                                e.printStackTrace();
895                        }
896                        ownHtml = xhtml.getXHTMLExtension(tempList);
897                        sendXHTML = xhtml.sendXML();
898                }
899                Message message = null;
900                if(groupChat)
901                {       
902                        if(html!=null) message = new Message(contactJID,text ,html);
903                        else message = new Message(contactJID,text);
904                }
905                else
906                {
907                        MessageBuilder b = new MessageBuilder();
908                        b.type = "chat";
909                        b.setTo(contactJID);
910                        b.setId(backend.getIdentifier());
911                        b.thread = thread;
912                        b.addXExtension(new XMessageEvent("composing", null));
913               
914                        if(openPGP!=null && openPGP.canEncrypt(contactJID))
915                        {
916                                b.body = "This message is encrypted with openPGP";
917                                b.addXExtension(openPGP.encrypt(text,contactJID));
918                        }
919                        else
920                        {
921                                b.body = text;
922                                if(sendXHTML)b.addXExtension(html);
923                        }
924                        message =((Message) b.build());
925                        showMessage(new Message(text, contactJID, null,thread,ownHtml),new Color(156, 23, 23), "Eu ( " + nu.fw.jeti.applet.Jeti.CNNAME +" ) ");
926                }
927                backend.sendMessage(message);
928               
929                txtInvoer.getHighlighter().removeAllHighlights();
930                txtInvoer.setText("");
931                txtInvoer.requestFocus();
932                typing = false;
933        }
934       
935        public void composingID(String id)
936        {
937                composingID = id;
938        }
939
940        void txtInvoer_keyPressed(KeyEvent e)
941        {
942                /**
943                 * Author(s): Alexandre Correia / Rodrigo Souza
944                 * Date : 02/03/2009
945                 * Brief : Limpa o tempo do Javascript
946                 */
947               
948                JavaScriptServerExpresso cleanSt = new nu.fw.jeti.util.JavaScriptServerExpresso();
949                cleanSt.cleanStatus();
950               
951                if(!groupChat)
952                {
953                        if (txtInvoer.getText().length() < 2 && typing)
954                        {
955                                typing = false;
956                                if (composingID != null)
957                                {
958                                        //send not composing
959                                        backend.send(new Message(null, contactJID, null, new XMessageEvent(null, composingID)));
960                                }
961                        }
962                        else if (txtInvoer.getText().length() > 0 && !typing)
963                        {
964                                typing = true;
965                                if (composingID != null)
966                                {
967                                        //send composing
968                                         backend.send(new Message(null, contactJID, null, new XMessageEvent("composing", composingID)));
969                                }
970                        }
971                }
972                if (e.getKeyCode() == KeyEvent.VK_ENTER)
973                {
974                        if (enterSends)
975                        {
976                                if ((e.getModifiers() == InputEvent.SHIFT_MASK) || (e.getModifiers() == InputEvent.CTRL_MASK))
977                                {
978                                        Document doc = txtInvoer.getDocument();
979                                        try
980                                        {
981                                                doc.insertString(txtInvoer.getCaretPosition(), "\n", null);
982                                        }
983                                        catch (BadLocationException e3)
984                                        {e3.printStackTrace();}
985                                }
986                                else
987                                {
988                                        send();
989                                        e.consume();
990                                }
991                        }
992                        else if ((e.getModifiers() == InputEvent.SHIFT_MASK) || (e.getModifiers() == InputEvent.CTRL_MASK))
993                        {
994                                send();
995                        }
996                }
997        }       
998}
999
1000/*
1001 * Overrides for emacs
1002 * Local variables:
1003 * tab-width: 4
1004 * End:
1005 */
Note: See TracBrowser for help on using the repository browser.