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

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