aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/osdependent/jdic/SystrayServiceJdicImpl.java
blob: 3fa31a438a6f9b39e8f7126ccc25068cf64b1055 (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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
/*
 * Jitsi, 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.osdependent.jdic;

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import java.util.List;

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

import net.java.sip.communicator.impl.osdependent.*;
import net.java.sip.communicator.impl.osdependent.SystemTray;
import net.java.sip.communicator.impl.osdependent.TrayIcon;
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.Logger;

import org.jitsi.service.configuration.*;
import org.jitsi.util.*;
import org.osgi.framework.*;

import com.apple.eawt.*;

/**
 * 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
 * @author Lubomir Marinov
 * @author Symphorien Wanko
 */
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 Object menu;

    /**
     * The popup handler currently used to show popup messages
     */
    private PopupMessageHandler activePopupHandler;

    /**
     * A set of usable <tt>PopupMessageHandler</tt>
     */
    private final Hashtable<String, PopupMessageHandler> popupHandlerSet =
        new Hashtable<String, PopupMessageHandler>();

    /**
     * A reference of the <tt>ConfigurationService</tt> obtained from the
     * <tt>SystrayServiceActivator</tt>
     */
    private final ConfigurationService configService = OsDependentActivator.
        getConfigurationService();

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

    /**
     * The various icons used on the systray
     */
    private ImageIcon currentIcon;

    private ImageIcon logoIcon;

    private ImageIcon logoIconOffline;

    private ImageIcon logoIconAway;

    private ImageIcon logoIconFFC;

    private ImageIcon logoIconDND;

    private ImageIcon logoIconWhite;

    private ImageIcon envelopeIcon;

    private ImageIcon envelopeIconWhite;

    /**
     * The dock Icons used only in Mac version
     */
    private URL dockIconOnline;
    
    private URL dockIconOffline;

    private URL dockIconAway;

    private URL dockIconFFC;

    private URL dockIconDND;

    private Image originalDockImage = null;

    private boolean initialized = false;

    /**
     * the listener we will use for popup message event (clicks on the popup)
     */
    private final SystrayPopupMessageListener popupMessageListener =
        new SystrayPopupMessageListenerImpl();

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

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

            UIService ui = OsDependentActivator.getUIService();
            if (ui != null)
                ui.setExitOnMainWindowClose(false);
        }
    }

    /**
     * Initializes the systray icon and related listeners.
     */
    private void initSystray()
    {
        if(OsDependentActivator.getUIService() == null)
            return;

        menu = TrayMenuFactory.createTrayMenu(this, systray.isSwing());

        boolean isMac = OSUtils.IS_MAC;

        // If we're running under Windows, we use a special icon without
        // background.
        if (OSUtils.IS_WINDOWS)
        {
            logoIcon = Resources.getImage("service.systray.TRAY_ICON_WINDOWS");
            logoIconOffline = Resources.getImage(
                "service.systray.TRAY_ICON_WINDOWS_OFFLINE");
            logoIconAway = Resources.getImage(
                "service.systray.TRAY_ICON_WINDOWS_AWAY");
            logoIconFFC = Resources.getImage(
                "service.systray.TRAY_ICON_WINDOWS_FFC");
            logoIconDND = Resources.getImage(
                "service.systray.TRAY_ICON_WINDOWS_DND");
            envelopeIcon = Resources.getImage(
                "service.systray.MESSAGE_ICON_WINDOWS");
        } // If we're running under MacOSX, we use a special black and
        // white icons without background.
        else if (isMac)
        {
            logoIcon = Resources.getImage("service.systray.TRAY_ICON_MACOSX");
            logoIconWhite = Resources.getImage(
                "service.systray.TRAY_ICON_MACOSX_WHITE");
            envelopeIcon = Resources.getImage(
                "service.systray.MESSAGE_ICON_MACOSX");
            envelopeIconWhite = Resources.getImage(
                "service.systray.MESSAGE_ICON_MACOSX_WHITE");
        }
        else
        {
            logoIcon = Resources.getImage("service.systray.TRAY_ICON");
            logoIconOffline = Resources.getImage(
                "service.systray.TRAY_ICON_OFFLINE");
            logoIconAway = Resources.getImage("service.systray.TRAY_ICON_AWAY");
            logoIconFFC = Resources.getImage("service.systray.TRAY_ICON_FFC");
            logoIconDND = Resources.getImage("service.systray.TRAY_ICON_DND");
            envelopeIcon = Resources.getImage("service.systray.MESSAGE_ICON");
        }

        /*
         * Default to set offline , if any protocols become online will set it
         * to online.
         */
        currentIcon = isMac ? logoIcon : logoIconOffline;

        trayIcon = new TrayIcon(
            currentIcon,
            Resources.getApplicationString("service.gui.APPLICATION_NAME"),
            menu);

        trayIcon.setIconAutoSize(true);

        if (isMac)
        {
            // init dock Icons
            dockIconOnline = Resources.getImageURL(
                "service.systray.DOCK_ICON_ONLINE");
            dockIconOffline = Resources.getImageURL(
                "service.systray.DOCK_ICON_OFFLINE");
            dockIconAway = Resources.getImageURL(
                "service.systray.DOCK_ICON_AWAY");
            dockIconFFC =
                    Resources.getImageURL("service.systray.DOCK_ICON_FFC");
            dockIconDND = 
                    Resources.getImageURL("service.systray.DOCK_ICON_DND");
        }

        //Show/hide the contact list when user clicks on the systray.
        trayIcon.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                UIService uiService = OsDependentActivator.getUIService();
                ExportedWindow win =
                    uiService.getExportedWindow(ExportedWindow.MAIN_WINDOW);
                boolean setIsVisible = !win.isVisible();

                uiService.setVisible(setIsVisible);
            }
        });

        // Change the MacOSX icon with the white one when the popup
        // menu appears
        if (isMac)
        {
            TrayMenuFactory.addPopupMenuListener(menu, new PopupMenuListener()
            {
                public void popupMenuWillBecomeVisible(PopupMenuEvent e)
                {
                    ImageIcon newIcon
                        = (currentIcon == envelopeIcon)
                            ? envelopeIconWhite
                            : logoIconWhite;

                    trayIcon.setIcon(newIcon);
                    currentIcon = newIcon;
                }

                public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
                {
                    ImageIcon newIcon
                        = (currentIcon == envelopeIconWhite)
                            ? envelopeIcon
                            : logoIcon;

                    getTrayIcon().setIcon(newIcon);
                    currentIcon = newIcon;
                }

                public void popupMenuCanceled(PopupMenuEvent e)
                {
                    popupMenuWillBecomeInvisible(e);
                }
            });
        }

        PopupMessageHandler pph = null;
        if (!isMac)
        {
            pph = new PopupMessageHandlerTrayIconImpl(trayIcon);
            popupHandlerSet.put(pph.getClass().getName(), pph);
            OsDependentActivator.bundleContext.registerService(
                PopupMessageHandler.class.getName(),
                pph, null);
        }
        try
        {
            OsDependentActivator.bundleContext.addServiceListener(
                new ServiceListenerImpl(),
                "(objectclass=" + PopupMessageHandler.class.getName() + ")");
        }
        catch (Exception e)
        {
            logger.warn(e);
        }

        // now we look if some handler has been registered before we start
        // to listen
        ServiceReference[] handlerRefs = null;
        try
        {
            handlerRefs = OsDependentActivator.bundleContext.getServiceReferences(
                PopupMessageHandler.class.getName(),
                null);
        }
        catch (InvalidSyntaxException ex)
        {
            logger.error("Error while retrieving service refs", ex);
        }
        if (handlerRefs != null)
        {
            String configuredHandler = (String) configService.getProperty(
                "systray.POPUP_HANDLER");
            for (int i = 0; i < handlerRefs.length; i++)
            {
                PopupMessageHandler handler =
                    (PopupMessageHandler) OsDependentActivator.bundleContext.
                    getService(handlerRefs[i]);
                String handlerName = handler.getClass().getName();
                if (!popupHandlerSet.containsKey(handlerName))
                {
                    popupHandlerSet.put(handlerName, handler);
                    if (logger.isInfoEnabled())
                        logger.info("added the following popup handler : " +
                        handler);
                    if (configuredHandler != null && 
                        configuredHandler.equals(handler.getClass().getName()))
                    {
                        setActivePopupMessageHandler(handler);
                    }
                }
            }
            
            if (configuredHandler == null)
            {
                selectBestPopupMessageHandler();
            }
        }

        // either we have an incorrect config value or the default popup handler
        // is not yet available. we use the available popup handler and will
        // auto switch to the configured one when it will be available.
        // we will be aware of it since we listen for new registered
        // service in the bundle context.
        if (activePopupHandler == null && pph != null)
        {
            setActivePopupMessageHandler(pph);
        }

        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)
    {
        if (configService != null)
        {
            String prefix = "net.java.sip.communicator.impl.gui.accounts";

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

            boolean savedAccount = false;

            for (String accountRootPropName : accounts)
            {
                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 <tt>SystraService#showPopupMessage()</tt>
     *
     * @param popupMessage the message we will show
     */
    public void showPopupMessage(PopupMessage popupMessage)
    {
        // since popup handler could be loaded and unloader on the fly,
        // we have to check if we currently have a valid one.
        if (activePopupHandler != null)
        {
            activePopupHandler.showPopupMessage(popupMessage);
        }
    }

    /**
     * Implements the <tt>SystrayService.addPopupMessageListener</tt> method.
     *
     * @param listener the listener to add
     */
    public void addPopupMessageListener(SystrayPopupMessageListener listener)
    {
        if (activePopupHandler != null)
        {
            activePopupHandler.addPopupMessageListener(listener);
        }
    }

    /**
     * Implements the <tt>SystrayService.removePopupMessageListener</tt> method.
     *
     * @param listener the listener to remove
     */
    public void removePopupMessageListener(SystrayPopupMessageListener listener)
    {
        if (activePopupHandler != null)
        {
            activePopupHandler.removePopupMessageListener(listener);
        }
    }

    /**
     * Sets a new Systray icon.
     *
     * @param imageType the type of the image to set.
     */
    public void setSystrayIcon(int imageType)
    {
        if (!checkInitialized())
            return;

        boolean isMac = OSUtils.IS_MAC;
        ImageIcon toChangeSystrayIcon = null;

        if (imageType == SystrayService.SC_IMG_TYPE)
        {
            toChangeSystrayIcon
                = (isMac && TrayMenuFactory.isVisible(menu))
                    ? logoIconWhite
                    : logoIcon;
        }
        else if (imageType == SystrayService.SC_IMG_OFFLINE_TYPE)
        {
            if (!isMac)
                toChangeSystrayIcon = logoIconOffline;
        }
        else if (imageType == SystrayService.SC_IMG_AWAY_TYPE)
        {
            if (!isMac)
                toChangeSystrayIcon = logoIconAway;
        }
        else if (imageType == SystrayService.SC_IMG_FFC_TYPE)
        {
            if (!isMac)
                toChangeSystrayIcon = logoIconFFC;
        }
        else if (imageType == SystrayService.SC_IMG_DND_TYPE)
        {
            if (!isMac)
                toChangeSystrayIcon = logoIconDND;
        }
        else if (imageType == SystrayService.ENVELOPE_IMG_TYPE)
        {
            toChangeSystrayIcon
                = (isMac && TrayMenuFactory.isVisible(menu))
                    ? envelopeIconWhite
                    : envelopeIcon;
        }

        if (toChangeSystrayIcon != null)
        {
            this.trayIcon.setIcon(toChangeSystrayIcon);
            this.currentIcon = toChangeSystrayIcon;
        }

        if (isMac)
        {
            URL toChangeDockIcon = null;
            switch (imageType)
            {
                case SystrayService.SC_IMG_TYPE:
                    toChangeDockIcon = dockIconOnline;
                    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;
                case SystrayService.SC_IMG_DND_TYPE:
                    toChangeDockIcon = dockIconDND;
                    break;
            }

            try
            {
                if(OSUtils.IS_MAC)
                {
                    if(originalDockImage == null)
                        originalDockImage =
                            Application.getApplication().getDockIconImage();

                    if (toChangeDockIcon != null)
                    {
                        Application.getApplication().setDockIconImage(
                            Toolkit.getDefaultToolkit()
                                .getImage(toChangeDockIcon));
                    }
                    else
                    {
                        if(originalDockImage != null)
                            Application.getApplication().setDockIconImage(
                                originalDockImage);
                    }
                }
            }
            catch (Exception e)
            {
                logger.error("failed to change dock icon", e);
            }
        }
    }

    private boolean checkInitialized()
    {
        if (!initialized)
            logger.error("Systray not init");
        return initialized;
    }

    /**
     * @return the trayIcon
     */
    public TrayIcon getTrayIcon()
    {
        return trayIcon;
    }

    /**
     * Set the handler which will be used for popup message
     * @param newHandler the handler to set. providing a null handler is like
     * disabling popup.
     * @return the previously used popup handler
     */
    public PopupMessageHandler setActivePopupMessageHandler(
        PopupMessageHandler newHandler)
    {
        PopupMessageHandler oldHandler = activePopupHandler;
        if (oldHandler != null)
        {
            oldHandler.removePopupMessageListener(popupMessageListener);
        }

        if (newHandler != null)
        {
            newHandler.addPopupMessageListener(popupMessageListener);
        }
        if (logger.isInfoEnabled())
            logger.info(
            "setting the following popup handler as active : " + newHandler);
        activePopupHandler = newHandler;

        return oldHandler;
    }

    /**
     * Get the handler currently used by this implementation to popup message
     * @return the current handler
     */
    public PopupMessageHandler getActivePopupMessageHandler()
    {
        return activePopupHandler;
    }
    
    /**
     * Sets activePopupHandler to be the one with the highest preference index.
     */
    public void selectBestPopupMessageHandler()
    {
        PopupMessageHandler preferedHandler = null;
        int highestPrefIndex = 0;
        if (!popupHandlerSet.isEmpty())
        {
            Enumeration<String> keys = popupHandlerSet.keys();
            while (keys.hasMoreElements())
            {
                String handlerName = keys.nextElement();
                PopupMessageHandler h = popupHandlerSet.get(handlerName);
                if (h.getPreferenceIndex() > highestPrefIndex)
                {
                    highestPrefIndex = h.getPreferenceIndex();
                    preferedHandler = h;
                }
            }
            setActivePopupMessageHandler(preferedHandler);
        }
    }

    /** our listener for popup message click */
    private static class SystrayPopupMessageListenerImpl
        implements SystrayPopupMessageListener
    {

        /**
         * Handles a user click on a systray popup message. If the
         * popup notification was the result of an incoming message from a
         * contact, the chat window with that contact will be opened if not already,
         * and brought to front.
         *
         * @param evt the event triggered when user clicks on a systray popup
         * message
         */
        public void popupMessageClicked(SystrayPopupMessageEvent evt)
        {
            Object o = evt.getTag();

            if (o instanceof Contact)
                OsDependentActivator.getUIService().
                    getChat((Contact) o).setChatVisible(true);
        }
    }

    /** an implementation of <tt>ServiceListener</tt> we will use */
    private class ServiceListenerImpl implements ServiceListener
    {

        /**
         * implements <tt>ServiceListener.serviceChanged</tt>
         * @param serviceEvent
         */
        public void serviceChanged(ServiceEvent serviceEvent)
        {
            try
            {
                PopupMessageHandler handler =
                    (PopupMessageHandler) OsDependentActivator.bundleContext.
                    getService(serviceEvent.getServiceReference());

                if (serviceEvent.getType() == ServiceEvent.REGISTERED)
                {
                    if (!popupHandlerSet.containsKey(
                        handler.getClass().getName()))
                    {
                        if (logger.isInfoEnabled())
                            logger.info(
                            "adding the following popup handler : " + handler);
                        popupHandlerSet.put(
                            handler.getClass().getName(), handler);
                    } else
                        logger.warn("the following popup handler has not " +
                            "been added since it is already known : " + handler);

                    String configuredHandler = (String) configService.
                        getProperty("systray.POPUP_HANDLER");

                    if (configuredHandler == null
                        && (activePopupHandler == null
                            || (handler.getPreferenceIndex()
                                > activePopupHandler.getPreferenceIndex())))
                    {
                        // The user doesn't have a preferred handler set and new 
                        // handler with better preference index has arrived, 
                        // thus setting it as active.
                        setActivePopupMessageHandler(handler);
                    }
                    if (configuredHandler != null &&
                        configuredHandler.equals(handler.getClass().getName()))
                    {
                        // The user has a preferred handler set and it just
                        // became available, thus setting it as active
                        setActivePopupMessageHandler(handler);
                    }
                } else if (serviceEvent.getType() == ServiceEvent.UNREGISTERING)
                {
                    if (logger.isInfoEnabled())
                        logger.info(
                        "removing the following popup handler : " + handler);
                    popupHandlerSet.remove(handler.getClass().getName());
                    if (activePopupHandler == handler)
                    {
                        activePopupHandler.removePopupMessageListener(
                            popupMessageListener);
                        activePopupHandler = null;
                        
                        // We just lost our default handler, so we replace it
                        // with the one that has the highest preference index.
                        selectBestPopupMessageHandler();
                    }
                }
            } catch (IllegalStateException e)
            {
                if (logger.isDebugEnabled())
                    logger.debug(e);
            }
        }
    }
}