aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/systray/jdic/SystrayServiceJdicImpl.java
blob: 672f1ca280495e3425a5240e64fea00a50ea902e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
/*
 * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package net.java.sip.communicator.impl.systray.jdic;

import java.awt.Toolkit;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import java.util.Timer;

import javax.swing.*;
import javax.swing.event.*;

import net.java.sip.communicator.impl.systray.*;
import net.java.sip.communicator.impl.systray.mac.*;
import net.java.sip.communicator.service.configuration.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.systray.*;
import net.java.sip.communicator.service.systray.event.*;
import net.java.sip.communicator.util.*;

import org.jdesktop.jdic.tray.*;

/**
 * The <tt>Systray</tt> provides a Icon and the associated <tt>TrayMenu</tt>
 * in the system tray using the Jdic library.
 *
 * @author Nicolas Chamouard
 * @author Yana Stamcheva
 */
public class SystrayServiceJdicImpl
    implements  SystrayService
{
    /**
     * The systray.
     */
    private SystemTray systray;

    /**
     * The icon in the system tray.
     */
    private TrayIcon trayIcon;

    /**
     * The menu that spring with a right click.
     */
    private TrayMenu menu;

    /**
     * The list of all added popup message listeners.
     */
    private Vector popupMessageListeners = new Vector();

    /**
     * List of all messages waiting to be shown.
     */
    private ArrayList messageQueue = new ArrayList();

    private Timer popupTimer = new Timer();

    /**
     * The delay between the message pop ups.
     */
    private int messageDelay = 1000;

    private int maxMessageNumber = 3;

    private SystrayMessage aggregatedMessage;
    
    /**
     * Stores the system time, when the main window was restored the last time 
     */
    private long setVisibleTime = 0;

    /**
     * The logger for this class.
     */
    private static Logger logger =
        Logger.getLogger(SystrayServiceJdicImpl.class.getName());

    /**
     * The various icons used on the systray
     */
    private ImageIcon currentIcon;
    private ImageIcon logoIcon;
    private ImageIcon logoIconOffline;
    private ImageIcon logoIconAway;
    private ImageIcon logoIconFFC;
    private ImageIcon logoIconWhite;
    private ImageIcon envelopeIcon;
    private ImageIcon envelopeIconWhite;
    
    /**
     * The dock Icons used only in Mac version
     */
    private URL dockIconOffline;
    private URL dockIconAway;
    private URL dockIconFFC;
    
    private boolean initialized = false;

    /**
     * Creates an instance of <tt>Systray</tt>.
     */
    public SystrayServiceJdicImpl()
    {
        try
        {
            systray = SystemTray.getDefaultSystemTray();
        }
        catch (Throwable e)
        {
            logger.error("Failed to create a systray!", e);
        }

        if(systray != null)
        {
            this.initSystray();

            SystrayActivator.getUIService().setExitOnMainWindowClose(false);
        }
    }

    /**
     * Initializes the systray icon and related listeners.
     */
    private void initSystray()
    {
        popupTimer.scheduleAtFixedRate(new ShowPopupTask(), 0, messageDelay);

        // Get the system's double click speed
        Object o = Toolkit.getDefaultToolkit().getDesktopProperty(
                "awt.multiClickInterval");
        final int doubleClickSpeed = (o instanceof Integer ? ((Integer) o)
                .intValue() : 500);

        menu = new TrayMenu(this);

        String osName = System.getProperty("os.name");
        // If we're running under Windows, we use a special icon without
        // background.
        if (osName.startsWith("Windows"))
        {
            logoIcon = Resources.getImage("trayIconWindows");
            logoIconOffline = Resources.getImage("trayIconWindowsOffline");
            logoIconAway = Resources.getImage("trayIconWindowsAway");
            logoIconFFC = Resources.getImage("trayIconWindowsFFC");
            envelopeIcon = Resources.getImage("messageIconWindows");
        }
        // If we're running under MacOSX, we use a special black and 
        // white icons without background.
        else if (osName.startsWith("Mac OS X"))
        {
            logoIcon = Resources.getImage("trayIconMacOSX");
            logoIconWhite = Resources.getImage("trayIconMacOSXWhite");
            envelopeIcon = Resources.getImage("messageIconMacOSX");
            envelopeIconWhite = Resources.getImage("messageIconMacOSXWhite");
        }
        else
        {
            logoIcon = Resources.getImage("trayIcon");
            logoIconOffline = Resources.getImage("trayIconOffline");
            logoIconAway = Resources.getImage("trayIconAway");
            logoIconFFC = Resources.getImage("trayIconFFC");
            envelopeIcon = Resources.getImage("messageIcon");
        }

        if (!osName.startsWith("Mac OS X"))
        {
            // default to set offline , if any protocols become 
            // online will set it to online
            currentIcon = logoIconOffline;
        }
        else
            currentIcon = logoIcon;
            
        trayIcon = new TrayIcon(currentIcon,
                                Resources.getApplicationString("applicationName"),
                                menu);

        trayIcon.setIconAutoSize(true);
        
        if (osName.startsWith("Mac OS X"))
        {
            // init dock Icons
            dockIconOffline = Resources.getImageURL("dockIconOffline");
            dockIconAway = Resources.getImageURL("dockIconAway");
            dockIconFFC = Resources.getImageURL("dockIconFFC");
        }

        //Show/hide the contact list when user clicks on the systray.
        trayIcon.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                long currentTime = System.currentTimeMillis();
                UIService uiService = SystrayActivator.getUIService();

                boolean isVisible;

                isVisible = ! uiService.isVisible();
                if (isVisible) {
                    setVisibleTime = currentTime;
                }
                else if (currentTime < (setVisibleTime + doubleClickSpeed)) 
                {
                    // Do nothing. the last restore is less than 2 seconds, so it is very
                    // likely, that the user made a double click. prevent the main window
                    // from opening and immediately closing again.
                    return;
                }

                uiService.setVisible(isVisible);

                ConfigurationService configService
                    = SystrayActivator.getConfigurationService();

                configService.setProperty(
                        "net.java.sip.communicator.impl.systray.showApplication",
                        Boolean.toString(isVisible));
            }
        });

        // Change the MacOSX icon with the white one when the popup 
        // menu appears
        if (osName.startsWith("Mac OS X"))
        {
            menu.addPopupMenuListener(new PopupMenuListener()
            {
                public void popupMenuWillBecomeVisible(PopupMenuEvent e)
                {
                    if (currentIcon == envelopeIcon)
                    {
                        trayIcon.setIcon(envelopeIconWhite);
                        currentIcon = envelopeIconWhite;
                    }
                    else
                    {
                        trayIcon.setIcon(logoIconWhite);
                        currentIcon = logoIconWhite;                        
                    }
                }

                public void popupMenuWillBecomeInvisible(PopupMenuEvent e) 
                {
                    if (currentIcon == envelopeIconWhite)
                    {
                        trayIcon.setIcon(envelopeIcon);
                        currentIcon = envelopeIcon;
                    }
                    else
                    {
                        trayIcon.setIcon(logoIcon);
                        currentIcon = logoIcon;
                    }
                }
        
                public void popupMenuCanceled(PopupMenuEvent e) 
                {
                    popupMenuWillBecomeInvisible(e);
                } 
            });
        }

        //Notify all interested listener that user has clicked on the systray
        //popup message.
        trayIcon.addBalloonActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                UIService uiService = SystrayActivator.getUIService();

                firePopupMessageEvent(e.getSource());

                ExportedWindow chatWindow
                    = uiService.getExportedWindow(ExportedWindow.CHAT_WINDOW);

                if(chatWindow != null && chatWindow.isVisible())
                {
                    chatWindow.bringToFront();
                }
            }
        });

        systray.addTrayIcon(trayIcon);

        initialized = true;
    }

    /**
     * Saves the last status for all accounts. This information is used
     * on logging. Each time user logs in he's logged with the same status
     * as he was the last time before closing the application.
     * 
     * @param protocolProvider  the protocol provider for which we save the 
     * last selected status
     * @param statusName the status name to save
     */
    public void saveStatusInformation(
            ProtocolProviderService protocolProvider,
            String statusName)
    {
        ConfigurationService configService
            = SystrayActivator.getConfigurationService();

        if(configService != null)
        {
            String prefix = "net.java.sip.communicator.impl.gui.accounts";

            List accounts = configService
                    .getPropertyNamesByPrefix(prefix, true);

            boolean savedAccount = false;
            Iterator accountsIter = accounts.iterator();

            while(accountsIter.hasNext()) {
                String accountRootPropName
                    = (String) accountsIter.next();

                String accountUID
                    = configService.getString(accountRootPropName);

                if(accountUID.equals(protocolProvider
                        .getAccountID().getAccountUniqueID())) {

                    configService.setProperty(
                            accountRootPropName + ".lastAccountStatus",
                            statusName);

                    savedAccount = true;
                }
            }

            if(!savedAccount) {
                String accNodeName
                    = "acc" + Long.toString(System.currentTimeMillis());

                String accountPackage
                    = "net.java.sip.communicator.impl.gui.accounts."
                            + accNodeName;

                configService.setProperty(accountPackage,
                        protocolProvider.getAccountID().getAccountUniqueID());

                configService.setProperty(
                        accountPackage+".lastAccountStatus",
                        statusName);
            }
        }
    }

    /**
     * Implements the <tt>SystratService.showPopupMessage</tt> method. Shows
     * a pop up message, above the Systray icon, which has the given title,
     * message content and message type.
     * 
     * @param title the title of the message
     * @param messageContent the content text
     * @param messageType the type of the message 
     */
    public void showPopupMessage(   String title,
                                    String messageContent,
                                    int messageType)
    {
        if(!checkInitialized())
            return;
        
        int trayMsgType = TrayIcon.NONE_MESSAGE_TYPE;

        if (messageType == SystrayService.ERROR_MESSAGE_TYPE)
            trayMsgType = TrayIcon.ERROR_MESSAGE_TYPE;
        else if (messageType == SystrayService.INFORMATION_MESSAGE_TYPE)
            trayMsgType = TrayIcon.INFO_MESSAGE_TYPE;
        else if (messageType == SystrayService.WARNING_MESSAGE_TYPE)
            trayMsgType = TrayIcon.WARNING_MESSAGE_TYPE;

        // remove eventual html code before showing the popup message
        messageContent = messageContent.replaceAll("</?\\w++[^>]*+>", "");

        if(messageContent.length() > 40)
            messageContent = messageContent.substring(0, 40).concat("...");

        messageQueue.add(new SystrayMessage(title, messageContent, trayMsgType));
    }

    /**
     * Implements the <tt>SystrayService.addPopupMessageListener</tt> method.
     * 
     * @param listener the listener to add
     */
    public void addPopupMessageListener(SystrayPopupMessageListener listener)
    {
        synchronized (popupMessageListeners)
        {
            this.popupMessageListeners.add(listener);
        }
    }

    /**
     * Implements the <tt>SystrayService.removePopupMessageListener</tt> method.
     * 
     * @param listener the listener to remove
     */
    public void removePopupMessageListener(SystrayPopupMessageListener listener)
    {
        synchronized (popupMessageListeners)
        {
            this.popupMessageListeners.remove(listener);
        }
    }

    /**
     * Notifies all interested listeners that a <tt>SystrayPopupMessageEvent</tt>
     * has occured.
     * 
     * @param sourceObject the source of this event
     */
    private void firePopupMessageEvent(Object sourceObject)
    {
        SystrayPopupMessageEvent evt
            = new SystrayPopupMessageEvent(sourceObject);

        logger.trace("Will dispatch the following systray msg event: " + evt);

        Iterator listeners = null;
        synchronized (popupMessageListeners)
        {
            listeners = new ArrayList(popupMessageListeners).iterator();
        }

        while (listeners.hasNext())
        {
            SystrayPopupMessageListener listener
                = (SystrayPopupMessageListener) listeners.next();

            listener.popupMessageClicked(evt);
        }
    }

    /**
     * Sets a new Systray icon.
     * 
     * @param imageType the type of the image to set.
     */
    public void setSystrayIcon(int imageType)
    {
        if(!checkInitialized())
            return;
        
        String osName = System.getProperty("os.name");
        
        ImageIcon toChangeSystrayIcon = null;

        if (imageType == SystrayService.SC_IMG_TYPE)
        {
            if (osName.startsWith("Mac OS X") && this.menu.isVisible())
            {
                toChangeSystrayIcon = logoIconWhite;
            }
            else
            {
                toChangeSystrayIcon = logoIcon;
            }
        }
        else if (imageType == SystrayService.SC_IMG_OFFLINE_TYPE)
        {
            if (!osName.startsWith("Mac OS X"))
            {
                toChangeSystrayIcon = logoIconOffline;
            }
        }
        else if (imageType == SystrayService.SC_IMG_AWAY_TYPE)
        {
            if (!osName.startsWith("Mac OS X"))
            {
                toChangeSystrayIcon = logoIconAway;
            }
        }
        else if (imageType == SystrayService.SC_IMG_FFC_TYPE)
        {
            if (!osName.startsWith("Mac OS X"))
            {
                toChangeSystrayIcon = logoIconFFC;
            }
        }
        else if (imageType == SystrayService.ENVELOPE_IMG_TYPE)
        {
            if (osName.startsWith("Mac OS X") && this.menu.isVisible())
            {
                toChangeSystrayIcon = envelopeIconWhite;
            }
            else
            {
                toChangeSystrayIcon = envelopeIcon;
            }
        }
        
        if(toChangeSystrayIcon != null)
        {
            this.trayIcon.setIcon(toChangeSystrayIcon);
            this.currentIcon = toChangeSystrayIcon;
        }
        
        if (osName.startsWith("Mac OS X"))
        {
            URL toChangeDockIcon = null;
            switch(imageType)
            {
                case SystrayService.SC_IMG_TYPE:
                    // online will restore the original image
                    break;
                case SystrayService.SC_IMG_OFFLINE_TYPE :
                    toChangeDockIcon = dockIconOffline; break;
                case SystrayService.SC_IMG_AWAY_TYPE :
                    toChangeDockIcon = dockIconAway; break;
                case SystrayService.SC_IMG_FFC_TYPE :
                    toChangeDockIcon = dockIconFFC; break;
            }
            
            try
            {
                if(toChangeDockIcon != null)
                {
                    Dock.setDockTileImage(toChangeDockIcon);
                }
                else
                    Dock.restoreDockTileImage();
            }
            catch (Exception e)
            {
                logger.error("failed to change dock icon", e);
            }
        }
    }
    
    private boolean checkInitialized()
    {
        if(!initialized)
        {
            logger.error("Systray not init");
            return false;
        }
        else
            return true;
    }
    
    /**
     * Shows the oldest message in the message queue and then removes it from
     * the queue.
     */
    private class ShowPopupTask extends TimerTask
    {
        public void run()
        {
            if(messageQueue.isEmpty())
                return;

            int messageNumber = messageQueue.size();

            SystrayMessage msg = (SystrayMessage) messageQueue.get(0);

            if(messageNumber > maxMessageNumber)
            {
                messageQueue.clear();

                if(aggregatedMessage != null)
                {
                    aggregatedMessage
                        .addAggregatedMessageNumber(messageNumber);
                }
                else
                {
                    String messageContent = msg.getMessageContent();

                    if(!messageContent.endsWith("..."))
                        messageContent.concat("...");

                    aggregatedMessage = new SystrayMessage(
                        "Messages start by: " + messageContent,
                        messageNumber);
                }

                messageQueue.add(aggregatedMessage);
            }
            else
            {
                trayIcon.displayMessage(msg.getTitle(),
                                    msg.getMessageContent(),
                                    msg.getMessageType());

                messageQueue.remove(0);

                if(msg.equals(aggregatedMessage))
                    aggregatedMessage = null;
            }
        }
    }

    /**
     * Represents a systray message.
     */
    private class SystrayMessage
    {
        private String title;
        private String messageContent;
        private int messageType;
        private int aggregatedMessageNumber;

        /**
         * Creates an instance of <tt>SystrayMessage</tt> by specifying the
         * message <tt>title</tt>, the content of the message and the type of
         * the message.
         * 
         * @param title the title of the message
         * @param messageContent the content of the message
         * @param messageType the type of the message
         */
        public SystrayMessage(  String title,
                                String messageContent,
                                int messageType)
        {
            this.title = title;
            this.messageContent = messageContent;
            this.messageType = messageType;
        }

        /**
         * Creates an instance of <tt>SystrayMessage</tt> by specifying the
         * message <tt>title</tt>, the content of the message, the type of
         * the message and the number of messages that this message has
         * aggregated.
         * 
         * @param messageContent the content of the message
         * @param aggregatedMessageNumber the number of messages that this
         * message has aggregated
         */
        public SystrayMessage(  String messageContent,
                                int aggregatedMessageNumber)
        {
            this.aggregatedMessageNumber = aggregatedMessageNumber;

            this.title = "You have received "
                            + aggregatedMessageNumber
                            + " new messages.";

            this.messageContent = messageContent;
            this.messageType = TrayIcon.INFO_MESSAGE_TYPE;
        }

        /**
         * Returns the title of the message.
         * 
         * @return the title of the message
         */
        public String getTitle()
        {
            return title;
        }

        /**
         * Returns the message content.
         * 
         * @return the message content
         */
        public String getMessageContent()
        {
            return messageContent;
        }

        /**
         * Returns the message type.
         * 
         * @return the message type
         */
        public int getMessageType()
        {
            return messageType;
        }

        /**
         * Returns the number of aggregated messages this message represents.
         * 
         * @return the number of aggregated messages this message represents.
         */
        public int getAggregatedMessageNumber()
        {
            return aggregatedMessageNumber;
        }

        /**
         * Adds the given number of messages to the number of aggregated
         * messages contained in this message.
         * 
         * @param messageNumber the number of messages to add to the number of
         * aggregated messages contained in this message
         */
        public void addAggregatedMessageNumber(int messageNumber)
        {
            this.aggregatedMessageNumber += messageNumber;

            this.title = "You have received " + aggregatedMessageNumber
                + " new messages.";
        }
    }
}