aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/gui/main/call/CallManager.java
blob: 2ffd2d693da7c383da00c2c1ecc6a350510a6549 (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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright @ 2015 Atlassian Pty Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.java.sip.communicator.impl.gui.main.call;

import java.awt.*;
import java.lang.ref.*;
import java.text.*;
import java.util.*;
import java.util.List;
import java.util.regex.*;

import javax.swing.*;

import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.main.*;
import net.java.sip.communicator.impl.gui.main.contactlist.*;
import net.java.sip.communicator.plugin.desktoputil.*;
import net.java.sip.communicator.plugin.desktoputil.transparent.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.contactsource.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.protocol.media.*;
import net.java.sip.communicator.util.*;
import net.java.sip.communicator.util.Logger;
import net.java.sip.communicator.util.account.*;

import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.codec.*;
import org.jitsi.service.neomedia.device.*;
import org.jitsi.service.neomedia.format.*;
import org.jitsi.service.resources.*;
import org.jitsi.util.*;

/**
 * The <tt>CallManager</tt> is the one that handles calls. It contains also
 * the "Call" and "Hang up" buttons panel. Here are handles incoming and
 * outgoing calls from and to the call operation set.
 *
 * @author Yana Stamcheva
 * @author Lyubomir Marinov
 * @author Boris Grozev
 */
public class CallManager
{
    /**
     * The <tt>Logger</tt> used by the <tt>CallManager</tt> class and its
     * instances for logging output.
     */
    private static final Logger logger = Logger.getLogger(CallManager.class);

    /**
     * The name of the property which indicates whether the user should be
     * warned when starting a desktop sharing session.
     */
    private static final String desktopSharingWarningProperty
        = "net.java.sip.communicator.impl.gui.main"
            + ".call.SHOW_DESKTOP_SHARING_WARNING";

    /**
     * The name of the property which indicates whether the preferred provider
     * will be used when calling UIContact (call history).
     */
    private static final String IGNORE_PREFERRED_PROVIDER_PROP
        = "net.java.sip.communicator.impl.gui.main"
            + ".call.IGNORE_PREFERRED_PROVIDER_PROP";

    /**
     * The <tt>CallPanel</tt>s opened by <tt>CallManager</tt> (because
     * <tt>CallContainer</tt> does not give access to such lists.)
     */
    private static final Map<CallConference, CallPanel> callPanels
        = new HashMap<CallConference, CallPanel>();

    /**
     * A map of active outgoing calls per <tt>UIContactImpl</tt>.
     */
    private static Map<Call, UIContactImpl> uiContactCalls;

    /**
     * The group of notifications dedicated to missed calls.
     */
    private static UINotificationGroup missedCallGroup;

    /**
     * A <tt>CallListener</tt>.
     */
    public static class GuiCallListener
        extends SwingCallListener
    {
        /**
         * Maps for incoming call handlers. The handlers needs to be created
         * in the protocol thread while their method
         * incomingCallReceivedInEventDispatchThread will be called on EDT.
         * On the protocol thread a call state changed listener is added,
         * if this is done on the EDT there is a almost no gap between incoming
         * CallEvent and call state changed when doing auto answer and we
         * end up with call answered and dialog for incoming call.
         */
        private Map<CallEvent,WeakReference<IncomingCallHandler>>
            inCallHandlers = Collections.synchronizedMap(
                new WeakHashMap<CallEvent,
                                WeakReference<IncomingCallHandler>>());

        /**
         * Delivers the <tt>CallEvent</tt> in the protocol thread.
         */
        public void incomingCallReceived(CallEvent ev)
        {
            inCallHandlers.put(
                ev,
                new WeakReference<IncomingCallHandler>(
                        new IncomingCallHandler(ev.getSourceCall())));

            super.incomingCallReceived(ev);
        }

        /**
         * Implements {@link CallListener#incomingCallReceived(CallEvent)}. When
         * a call is received, creates a <tt>ReceivedCallDialog</tt> and plays
         * the ring phone sound to the user.
         *
         * @param ev the <tt>CallEvent</tt>
         */
        @Override
        public void incomingCallReceivedInEventDispatchThread(CallEvent ev)
        {
            WeakReference<IncomingCallHandler> ihRef
                = inCallHandlers.remove(ev);

            if(ihRef != null)
            {
                ihRef.get().incomingCallReceivedInEventDispatchThread(ev);
            }
        }

        /**
         * Implements CallListener.callEnded. Stops sounds that are playing at
         * the moment if there're any. Removes the <tt>CallPanel</tt> and
         * disables the hang-up button.
         *
         * @param ev the <tt>CallEvent</tt> which specifies the <tt>Call</tt>
         * that has ended
         */
        @Override
        public void callEndedInEventDispatchThread(CallEvent ev)
        {
            CallConference callConference = ev.getCallConference();

            closeCallContainerIfNotNecessary(callConference);

            /*
             * Notify the existing CallPanels about the CallEvent (in case
             * they need to update their UI, for example).
             */
            forwardCallEventToCallPanels(ev);

            // If we're currently in the call history view, refresh
            // it.
            TreeContactList contactList
                = GuiActivator.getContactList();

            if (contactList.getCurrentFilter().equals(
                    TreeContactList.historyFilter))
            {
                contactList.applyFilter(
                        TreeContactList.historyFilter);
            }
        }

        /**
         * Creates and opens a call dialog. Implements
         * {@link CallListener#outgoingCallCreated(CallEvent)}.
         *
         * @param ev the <tt>CallEvent</tt>
         */
        @Override
        public void outgoingCallCreatedInEventDispatchThread(CallEvent ev)
        {
            Call sourceCall = ev.getSourceCall();

            openCallContainerIfNecessary(sourceCall);

            /*
             * Notify the existing CallPanels about the CallEvent (in case they
             * need to update their UI, for example).
             */
            forwardCallEventToCallPanels(ev);
        }
    }

    /**
     * Handles incoming calls. Must be created on the protocol thread while the
     * method incomingCallReceivedInEventDispatchThread is executed on the EDT.
     */
    private static class IncomingCallHandler
        extends CallChangeAdapter
    {
        /**
         * The dialog shown
         */
        private ReceivedCallDialog receivedCallDialog;

        /**
         * Peer name.
         */
        private String peerName;

        /**
         * The time of the incoming call.
         */
        private long callTime;

        /**
         * Construct
         * @param sourceCall
         */
        IncomingCallHandler(Call sourceCall)
        {
            Iterator<? extends CallPeer> peerIter = sourceCall.getCallPeers();

            if(!peerIter.hasNext())
            {
                return;
            }

            peerName = peerIter.next().getDisplayName();
            callTime = System.currentTimeMillis();

            sourceCall.addCallChangeListener(this);
        }

        /**
         * State has changed.
         * @param ev
         */
        @Override
        public void callStateChanged(final CallChangeEvent ev)
        {
            if(!SwingUtilities.isEventDispatchThread())
            {
                SwingUtilities.invokeLater(
                        new Runnable()
                        {
                            public void run()
                            {
                                callStateChanged(ev);
                            }
                        });
                return;
            }
            if (!CallChangeEvent.CALL_STATE_CHANGE
                    .equals(ev.getPropertyName()))
                return;

            // When the call state changes, we ensure here that the
            // received call notification dialog is closed.
            if (receivedCallDialog != null && receivedCallDialog.isVisible())
                receivedCallDialog.setVisible(false);

            // Ensure that the CallDialog is created, because it is the
            // one that listens for CallPeers.
            Object newValue = ev.getNewValue();
            Call call = ev.getSourceCall();

            if (CallState.CALL_INITIALIZATION.equals(newValue)
                    || CallState.CALL_IN_PROGRESS.equals(newValue))
            {
                openCallContainerIfNecessary(call);
            }
            else if (CallState.CALL_ENDED.equals(newValue))
            {
                if (ev.getOldValue().equals(
                        CallState.CALL_INITIALIZATION))
                {
                    // If the call was answered elsewhere, don't mark it
                    // as missed.
                    CallPeerChangeEvent cause = ev.getCause();

                    if ((cause == null)
                            || (cause.getReasonCode()
                                    != CallPeerChangeEvent
                                            .NORMAL_CALL_CLEARING))
                    {
                        addMissedCallNotification(peerName, callTime);
                    }
                }

                call.removeCallChangeListener(this);
            }
        }

        /**
         * Executed on EDT cause will create dialog and will show it.
         * @param ev
         */
        public void incomingCallReceivedInEventDispatchThread(CallEvent ev)
        {
            Call sourceCall = ev.getSourceCall();
            boolean isVideoCall
                = ev.isVideoCall()
                    && ConfigurationUtils.hasEnabledVideoFormat(
                            sourceCall.getProtocolProvider());
            receivedCallDialog = new ReceivedCallDialog(
                sourceCall,
                isVideoCall,
                (CallManager.getInProgressCalls().size() > 0),
                ev.isDesktopStreaming());

            receivedCallDialog.setVisible(true);

            Iterator<? extends CallPeer> peerIter = sourceCall.getCallPeers();

            if(!peerIter.hasNext())
            {
                if (receivedCallDialog.isVisible())
                    receivedCallDialog.setVisible(false);
                return;
            }

            /*
             * Notify the existing CallPanels about the CallEvent (in case they
             * need to update their UI, for example).
             */
            forwardCallEventToCallPanels(ev);
        }
    }

    /**
     * Answers the given call.
     *
     * @param call the call to answer
     */
    public static void answerCall(Call call)
    {
        answerCall(call, null, false /* without video */);
    }

    /**
     * Answers a specific <tt>Call</tt> with or without video and, optionally,
     * does that in a telephony conference with an existing <tt>Call</tt>.
     *
     * @param call
     * @param existingCall
     * @param video
     */
    private static void answerCall(Call call, Call existingCall, boolean video)
    {
        if (existingCall == null)
            openCallContainerIfNecessary(call);

        new AnswerCallThread(call, existingCall, video).start();
    }

    /**
     * Answers the given call in an existing call. It will end up with a
     * conference call.
     *
     * @param call the call to answer
     */
    public static void answerCallInFirstExistingCall(Call call)
    {
        // Find the first existing call.
        Iterator<Call> existingCallIter = getInProgressCalls().iterator();
        Call existingCall
            = existingCallIter.hasNext() ? existingCallIter.next() : null;

        answerCall(call, existingCall, false /* without video */);
    }

    /**
     * Merges specific existing <tt>Call</tt>s into a specific telephony
     * conference.
     *
     * @param conference the conference
     * @param calls list of calls
     */
    public static void mergeExistingCalls(
            CallConference conference,
            Collection<Call> calls)
    {
        new MergeExistingCalls(conference, calls).start();
    }

    /**
     * Answers the given call with video.
     *
     * @param call the call to answer
     */
    public static void answerVideoCall(Call call)
    {
        answerCall(call, null, true /* with video */);
    }

    /**
     * Hang ups the given call.
     *
     * @param call the call to hang up
     */
    public static void hangupCall(Call call)
    {
        new HangupCallThread(call).start();
    }

    /**
     * Hang ups the given <tt>callPeer</tt>.
     *
     * @param peer the <tt>CallPeer</tt> to hang up
     */
    public static void hangupCallPeer(CallPeer peer)
    {
        new HangupCallThread(peer).start();
    }

    /**
     * Asynchronously hangs up the <tt>Call</tt>s participating in a specific
     * <tt>CallConference</tt>.
     *
     * @param conference the <tt>CallConference</tt> whose participating
     * <tt>Call</tt>s are to be hanged up
     */
    public static void hangupCalls(CallConference conference)
    {
        new HangupCallThread(conference).start();
    }

    /**
     * Creates a call to the contact represented by the given string.
     *
     * @param protocolProvider the protocol provider to which this call belongs.
     * @param contact the contact to call to
     */
    public static void createCall(  ProtocolProviderService protocolProvider,
                                    String contact)
    {
        new CreateCallThread(protocolProvider, contact, false /* audio-only */)
            .start();
    }

    /**
     * Creates a call to the contact represented by the given string.
     *
     * @param protocolProvider the protocol provider to which this call belongs.
     * @param contact the contact to call to
     * @param uiContact the meta contact we're calling
     */
    public static void createCall(  ProtocolProviderService protocolProvider,
                                    String contact,
                                    UIContactImpl uiContact)
    {
        new CreateCallThread(protocolProvider, null, null, uiContact,
            contact, null, null, false /* audio-only */).start();
    }

    /**
     * Creates a video call to the contact represented by the given string.
     *
     * @param protocolProvider the protocol provider to which this call belongs.
     * @param contact the contact to call to
     */
    public static void createVideoCall(ProtocolProviderService protocolProvider,
                                        String contact)
    {
        new CreateCallThread(protocolProvider, contact, true /* video */)
            .start();
    }

    /**
     * Creates a video call to the contact represented by the given string.
     *
     * @param protocolProvider the protocol provider to which this call belongs.
     * @param contact the contact to call to
     * @param uiContact the <tt>UIContactImpl</tt> we're calling
     */
    public static void createVideoCall( ProtocolProviderService protocolProvider,
                                        String contact,
                                        UIContactImpl uiContact)
    {
        new CreateCallThread(protocolProvider, null, null, uiContact,
            contact, null, null, true /* video */).start();
    }

    /**
     * Enables/disables local video for a specific <tt>Call</tt>.
     *
     * @param call the <tt>Call</tt> to enable/disable to local video for
     * @param enable <tt>true</tt> to enable the local video; otherwise,
     * <tt>false</tt>
     */
    public static void enableLocalVideo(Call call, boolean enable)
    {
        new EnableLocalVideoThread(call, enable).start();
    }

    /**
     * Indicates if the desktop sharing is currently enabled for the given
     * <tt>call</tt>.
     *
     * @param call the <tt>Call</tt>, for which we would to check if the desktop
     * sharing is currently enabled
     * @return <tt>true</tt> if the desktop sharing is currently enabled for the
     * given <tt>call</tt>, <tt>false</tt> otherwise
     */
    public static boolean isLocalVideoEnabled(Call call)
    {
        OperationSetVideoTelephony telephony
            = call.getProtocolProvider().getOperationSet(
                    OperationSetVideoTelephony.class);

        return (telephony != null) && telephony.isLocalVideoAllowed(call);
    }

    /**
     * Creates a desktop sharing call to the contact represented by the given
     * string.
     *
     * @param protocolProvider the protocol provider to which this call belongs.
     * @param contact the contact to call to
     * @param uiContact the <tt>UIContactImpl</tt> we're calling
     */
    private static void createDesktopSharing(
            ProtocolProviderService protocolProvider,
            String contact,
            UIContactImpl uiContact)
    {
        // If the user presses cancel on the desktop sharing warning then we
        // have nothing more to do here.
        if (!showDesktopSharingWarning())
            return;

        MediaService mediaService = GuiActivator.getMediaService();
        List<MediaDevice> desktopDevices
            = mediaService.getDevices(MediaType.VIDEO, MediaUseCase.DESKTOP);
        int deviceNumber = desktopDevices.size();

        if (deviceNumber == 1)
        {
            createDesktopSharing(
                    protocolProvider,
                    contact,
                    uiContact,
                    desktopDevices.get(0),
                    true);
        }
        else if (deviceNumber > 1)
        {
            SelectScreenDialog selectDialog
                = new SelectScreenDialog(desktopDevices);

            selectDialog.setVisible(true);
            if (selectDialog.getSelectedDevice() != null)
                createDesktopSharing(
                        protocolProvider,
                        contact,
                        uiContact,
                        selectDialog.getSelectedDevice(),
                        true);
        }
    }

    /**
     * Creates a region desktop sharing through the given
     * <tt>protocolProvider</tt> with the given <tt>contact</tt>.
     *
     * @param protocolProvider the <tt>ProtocolProviderService</tt>, through
     * which the sharing session will be established
     * @param contact the address of the contact recipient
     * @param uiContact the <tt>UIContactImpl</tt> we're calling
     */
    private static void createRegionDesktopSharing(
                                    ProtocolProviderService protocolProvider,
                                    String contact,
                                    UIContactImpl uiContact)
    {
        if (showDesktopSharingWarning())
        {
            TransparentFrame frame = DesktopSharingFrame
                .createTransparentFrame(
                    protocolProvider, contact, uiContact, true);

            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }

    /**
     * Creates a desktop sharing call to the contact represented by the given
     * string.
     *
     * @param protocolProvider the protocol provider to which this call belongs.
     * @param contact the contact to call to
     * @param uiContact the <tt>MetaContact</tt> we're calling
     * @param x the x coordinate of the shared region
     * @param y the y coordinated of the shared region
     * @param width the width of the shared region
     * @param height the height of the shared region
     */
    public static void createRegionDesktopSharing(
                                    ProtocolProviderService protocolProvider,
                                    String contact,
                                    UIContactImpl uiContact,
                                    int x,
                                    int y,
                                    int width,
                                    int height)
    {
        MediaService mediaService = GuiActivator.getMediaService();

        List<MediaDevice> desktopDevices = mediaService.getDevices(
            MediaType.VIDEO, MediaUseCase.DESKTOP);

        int deviceNumber = desktopDevices.size();

        if (deviceNumber > 0)
        {
            createDesktopSharing(
                    protocolProvider,
                    contact,
                    uiContact,
                    mediaService.getMediaDeviceForPartialDesktopStreaming(
                        width,
                        height,
                        x,
                        y),
                    false);
        }
    }

    /**
     * Creates a desktop sharing call to the contact represented by the given
     * string.
     *
     * @param protocolProvider the protocol provider to which this call belongs.
     * @param contact the contact to call to
     * @param uiContact the <tt>UIContactImpl</tt> we're calling
     * @param mediaDevice the media device corresponding to the screen to share
     * @param fullscreen whether we are sharing the fullscreen
     */
    private static void createDesktopSharing(
                                    ProtocolProviderService protocolProvider,
                                    String contact,
                                    UIContactImpl uiContact,
                                    MediaDevice mediaDevice,
                                    boolean fullscreen)
    {
        new CreateDesktopSharingThread( protocolProvider,
                                        contact,
                                        uiContact,
                                        mediaDevice,
                                        fullscreen).start();
    }

    /**
     * Enables the desktop sharing in an existing <tt>call</tt>.
     *
     * @param call the call for which desktop sharing should be enabled
     * @param enable indicates if the desktop sharing should be enabled or
     * disabled
     */
    public static void enableDesktopSharing(Call call, boolean enable)
    {
        if (!enable)
            enableDesktopSharing(call, null, enable);
        else if (showDesktopSharingWarning())
        {
            MediaService mediaService = GuiActivator.getMediaService();
            List<MediaDevice> desktopDevices
                = mediaService.getDevices(MediaType.VIDEO, MediaUseCase.DESKTOP);
            int deviceNumber = desktopDevices.size();

            new FullScreenShareIndicator(call);

            if (deviceNumber == 1)
                enableDesktopSharing(call, null, enable);
            else if (deviceNumber > 1)
            {
                SelectScreenDialog selectDialog
                    = new SelectScreenDialog(desktopDevices);

                selectDialog.setVisible(true);

                if (selectDialog.getSelectedDevice() != null)
                    enableDesktopSharing(
                        call, selectDialog.getSelectedDevice(), enable);
            }
        }

        // in case we switch to video, disable remote control if it was
        // enabled
        enableDesktopRemoteControl(call.getCallPeers().next(), false);
    }

    /**
     * Enables the region desktop sharing for the given call.
     *
     * @param call the call, for which the region desktop sharing should be
     * enabled
     * @param enable indicates if the desktop sharing should be enabled or
     * disabled
     */
    public static void enableRegionDesktopSharing(Call call, boolean enable)
    {
        if (!enable)
            enableDesktopSharing(call, null, enable);
        else if (showDesktopSharingWarning())
        {
            TransparentFrame frame
                = DesktopSharingFrame.createTransparentFrame(call, true);

            frame.setVisible(true);
        }
    }

    /**
     * Creates a desktop sharing call to the contact represented by the given
     * string.
     *
     * @param call the call for which desktop sharing should be enabled
     * @param x the x coordinate of the shared region
     * @param y the y coordinated of the shared region
     * @param width the width of the shared region
     * @param height the height of the shared region
     */
    public static void enableRegionDesktopSharing(
                                    Call call,
                                    int x,
                                    int y,
                                    int width,
                                    int height)
    {
        // Use the default media device corresponding to the screen to share
        MediaService mediaService = GuiActivator.getMediaService();

        List<MediaDevice> desktopDevices = mediaService.getDevices(
            MediaType.VIDEO, MediaUseCase.DESKTOP);

        int deviceNumber = desktopDevices.size();

        if (deviceNumber > 0)
        {
            boolean succeed = enableDesktopSharing(
                    call,
                    mediaService.getMediaDeviceForPartialDesktopStreaming(
                        width,
                        height,
                        x,
                        y),
                    true);
            // If the region sharing succeed, then display the frame of the
            // current region shared.
            if(succeed)
            {
                TransparentFrame frame
                    = DesktopSharingFrame.createTransparentFrame(call, false);

                frame.setVisible(true);
            }
        }

        // in case we switch to video, disable remote control if it was
        // enabled
        enableDesktopRemoteControl(call.getCallPeers().next(), false);
    }

    /**
     * Enables the desktop sharing in an existing <tt>call</tt>.
     *
     * @param call the call for which desktop sharing should be enabled
     * @param mediaDevice the media device corresponding to the screen to share
     * @param enable indicates if the desktop sharing should be enabled or
     * disabled
     *
     * @return True if the desktop sharing succeed (we are currently sharing the
     * whole or a part of the desktop). False, otherwise.
     */
    private static boolean enableDesktopSharing(Call call,
                                            MediaDevice mediaDevice,
                                            boolean enable)
    {
        OperationSetDesktopStreaming desktopOpSet
            = call.getProtocolProvider().getOperationSet(
                OperationSetDesktopStreaming.class);
        boolean enableSucceeded = false;

        // This shouldn't happen at this stage, because we disable the button
        // if the operation set isn't available.
        if (desktopOpSet != null)
        {
            // First make sure the local video button is disabled.
            if (enable && isLocalVideoEnabled(call))
                getActiveCallContainer(call).setVideoButtonSelected(false);

            try
            {
                if (mediaDevice != null)
                {
                    desktopOpSet.setLocalVideoAllowed(
                            call,
                            mediaDevice,
                            enable);
                }
                else
                    desktopOpSet.setLocalVideoAllowed(call, enable);

                enableSucceeded = true;
            }
            catch (OperationFailedException ex)
            {
                logger.error(
                        "Failed to toggle the streaming of local video.",
                        ex);
            }
        }

        return (enable && enableSucceeded);
    }

    /**
     * Indicates if the desktop sharing is currently enabled for the given
     * <tt>call</tt>.
     *
     * @param call the <tt>Call</tt>, for which we would to check if the desktop
     * sharing is currently enabled
     * @return <tt>true</tt> if the desktop sharing is currently enabled for the
     * given <tt>call</tt>, <tt>false</tt> otherwise
     */
    public static boolean isDesktopSharingEnabled(Call call)
    {
        OperationSetDesktopStreaming desktopOpSet
            = call.getProtocolProvider().getOperationSet(
                OperationSetDesktopStreaming.class);

        if (desktopOpSet != null
            && desktopOpSet.isLocalVideoAllowed(call))
            return true;

        return false;
    }

    /**
     * Indicates if the desktop sharing is currently enabled for the given
     * <tt>call</tt>.
     *
     * @param call the <tt>Call</tt>, for which we would to check if the desktop
     * sharing is currently enabled
     * @return <tt>true</tt> if the desktop sharing is currently enabled for the
     * given <tt>call</tt>, <tt>false</tt> otherwise
     */
    public static boolean isRegionDesktopSharingEnabled(Call call)
    {
        OperationSetDesktopStreaming desktopOpSet
            = call.getProtocolProvider().getOperationSet(
                OperationSetDesktopStreaming.class);

        if (desktopOpSet != null
            && desktopOpSet.isPartialStreaming(call))
            return true;

        return false;
    }

    /**
     * Enables/disables remote control when in a desktop sharing session with
     * the given <tt>callPeer</tt>.
     *
     * @param callPeer the call peer for which we enable/disable remote control
     * @param isEnable indicates if the remote control should be enabled
     */
    public static void enableDesktopRemoteControl(  CallPeer callPeer,
                                                    boolean isEnable)
    {
        OperationSetDesktopSharingServer sharingOpSet
            = callPeer.getProtocolProvider().getOperationSet(
                OperationSetDesktopSharingServer.class);

        if (sharingOpSet == null)
            return;

        if (isEnable)
            sharingOpSet.enableRemoteControl(callPeer);
        else
            sharingOpSet.disableRemoteControl(callPeer);
    }

    /**
     * Creates a call to the given call string. The given component indicates
     * where should be shown the "call via" menu if needed.
     *
     * @param callString the string to call
     * @param c the component, which indicates where should be shown the "call
     * via" menu if needed
     */
    public static void createCall(  String callString,
                                    JComponent c)
    {
        createCall(callString, c, null);
    }

    /**
     * Creates a call to the given call string. The given component indicates
     * where should be shown the "call via" menu if needed.
     *
     * @param callString the string to call
     * @param c the component, which indicates where should be shown the "call
     * via" menu if needed
     * @param l listener that is notified when the call interface has been
     * started after call was created
     */
    public static void createCall(  String callString,
                                    JComponent c,
                                    CallInterfaceListener l)
    {
        callString = callString.trim();

        // Removes special characters from phone numbers.
        if (ConfigurationUtils.isNormalizePhoneNumber()
            && !NetworkUtils.isValidIPAddress(callString))
        {
            callString = GuiActivator.getPhoneNumberI18nService()
                .normalize(callString);
        }

        List<ProtocolProviderService> telephonyProviders
            = CallManager.getTelephonyProviders();

        if (telephonyProviders.size() == 1)
        {
            CallManager.createCall(
                telephonyProviders.get(0), callString);

            if (l != null)
                l.callInterfaceStarted();
        }
        else if (telephonyProviders.size() > 1)
        {
            /*
             * Allow plugins which do not have a (Jitsi) UI to create calls by
             * automagically picking up a telephony provider.
             */
            if (c == null)
            {
                ProtocolProviderService preferredTelephonyProvider = null;

                for (ProtocolProviderService telephonyProvider
                        : telephonyProviders)
                {
                    try
                    {
                        OperationSetPresence presenceOpSet
                            = telephonyProvider.getOperationSet(
                                    OperationSetPresence.class);

                        if ((presenceOpSet != null)
                                && (presenceOpSet.findContactByID(callString)
                                        != null))
                        {
                            preferredTelephonyProvider = telephonyProvider;
                            break;
                        }
                    }
                    catch (Throwable t)
                    {
                        if (t instanceof ThreadDeath)
                            throw (ThreadDeath) t;
                    }
                }
                if (preferredTelephonyProvider == null)
                    preferredTelephonyProvider = telephonyProviders.get(0);

                CallManager.createCall(preferredTelephonyProvider, callString);
                if (l != null)
                    l.callInterfaceStarted();
            }
            else
            {
                ChooseCallAccountPopupMenu chooseAccountDialog
                    = new ChooseCallAccountPopupMenu(
                            c,
                            callString,
                            telephonyProviders,
                            l);

                chooseAccountDialog.setLocation(c.getLocation());
                chooseAccountDialog.showPopupMenu();
            }
        }
        else
        {
            ResourceManagementService resources = GuiActivator.getResources();

            new ErrorDialog(
                    null,
                    resources.getI18NString("service.gui.WARNING"),
                    resources.getI18NString(
                            "service.gui.NO_ONLINE_TELEPHONY_ACCOUNT"))
                .showDialog();
        }
    }

    /**
     * Creates a call to the given list of contacts.
     *
     * @param protocolProvider the protocol provider to which this call belongs.
     * @param callees the list of contacts to call to
     */
    public static void createConferenceCall(
            String[] callees,
            ProtocolProviderService protocolProvider)
    {
        Map<ProtocolProviderService, List<String>> crossProtocolCallees
            = new HashMap<ProtocolProviderService, List<String>>();

        crossProtocolCallees.put(protocolProvider, Arrays.asList(callees));
        createConferenceCall(crossProtocolCallees);
    }

    /**
     * Invites the given list of <tt>callees</tt> to the given conference
     * <tt>call</tt>.
     *
     * @param callees the list of contacts to invite
     * @param call the protocol provider to which this call belongs
     */
    public static void inviteToConferenceCall(String[] callees, Call call)
    {
        Map<ProtocolProviderService, List<String>> crossProtocolCallees
            = new HashMap<ProtocolProviderService, List<String>>();

        crossProtocolCallees.put(
                call.getProtocolProvider(),
                Arrays.asList(callees));
        inviteToConferenceCall(crossProtocolCallees, call);
    }

    /**
     * Invites the given list of <tt>callees</tt> to the given conference
     * <tt>call</tt>.
     *
     * @param callees the list of contacts to invite
     * @param call existing call
     */
    public static void inviteToConferenceCall(
            Map<ProtocolProviderService, List<String>> callees,
            Call call)
    {
        new InviteToConferenceCallThread(callees, call).start();
    }

    /**
     * Invites specific <tt>callees</tt> to a specific telephony conference.
     *
     * @param callees the list of contacts to invite
     * @param conference the telephony conference to invite the specified
     * <tt>callees</tt> into
     */
    public static void inviteToConferenceCall(
            Map<ProtocolProviderService, List<String>> callees,
            CallConference conference)
    {
        /*
         * InviteToConferenceCallThread takes a specific Call but actually
         * invites to the telephony conference associated with the specified
         * Call (if any). In order to not change the signature of its
         * constructor at this time, just pick up a Call participating in the
         * specified telephony conference (if any).
         */
        Call call = null;

        if (conference != null)
        {
            List<Call> calls = conference.getCalls();

            if (!calls.isEmpty())
                call = calls.get(0);
        }

        new InviteToConferenceCallThread(callees, call).start();
    }

    /**
     * Asynchronously creates a new conference <tt>Call</tt> with a specific
     * list of participants/callees.
     *
     * @param callees the list of participants/callees to invite to a
     * newly-created conference <tt>Call</tt>
     */
    public static void createConferenceCall(
        Map<ProtocolProviderService, List<String>> callees)
    {
        new InviteToConferenceCallThread(callees, null).start();
    }

    /**
     * Asynchronously creates a new video bridge conference <tt>Call</tt> with
     * a specific list of participants/callees.
     *
     * @param callProvider the <tt>ProtocolProviderService</tt> to use for
     * creating the call
     * @param callees the list of participants/callees to invite to the
     * newly-created video bridge conference <tt>Call</tt>
     */
    public static void createJitsiVideobridgeConfCall(
                                        ProtocolProviderService callProvider,
                                        String[] callees)
    {
        new InviteToConferenceBridgeThread(callProvider, callees, null).start();
    }

    /**
     * Invites the given list of <tt>callees</tt> to the given conference
     * <tt>call</tt>.
     *
     * @param callees the list of contacts to invite
     * @param call the protocol provider to which this call belongs
     */
    public static void inviteToJitsiVideobridgeConfCall(String[] callees, Call call)
    {
        new InviteToConferenceBridgeThread( call.getProtocolProvider(),
                                            callees,
                                            call).start();
    }

    /**
     * Puts on or off hold the given <tt>callPeer</tt>.
     * @param callPeer the peer to put on/off hold
     * @param isOnHold indicates the action (on hold or off hold)
     */
    public static void putOnHold(CallPeer callPeer, boolean isOnHold)
    {
        new PutOnHoldCallPeerThread(callPeer, isOnHold).start();
    }

    /**
     * Transfers the given <tt>peer</tt> to the given <tt>target</tt>.
     * @param peer the <tt>CallPeer</tt> to transfer
     * @param target the <tt>CallPeer</tt> target to transfer to
     */
    public static void transferCall(CallPeer peer, CallPeer target)
    {
        OperationSetAdvancedTelephony<?> telephony
            = peer.getCall().getProtocolProvider()
                .getOperationSet(OperationSetAdvancedTelephony.class);

        if (telephony != null)
        {
            try
            {
                telephony.transfer(peer, target);
            }
            catch (OperationFailedException ex)
            {
                logger.error("Failed to transfer " + peer.getAddress()
                    + " to " + target, ex);
            }
        }
    }

    /**
     * Transfers the given <tt>peer</tt> to the given <tt>target</tt>.
     * @param peer the <tt>CallPeer</tt> to transfer
     * @param target the target of the transfer
     */
    public static void transferCall(CallPeer peer, String target)
    {
        OperationSetAdvancedTelephony<?> telephony
            = peer.getCall().getProtocolProvider()
                .getOperationSet(OperationSetAdvancedTelephony.class);

        if (telephony != null)
        {
            try
            {
                telephony.transfer(peer, target);
            }
            catch (OperationFailedException ex)
            {
                logger.error("Failed to transfer " + peer.getAddress()
                    + " to " + target, ex);
            }
        }
    }

    /**
     * Closes the <tt>CallPanel</tt> of a specific <tt>Call</tt> if it is no
     * longer necessary (i.e. is not used by other <tt>Call</tt>s participating
     * in the same telephony conference as the specified <tt>Call</tt>.)
     *
     * @param callConference The <tt>CallConference</tt> which is to have its
     * associated <tt>CallPanel</tt>, if any
     */
    private static void closeCallContainerIfNotNecessary(
            final CallConference callConference)
    {
        CallPanel callPanel = callPanels.get(callConference);

        if (callPanel != null)
            closeCallContainerIfNotNecessary(
                callConference, callPanel.isCloseWaitAfterHangup());
    }

    /**
     * Closes the <tt>CallPanel</tt> of a specific <tt>Call</tt> if it is no
     * longer necessary (i.e. is not used by other <tt>Call</tt>s participating
     * in the same telephony conference as the specified <tt>Call</tt>.)
     *
     * @param callConference The <tt>CallConference</tt> which is to have its
     * associated <tt>CallPanel</tt>, if any, closed
     * @param wait <tt>true</tt> to set <tt>delay</tt> param of
     * {@link CallContainer#close(CallPanel, boolean)} (CallPanel)}
     */
    private static void closeCallContainerIfNotNecessary(
            final CallConference callConference,
            final boolean wait)
    {
        if (!SwingUtilities.isEventDispatchThread())
        {
            SwingUtilities.invokeLater(
                    new Runnable()
                    {
                        public void run()
                        {
                            closeCallContainerIfNotNecessary(
                                callConference,
                                wait);
                        }
                    });
            return;
        }

        /*
         * XXX The integrity of the execution of the method may be compromised
         * if it is not invoked on the AWT event dispatching thread because
         * findCallPanel and callPanels.remove must be atomically executed. The
         * uninterrupted execution (with respect to the synchronization) is
         * guaranteed by requiring all modifications to callPanels to be made on
         * the AWT event dispatching thread.
         */

        for (Iterator<Map.Entry<CallConference, CallPanel>> entryIter
                    = callPanels.entrySet().iterator();
                entryIter.hasNext();)
        {
            Map.Entry<CallConference, CallPanel> entry = entryIter.next();
            CallConference aConference = entry.getKey();
            boolean notNecessary = aConference.isEnded();

            if (notNecessary)
            {
                CallPanel aCallPanel = entry.getValue();
                CallContainer window = aCallPanel.getCallWindow();

                try
                {
                    window.close(
                            aCallPanel,
                            wait && (aConference == callConference));
                }
                finally
                {
                    /*
                     * We allow non-modifications i.e. reads of callPanels on
                     * threads other than the AWT event dispatching thread so we
                     * have to make sure that we will not cause
                     * ConcurrentModificationException.
                     */
                    synchronized (callPanels)
                    {
                        entryIter.remove();
                    }

                    aCallPanel.dispose();
                }
            }
        }
    }

    /**
     * Opens a <tt>CallPanel</tt> for a specific <tt>Call</tt> if there is none.
     * <p>
     * <b>Note</b>: The method can be called only on the AWT event dispatching
     * thread.
     * </p>
     *
     * @param call the <tt>Call</tt> to open a <tt>CallPanel</tt> for
     * @return the <tt>CallPanel</tt> associated with the <tt>Call</tt>
     * @throws RuntimeException if the method is not called on the AWT event
     * dispatching thread
     */
    private static CallPanel openCallContainerIfNecessary(Call call)
    {
        /*
         * XXX The integrity of the execution of the method may be compromised
         * if it is not invoked on the AWT event dispatching thread because
         * findCallPanel and callPanels.put must be atomically executed. The
         * uninterrupted execution (with respect to the synchronization) is
         * guaranteed by requiring all modifications to callPanels to be made on
         * the AWT event dispatching thread.
         */
        assertIsEventDispatchingThread();

        /*
         * CallPanel displays a CallConference (which may contain multiple
         * Calls.)
         */
        CallConference conference = call.getConference();
        CallPanel callPanel = findCallPanel(conference);

        if (callPanel == null)
        {
            // If we're in single-window mode, the single window is the
            // CallContainer.
            CallContainer callContainer
                = GuiActivator.getUIService().getSingleWindowContainer();

            // If we're in multi-window mode, we create the CallDialog.
            if (callContainer == null)
                callContainer = new CallDialog();

            callPanel = new CallPanel(conference, callContainer);
            callContainer.addCallPanel(callPanel);

            synchronized (callPanels)
            {
                callPanels.put(conference, callPanel);
            }
        }

        return callPanel;
    }

    /**
     * Returns a list of all currently registered telephony providers.
     * @return a list of all currently registered telephony providers
     */
    public static List<ProtocolProviderService> getTelephonyProviders()
    {
        return AccountUtils
            .getRegisteredProviders(OperationSetBasicTelephony.class);
    }

    /**
     * Returns a list of all currently registered telephony providers supporting
     * conferencing.
     *
     * @return a list of all currently registered telephony providers supporting
     * conferencing
     */
    public static List<ProtocolProviderService>
                                            getTelephonyConferencingProviders()
    {
        return AccountUtils
            .getRegisteredProviders(OperationSetTelephonyConferencing.class);
    }

    /**
     * Returns a list of all currently active calls.
     *
     * @return a list of all currently active calls
     */
    private static List<Call> getActiveCalls()
    {
        CallConference[] conferences;

        synchronized (callPanels)
        {
            Set<CallConference> keySet = callPanels.keySet();

            conferences = keySet.toArray(new CallConference[keySet.size()]);
        }

        List<Call> calls = new ArrayList<Call>();

        for (CallConference conference : conferences)
        {
            for (Call call : conference.getCalls())
            {
                if (call.getCallState() == CallState.CALL_IN_PROGRESS)
                    calls.add(call);
            }
        }
        return calls;
    }

    /**
     * Returns a collection of all currently in progress calls. A call is active
     * if it is in progress so the method merely delegates to
     *
     * @return a collection of all currently in progress calls.
     */
    public static Collection<Call> getInProgressCalls()
    {
        return getActiveCalls();
    }

    /**
     * Returns the <tt>CallContainer</tt> corresponding to the given
     * <tt>call</tt>. If the call has been finished and no active
     * <tt>CallContainer</tt> could be found it returns null.
     *
     * @param call the <tt>Call</tt>, which dialog we're looking for
     * @return the <tt>CallContainer</tt> corresponding to the given
     * <tt>call</tt>
     */
    public static CallPanel getActiveCallContainer(Call call)
    {
        return findCallPanel(call.getConference());
    }

    /**
     * A informative text to show for the peer. If display name is missing
     * return the address.
     * @param peer the peer.
     * @param listener the listener to fire change events for later resolutions
     * of display name and image, if exist.
     * @return the text contain display name.
     */
    public static String getPeerDisplayName(CallPeer peer,
                                            DetailsResolveListener listener)
    {
        String displayName = null;

        // We try to find the <tt>UIContact</tt>, to which the call was
        // created if this was an outgoing call.
        UIContactImpl uiContact
            = CallManager.getCallUIContact(peer.getCall());

        if(uiContact != null)
        {
            if(uiContact.getDescriptor() instanceof SourceContact)
            {
                // if it is source contact (history record)
                // search for cusax contact match
                Contact contact = getPeerCusaxContact(peer,
                    (SourceContact)uiContact.getDescriptor());
                if(contact != null)
                    displayName = contact.getDisplayName();
            }

            if(StringUtils.isNullOrEmpty(displayName, true))
                displayName = uiContact.getDisplayName();
        }

        // We search for a contact corresponding to this call peer and
        // try to get its display name.
        if (StringUtils.isNullOrEmpty(displayName, true)
            && peer.getContact() != null)
        {
            displayName = peer.getContact().getDisplayName();
        }

        // We try to find the an alternative peer address.
        if (StringUtils.isNullOrEmpty(displayName, true))
        {
            String imppAddress = peer.getAlternativeIMPPAddress();

            if (!StringUtils.isNullOrEmpty(imppAddress))
            {
                int protocolPartIndex = imppAddress.indexOf(":");

                imppAddress = (protocolPartIndex >= 0)
                        ? imppAddress.substring(protocolPartIndex + 1)
                        : imppAddress;

                        Collection<ProtocolProviderService> cusaxProviders
                        = AccountUtils.getRegisteredProviders(
                            OperationSetCusaxUtils.class);

                if (cusaxProviders != null && cusaxProviders.size() > 0)
                {
                    Iterator<ProtocolProviderService> iter
                        = cusaxProviders.iterator();
                    while(iter.hasNext())
                    {
                        Contact contact = getPeerContact(
                            peer,
                            iter.next(),
                            imppAddress);

                        displayName = (contact != null)
                            ? contact.getDisplayName() : null;

                        if(!StringUtils.isNullOrEmpty(displayName, true))
                            break;
                    }
                }
                else
                {
                    MetaContact metaContact
                        = getPeerMetaContact(peer, imppAddress);

                    displayName = (metaContact != null)
                                    ? metaContact.getDisplayName() : null;
                }
            }
        }

        if (StringUtils.isNullOrEmpty(displayName, true))
        {
            displayName = (!StringUtils.isNullOrEmpty
                            (peer.getDisplayName(), true))
                            ? peer.getDisplayName()
                            : peer.getAddress();

            // Try to resolve the display name
            String resolvedName = queryContactSource(displayName, listener);
            if(resolvedName != null)
            {
                displayName = resolvedName;
            }
        }

        return displayName;
    }

    /**
     * Returns the image corresponding to the given <tt>peer</tt>.
     *
     * @param peer the call peer, for which we're returning an image
     * @return the peer image
     */
    public static byte[] getPeerImage(CallPeer peer)
    {
        byte[] image = null;
        // We search for a contact corresponding to this call peer and
        // try to get its image.
        if (peer.getContact() != null)
        {
            image = getContactImage(peer.getContact());
        }

        // We try to find the <tt>UIContact</tt>, to which the call was
        // created if this was an outgoing call.
        if (image == null || image.length == 0)
        {
            UIContactImpl uiContact
                = CallManager.getCallUIContact(peer.getCall());

            if (uiContact != null)
            {
                if(uiContact.getDescriptor() instanceof SourceContact
                    && ((SourceContact)uiContact.getDescriptor())
                        .isDefaultImage())
                {
                    // if it is source contact (history record)
                    // search for cusax contact match
                    Contact contact = getPeerCusaxContact(peer,
                        (SourceContact)uiContact.getDescriptor());

                    if(contact != null)
                        image = contact.getImage();
                }
                else
                    image = uiContact.getAvatar();
            }
        }

        // We try to find the an alternative peer address.
        if (image == null || image.length == 0)
        {
            String imppAddress = peer.getAlternativeIMPPAddress();

            if (!StringUtils.isNullOrEmpty(imppAddress))
            {
                int protocolPartIndex = imppAddress.indexOf(":");

                imppAddress = (protocolPartIndex >= 0)
                        ? imppAddress.substring(protocolPartIndex + 1)
                        : imppAddress;

                Collection<ProtocolProviderService> cusaxProviders
                    = AccountUtils.getRegisteredProviders(
                        OperationSetCusaxUtils.class);

                if (cusaxProviders != null && cusaxProviders.size() > 0)
                {
                    Iterator<ProtocolProviderService> iter
                        = cusaxProviders.iterator();
                    while(iter.hasNext())
                    {
                        Contact contact = getPeerContact(
                            peer,
                            iter.next(),
                            imppAddress);

                        image = (contact != null) ?
                            getContactImage(contact) : null;

                        if(image != null)
                            break;
                    }
                }
                else
                {
                    MetaContact metaContact
                        = getPeerMetaContact(peer, imppAddress);

                    image = (metaContact != null)
                                ? metaContact.getAvatar() : null;
                }
            }
        }

        // If the icon is still null we try to get an image from the call
        // peer.
        if ((image == null || image.length == 0)
                && peer.getImage() != null)
            image = peer.getImage();

        return image;
    }

    /**
     * Searches the cusax enabled providers for a contact with
     * the detail (address) of the call peer if found and the contact
     * is provided by a provider which is IM capable, return the contact.
     * @param peer the peer we are calling.
     * @return the im capable contact corresponding the <tt>peer</tt>.
     */
    public static Contact getIMCapableCusaxContact(CallPeer peer)
    {
        // We try to find the <tt>UIContact</tt>, to which the call was
        // created if this was an outgoing call.
        UIContactImpl uiContact
            = CallManager.getCallUIContact(peer.getCall());

        if (uiContact != null)
        {
            if(uiContact.getDescriptor() instanceof MetaContact)
            {
                MetaContact metaContact =
                    (MetaContact)uiContact.getDescriptor();
                Iterator<Contact> iter = metaContact.getContacts();
                while(iter.hasNext())
                {
                    Contact contact = iter.next();
                    if(contact.getProtocolProvider()
                        .getOperationSet(
                            OperationSetBasicInstantMessaging.class) != null)
                        return contact;
                }
            }
            else if(uiContact.getDescriptor() instanceof SourceContact)
            {
                // if it is source contact (history record)
                // search for cusax contact match
                Contact contact = getPeerCusaxContact(peer,
                            (SourceContact)uiContact.getDescriptor());
                if(contact != null
                    && contact.getProtocolProvider().getOperationSet(
                            OperationSetBasicInstantMessaging.class) != null)
                    return contact;
            }
        }

        // We try to find the an alternative peer address.
        String imppAddress = peer.getAlternativeIMPPAddress();

        if (!StringUtils.isNullOrEmpty(imppAddress))
        {
            int protocolPartIndex = imppAddress.indexOf(":");

            imppAddress = (protocolPartIndex >= 0)
                    ? imppAddress.substring(protocolPartIndex + 1)
                    : imppAddress;

            Collection<ProtocolProviderService> cusaxProviders
                = AccountUtils.getRegisteredProviders(
                    OperationSetCusaxUtils.class);

            if (cusaxProviders != null && cusaxProviders.size() > 0)
            {
                Iterator<ProtocolProviderService> iter
                    = cusaxProviders.iterator();
                while(iter.hasNext())
                {
                    ProtocolProviderService cusaxProvider = iter.next();

                    Contact contact = getPeerContact(
                        peer,
                        cusaxProvider,
                        imppAddress);

                    if(contact != null
                        && cusaxProvider.getOperationSet(
                        OperationSetBasicInstantMessaging.class) != null)
                    {
                        return contact;
                    }
                }
            }
        }

        return null;
    }

    /**
     * Find is there a linked cusax protocol provider for this source contact,
     * if it exist we try to resolve current peer to one of its contacts
     * or details of a contact (numbers).
     * @param peer the peer to check
     * @param sourceContact the currently selected source contact.
     * @return matching cusax contact.
     */
    private static Contact getPeerCusaxContact(
        CallPeer peer, SourceContact sourceContact)
    {
        ProtocolProviderService linkedCusaxProvider = null;
        for(ContactDetail detail : sourceContact.getContactDetails())
        {
            ProtocolProviderService pps
                = detail.getPreferredProtocolProvider(
                OperationSetBasicTelephony.class);

            if(pps != null)
            {
                OperationSetCusaxUtils cusaxOpSet =
                    pps.getOperationSet(OperationSetCusaxUtils.class);

                if(cusaxOpSet != null)
                {
                    linkedCusaxProvider
                        = cusaxOpSet.getLinkedCusaxProvider();
                    break;
                }
            }
        }

        // if we do not have preferred protocol, lets check the one
        // used to dial the peer
        if(linkedCusaxProvider == null)
        {
            ProtocolProviderService pps = peer.getProtocolProvider();

            OperationSetCusaxUtils cusaxOpSet =
                pps.getOperationSet(OperationSetCusaxUtils.class);

            if(cusaxOpSet != null)
            {
                linkedCusaxProvider
                    = cusaxOpSet.getLinkedCusaxProvider();
            }
        }

        if(linkedCusaxProvider != null)
        {
            OperationSetPersistentPresence opSetPersistentPresence
                = linkedCusaxProvider.getOperationSet(
                        OperationSetPersistentPresence.class);

            if(opSetPersistentPresence != null)
            {
                String peerAddress = peer.getAddress();

                // will strip the @server-address part, as the regular expression
                // will match it
                int index = peerAddress.indexOf("@");
                String peerUserID =
                    (index > -1) ? peerAddress.substring(0, index) : peerAddress;

                // searches for the whole number/username or with the @serverpart
                String peerUserIDQ = Pattern.quote(peerUserID);

                Pattern pattern = Pattern.compile(
                    "^(" + peerUserIDQ + "|" + peerUserIDQ + "@.*)$");

                return findContactByPeer(
                    peerUserID,
                    pattern,
                    opSetPersistentPresence.getServerStoredContactListRoot(),
                    linkedCusaxProvider.getOperationSet(
                        OperationSetCusaxUtils.class));
            }
        }

        return null;
    }

    /**
     * Finds a matching cusax contact.
     * @param peerUserID the userID of the call peer to search for
     * @param searchPattern the pattern (userID | userID@...)
     * @param parent the parent group of the groups and contacts to search in
     * @param cusaxOpSet the opset of the provider which will be used to match
     *                   contact's details to peer userID (stored numbers).
     * @return a cusax matching contac
     */
    private static Contact findContactByPeer(
        String peerUserID,
        Pattern searchPattern,
        ContactGroup parent,
        OperationSetCusaxUtils cusaxOpSet)
    {
        Iterator<Contact> contactIterator = parent.contacts();
        while(contactIterator.hasNext())
        {
            Contact contact = contactIterator.next();

            if(searchPattern.matcher(contact.getAddress()).find()
                || cusaxOpSet.doesDetailBelong(contact, peerUserID))
            {
                return contact;
            }
        }

        Iterator<ContactGroup> groupsIterator = parent.subgroups();
        while(groupsIterator.hasNext())
        {
            ContactGroup gr = groupsIterator.next();
            Contact contact = findContactByPeer(
                peerUserID, searchPattern, gr, cusaxOpSet);
            if(contact != null)
                return contact;
        }

        return null;
    }

    /**
     * Returns the image for the given contact.
     *
     * @param contact the <tt>Contact</tt>, which image we're looking for
     * @return the array of bytes representing the image for the given contact
     * or null if such image doesn't exist
     */
    private static byte[] getContactImage(Contact contact)
    {
        MetaContact metaContact = GuiActivator.getContactListService()
            .findMetaContactByContact(contact);

        if (metaContact != null)
            return metaContact.getAvatar();

        return null;
    }

    /**
     * Returns the peer contact for the given <tt>alternativePeerAddress</tt> by
     * checking the if the <tt>callPeer</tt> exists as a detail in the given
     * <tt>cusaxProvider</tt>.
     *
     * @param callPeer the <tt>CallPeer</tt> to check in the cusax provider
     * details
     * @param cusaxProvider the linked cusax <tt>ProtocolProviderService</tt>
     * @param alternativePeerAddress the alternative peer address to obtain the
     * image from
     * @return the protocol <tt>Contact</tt> corresponding to the given
     * <tt>alternativePeerAddress</tt>
     */
    private static Contact getPeerContact( CallPeer callPeer,
                                        ProtocolProviderService cusaxProvider,
                                        String alternativePeerAddress)
    {
        OperationSetPresence presenceOpSet
            = cusaxProvider.getOperationSet(OperationSetPresence.class);

        if (presenceOpSet == null)
            return null;

        Contact contact = presenceOpSet.findContactByID(alternativePeerAddress);

        if (contact == null)
            return null;

        OperationSetCusaxUtils cusaxOpSet
            = cusaxProvider.getOperationSet(OperationSetCusaxUtils.class);

        if (cusaxOpSet != null && cusaxOpSet.doesDetailBelong(
                contact, callPeer.getAddress()))
            return contact;

        return null;
    }

    /**
     * Returns the metacontact for the given <tt>CallPeer</tt> by
     * checking the if the <tt>callPeer</tt> contact exists, if not checks the
     * contacts in our contact list that are provided by cusax enabled
     * providers.
     *
     * @param peer the <tt>CallPeer</tt> to check in contact details
     * @return the <tt>MetaContact</tt> corresponding to the given
     * <tt>peer</tt>.
     */
    public static MetaContact getPeerMetaContact(CallPeer peer)
    {
        if(peer == null)
            return null;

        if(peer.getContact() != null)
            return GuiActivator.getContactListService()
                .findMetaContactByContact(peer.getContact());

        // We try to find the <tt>UIContact</tt>, to which the call was
        // created if this was an outgoing call.
        UIContactImpl uiContact
            = CallManager.getCallUIContact(peer.getCall());

        if (uiContact != null)
        {
            if(uiContact.getDescriptor() instanceof MetaContact)
            {
                return (MetaContact)uiContact.getDescriptor();
            }
            else if(uiContact.getDescriptor() instanceof SourceContact)
            {
                // if it is a source contact check for matching cusax contact
                Contact contact = getPeerCusaxContact(peer,
                    (SourceContact)uiContact.getDescriptor());
                if(contact != null)
                    return GuiActivator.getContactListService()
                                .findMetaContactByContact(contact);
            }
        }

        String imppAddress = peer.getAlternativeIMPPAddress();

        if (!StringUtils.isNullOrEmpty(imppAddress))
        {
            int protocolPartIndex = imppAddress.indexOf(":");

            imppAddress = (protocolPartIndex >= 0)
                    ? imppAddress.substring(protocolPartIndex + 1)
                    : imppAddress;

            Collection<ProtocolProviderService> cusaxProviders
                = AccountUtils.getRegisteredProviders(
                    OperationSetCusaxUtils.class);

            if (cusaxProviders != null && cusaxProviders.size() > 0)
            {
                Iterator<ProtocolProviderService> iter
                    = cusaxProviders.iterator();
                while(iter.hasNext())
                {
                    Contact contact = getPeerContact(
                        peer,
                        iter.next(),
                        imppAddress);

                    MetaContact res = GuiActivator.getContactListService()
                        .findMetaContactByContact(contact);

                    if(res != null)
                        return res;
                }
            }
            else
            {
                return getPeerMetaContact(peer, imppAddress);
            }
        }

        return null;
    }

    /**
     * Returns the image for the given <tt>alternativePeerAddress</tt> by
     * checking the if the <tt>callPeer</tt> exists as a detail in one of the
     * contacts in our contact list.
     *
     * @param callPeer the <tt>CallPeer</tt> to check in contact details
     * @param alternativePeerAddress the alternative peer address to obtain the
     * image from
     * @return the <tt>MetaContact</tt> corresponding to the given
     * <tt>alternativePeerAddress</tt>
     */
    private static MetaContact getPeerMetaContact(
                                            CallPeer callPeer,
                                            String alternativePeerAddress)
    {
        Iterator<MetaContact> metaContacts
            = GuiActivator.getContactListService()
                .findAllMetaContactsForAddress(alternativePeerAddress);

        while (metaContacts.hasNext())
        {
            MetaContact metaContact = metaContacts.next();

            UIPhoneUtil phoneUtil
                = UIPhoneUtil.getPhoneUtil(metaContact);

            List<UIContactDetail> additionalNumbers
                = phoneUtil.getAdditionalNumbers();

            if (additionalNumbers == null || additionalNumbers.size() > 0)
                continue;

            Iterator<UIContactDetail> numbersIter
                = additionalNumbers.iterator();
            while (numbersIter.hasNext())
            {
                if (numbersIter.next().getAddress()
                    .equals(callPeer.getAddress()))
                    return metaContact;
            }
        }

        return null;
    }

    /**
     * Opens a call transfer dialog to transfer the given <tt>peer</tt>.
     * @param peer the <tt>CallPeer</tt> to transfer
     */
    public static void openCallTransferDialog(CallPeer peer)
    {
        final TransferCallDialog dialog
            = new TransferCallDialog(peer);

        final Call call = peer.getCall();

        /*
         * Transferring a call works only when the call is in progress
         * so close the dialog (if it's not already closed, of course)
         * once the dialog ends.
         */
        CallChangeListener callChangeListener = new CallChangeAdapter()
        {
            /*
             * Overrides
             * CallChangeAdapter#callStateChanged(CallChangeEvent).
             */
            @Override
            public void callStateChanged(CallChangeEvent evt)
            {
                // we are interested only in CALL_STATE_CHANGEs
                if(!evt.getEventType().equals(
                        CallChangeEvent.CALL_STATE_CHANGE))
                    return;

                if (!CallState.CALL_IN_PROGRESS.equals(call
                    .getCallState()))
                {
                    dialog.setVisible(false);
                    dialog.dispose();
                }
            }
        };
        call.addCallChangeListener(callChangeListener);
        try
        {
            dialog.pack();
            dialog.setVisible(true);
        }
        finally
        {
            call.removeCallChangeListener(callChangeListener);
        }
    }

    /**
     * Checks whether the <tt>callPeer</tt> supports setting video
     * quality presets. If quality controls is null, its not supported.
     * @param callPeer the peer, which video quality we're checking
     * @return whether call peer supports setting quality preset.
     */
    public static boolean isVideoQualityPresetSupported(CallPeer callPeer)
    {
        ProtocolProviderService provider = callPeer.getProtocolProvider();
        OperationSetVideoTelephony videoOpSet
            = provider.getOperationSet(OperationSetVideoTelephony.class);

        if (videoOpSet == null)
            return false;

        return videoOpSet.getQualityControl(callPeer) != null;
    }

    /**
     * Sets the given quality preset for the video of the given call peer.
     *
     * @param callPeer the peer, which video quality we're setting
     * @param qualityPreset the new quality settings
     */
    public static void setVideoQualityPreset(final CallPeer callPeer,
                                            final QualityPreset qualityPreset)
    {
        ProtocolProviderService provider = callPeer.getProtocolProvider();
        final OperationSetVideoTelephony videoOpSet
            = provider.getOperationSet(OperationSetVideoTelephony.class);

        if (videoOpSet == null)
            return;

        final QualityControl qualityControl =
                    videoOpSet.getQualityControl(callPeer);

        if (qualityControl != null)
        {
            new Thread(new Runnable()
            {
                public void run()
                {
                    try
                    {
                        qualityControl.setPreferredRemoteSendMaxPreset(
                                qualityPreset);
                    }
                    catch(Exception e)
                    {
                        logger.info("Unable to change video quality.", e);

                        ResourceManagementService resources
                            = GuiActivator.getResources();

                        new ErrorDialog(
                                null,
                                resources.getI18NString("service.gui.WARNING"),
                                resources.getI18NString(
                                        "service.gui.UNABLE_TO_CHANGE_VIDEO_QUALITY"),
                                e)
                            .showDialog();
                    }
                }
            }).start();
        }
    }

    /**
     * Indicates if we have video streams to show in this interface.
     *
     * @param call the call to check for video streaming
     * @return <tt>true</tt> if we have video streams to show in this interface;
     * otherwise, <tt>false</tt>
     */
    public static boolean isVideoStreaming(Call call)
    {
        return isVideoStreaming(call.getConference());
    }

    /**
     * Indicates if we have video streams to show in this interface.
     *
     * @param conference the conference we check for video streaming
     * @return <tt>true</tt> if we have video streams to show in this interface;
     * otherwise, <tt>false</tt>
     */
    public static boolean isVideoStreaming(CallConference conference)
    {
        for (Call call : conference.getCalls())
        {
            OperationSetVideoTelephony videoTelephony
                = call.getProtocolProvider().getOperationSet(
                        OperationSetVideoTelephony.class);

            if (videoTelephony == null)
                continue;

            if (videoTelephony.isLocalVideoStreaming(call))
                return true;

            Iterator<? extends CallPeer> callPeers = call.getCallPeers();

            while (callPeers.hasNext())
            {
                List<Component> remoteVideos
                    = videoTelephony.getVisualComponents(callPeers.next());

                if ((remoteVideos != null) && (remoteVideos.size() > 0))
                    return true;
            }
        }
        return false;
    }

    /**
     * Determines whether two specific addresses refer to one and the same
     * peer/resource/contact.
     * <p>
     * <b>Warning</b>: Use the functionality sparingly because it assumes that
     * an unspecified service is equal to any service.
     * </p>
     *
     * @param a one of the addresses to be compared
     * @param b the other address to be compared to <tt>a</tt>
     * @return <tt>true</tt> if <tt>a</tt> and <tt>b</tt> name one and the same
     * peer/resource/contact; <tt>false</tt>, otherwise
     */
    public static boolean addressesAreEqual(String a, String b)
    {
        if (a.equals(b))
            return true;

        int aProtocolIndex = a.indexOf(':');
        if(aProtocolIndex != -1)
            a = a.substring(aProtocolIndex + 1);

        int bProtocolIndex = b.indexOf(':');
        if(bProtocolIndex != -1)
            b = b.substring(bProtocolIndex + 1);

        if (a.equals(b))
            return true;

        int aServiceBegin = a.indexOf('@', aProtocolIndex);
        String aUserID;
        String aService;

        if (aServiceBegin != -1)
        {
            aUserID = a.substring(0, aServiceBegin);
            ++aServiceBegin;

            int aResourceBegin = a.indexOf('/', aServiceBegin);
            if (aResourceBegin != -1)
                aService = a.substring(aServiceBegin, aResourceBegin);
            else
                aService = a.substring(aServiceBegin);
        }
        else
        {
            aUserID = a;
            aService = null;
        }

        int bServiceBegin = b.indexOf('@', bProtocolIndex);
        String bUserID;
        String bService;

        if (bServiceBegin != -1)
        {
            bUserID = b.substring(0, bServiceBegin);
            ++bServiceBegin;

            int bResourceBegin = b.indexOf('/', bServiceBegin);
            if (bResourceBegin != -1)
                bService = b.substring(bServiceBegin, bResourceBegin);
            else
                bService = b.substring(bServiceBegin);
        }
        else
        {
            bUserID = b;
            bService = null;
        }

        boolean userIDsAreEqual;

        if ((aUserID == null) || (aUserID.length() < 1))
            userIDsAreEqual = ((bUserID == null) || (bUserID.length() < 1));
        else
            userIDsAreEqual = aUserID.equals(bUserID);
        if (!userIDsAreEqual)
            return false;

        boolean servicesAreEqual;

        /*
         * It's probably a veeery long shot but it's assumed here that an
         * unspecified service is equal to any service. Such a case is, for
         * example, RegistrarLess SIP.
         */
        if (((aService == null) || (aService.length() < 1))
                || ((bService == null) || (bService.length() < 1)))
            servicesAreEqual = true;
        else
            servicesAreEqual = aService.equals(bService);

        return servicesAreEqual;
    }

    /**
     * Indicates if the given <tt>ConferenceMember</tt> corresponds to the local
     * user.
     *
     * @param conferenceMember the conference member to check
     * @return <tt>true</tt> if the given <tt>conferenceMember</tt> is the local
     * user, <tt>false</tt> - otherwise
     */
    public static boolean isLocalUser(ConferenceMember conferenceMember)
    {
        String localUserAddress
            = conferenceMember.getConferenceFocusCallPeer()
                .getProtocolProvider().getAccountID().getAccountAddress();

        return CallManager.addressesAreEqual(
            conferenceMember.getAddress(), localUserAddress);
    }

    /**
     * Adds a missed call notification.
     *
     * @param peerName the name of the peer
     * @param callTime the time of the call
     */
    private static void addMissedCallNotification(String peerName, long callTime)
    {
        if (missedCallGroup == null)
        {
            missedCallGroup
                = new UINotificationGroup(
                        "MissedCalls",
                        GuiActivator.getResources().getI18NString(
                                "service.gui.MISSED_CALLS_TOOL_TIP"));
        }

        UINotificationManager.addNotification(
                new UINotification(peerName, callTime, missedCallGroup));
    }

    /**
     * Returns of supported/enabled list of audio formats for a provider.
     * @param device the <tt>MediaDevice</tt>, which audio formats we're
     * looking for
     * @param protocolProvider the provider to check.
     * @return list of supported/enabled auido formats or empty list
     * otherwise.
     */
    private static List<MediaFormat> getAudioFormats(
        MediaDevice device,
        ProtocolProviderService protocolProvider)
    {
        List<MediaFormat> res = new ArrayList<MediaFormat>();

        Map<String, String> accountProperties
           = protocolProvider.getAccountID().getAccountProperties();
        String overrideEncodings
           = accountProperties.get(ProtocolProviderFactory.OVERRIDE_ENCODINGS);

        List<MediaFormat> formats;
        if(Boolean.parseBoolean(overrideEncodings))
        {
           /*
            * The account properties associated with account
             * override the global EncodingConfiguration.
            */
           EncodingConfiguration encodingConfiguration
               = ProtocolMediaActivator.getMediaService()
                       .createEmptyEncodingConfiguration();

           encodingConfiguration.loadProperties(
                   accountProperties,
                   ProtocolProviderFactory.ENCODING_PROP_PREFIX);

            formats = device.getSupportedFormats(
                       null, null, encodingConfiguration);
        }
        else /* The global EncodingConfiguration is in effect. */
        {
            formats = device.getSupportedFormats();
        }

        // skip the special telephony event
        for(MediaFormat format : formats)
        {
            if(!format.getEncoding().equals(Constants.TELEPHONE_EVENT))
                res.add(format);
        }

        return res;
    }

    /**
     * Creates a new (audio-only or video) <tt>Call</tt> to a contact specified
     * as a <tt>Contact</tt> instance or a <tt>String</tt> contact
     * address/identifier.
     */
    private static class CreateCallThread
        extends Thread
    {
        /**
         * The contact to call.
         */
        private final Contact contact;

        /**
         * The specific contact resource to call.
         */
        private final ContactResource contactResource;

        /**
         * The <tt>UIContactImpl</tt> we're calling.
         */
        private final UIContactImpl uiContact;

        /**
         * The protocol provider through which the call goes.
         */
        private final ProtocolProviderService protocolProvider;

        /**
         * The string to call.
         */
        private final String stringContact;

        /**
         * The description of a conference to call, if any.
         */
        private final ConferenceDescription conferenceDescription;

        /**
         * The indicator which determines whether this instance is to create a
         * new video (as opposed to audio-only) <tt>Call</tt>.
         */
        private final boolean video;

        /**
         * The chat room associated with the call.
         */
        private final ChatRoom chatRoom;
        
        /**
         * Creates an instance of <tt>CreateCallThread</tt>.
         *
         * @param protocolProvider the protocol provider through which the call
         * is going.
         * @param contact the contact to call
         * @param contactResource the specific <tt>ContactResource</tt> we're
         * calling
         * @param video indicates if this is a video call
         */
        public CreateCallThread(
                ProtocolProviderService protocolProvider,
                Contact contact,
                ContactResource contactResource,
                boolean video)
        {
            this(protocolProvider, contact, contactResource, null, null, null,
                null, video);
        }

        /**
         * Creates an instance of <tt>CreateCallThread</tt>.
         *
         * @param protocolProvider the protocol provider through which the call
         * is going.
         * @param contact the contact to call
         * @param video indicates if this is a video call
         */
        public CreateCallThread(
                ProtocolProviderService protocolProvider,
                String contact,
                boolean video)
        {
            this(protocolProvider, null, null, null, contact, null, null, video);
        }

        /**
         * Initializes a new <tt>CreateCallThread</tt> instance which is to
         * create a new <tt>Call</tt> to a conference specified via a
         * <tt>ConferenceDescription</tt>.
         * @param protocolProvider the <tt>ProtocolProviderService</tt> which is
         * to perform the establishment of the new <tt>Call</tt>.
         * @param conferenceDescription the description of the conference to
         * call.
         * @param chatRoom the chat room associated with the call.
         */
        public CreateCallThread(
                ProtocolProviderService protocolProvider,
                ConferenceDescription conferenceDescription,
                ChatRoom chatRoom)
        {
            this(protocolProvider, null, null, null, null,
                    conferenceDescription, chatRoom,
                    false /* video */);
        }

        /**
         * Initializes a new <tt>CreateCallThread</tt> instance which is to
         * create a new <tt>Call</tt> to a contact specified either as a
         * <tt>Contact</tt> instance or as a <tt>String</tt> contact
         * address/identifier.
         * <p>
         * The constructor is private because it relies on its arguments being
         * validated prior to its invocation.
         * </p>
         *
         * @param protocolProvider the <tt>ProtocolProviderService</tt> which is
         * to perform the establishment of the new <tt>Call</tt>
         * @param contact the contact to call
         * @param contactResource the specific contact resource to call
         * @param uiContact the ui contact we're calling
         * @param stringContact the string to call
         * @param video <tt>true</tt> if this instance is to create a new video
         * (as opposed to audio-only) <tt>Call</tt>
         * @param conferenceDescription the description of a conference to call
         * @param chatRoom the chat room associated with the call.
         */
        public CreateCallThread(
                ProtocolProviderService protocolProvider,
                Contact contact,
                ContactResource contactResource,
                UIContactImpl uiContact,
                String stringContact,
                ConferenceDescription conferenceDescription,
                ChatRoom chatRoom,
                boolean video)
        {
            this.protocolProvider = protocolProvider;
            this.contact = contact;
            this.contactResource = contactResource;
            this.uiContact = uiContact;
            this.stringContact = stringContact;
            this.video = video;
            this.conferenceDescription = conferenceDescription;
            this.chatRoom = chatRoom;
        }

        @Override
        public void run()
        {
            if(!video)
            {
                // if it is not video let's check for available audio codecs
                // and available audio devices
                MediaService mediaService = GuiActivator.getMediaService();
                MediaDevice dev = mediaService.getDefaultDevice(
                   MediaType.AUDIO, MediaUseCase.CALL);

                List<MediaFormat> formats
                    = getAudioFormats(dev, protocolProvider);

                String errorMsg = null;

                if(!dev.getDirection().allowsSending())
                    errorMsg = GuiActivator.getResources().getI18NString(
                        "service.gui.CALL_NO_AUDIO_DEVICE");
                else if(formats.isEmpty())
                {
                    errorMsg = GuiActivator.getResources().getI18NString(
                        "service.gui.CALL_NO_AUDIO_CODEC");
                }

                if(errorMsg != null)
                {
                    if(GuiActivator.getUIService()
                        .getPopupDialog().showConfirmPopupDialog(
                            errorMsg + " " +
                                GuiActivator.getResources().getI18NString(
                                    "service.gui.CALL_NO_DEVICE_CODECS_Q"),
                            GuiActivator.getResources().getI18NString(
                                    "service.gui.CALL"),
                                PopupDialog.YES_NO_OPTION,
                                PopupDialog.QUESTION_MESSAGE)
                        == PopupDialog.NO_OPTION)
                    {
                        return;
                    }
                }
            }

            Contact contact = this.contact;
            String stringContact = this.stringContact;

            if (ConfigurationUtils.isNormalizePhoneNumber()
                && !NetworkUtils.isValidIPAddress(stringContact))
            {
                if (contact != null)
                {
                    stringContact = contact.getAddress();
                    contact = null;
                }

                if (stringContact != null)
                {
                    stringContact = GuiActivator.getPhoneNumberI18nService()
                        .normalize(stringContact);
                }
            }

            try
            {
                if (conferenceDescription != null)
                {
                    internalCall(  protocolProvider,
                                   conferenceDescription,
                                   chatRoom);
                }
                else
                {
                    if (video)
                    {
                        internalCallVideo(  protocolProvider,
                                            contact,
                                            uiContact,
                                            stringContact);
                    }
                    else
                    {
                        internalCall(   protocolProvider,
                                        contact,
                                        stringContact,
                                        contactResource,
                                        uiContact);
                    }
                }
            }
            catch (Throwable t)
            {
                if (t instanceof ThreadDeath)
                    throw (ThreadDeath) t;

                logger.error("The call could not be created: ", t);

                String message = GuiActivator.getResources()
                    .getI18NString("servoce.gui.CREATE_CALL_FAILED");

                if (t.getMessage() != null)
                    message += " " +  t.getMessage();

                new ErrorDialog(
                        null,
                        GuiActivator.getResources().getI18NString(
                                "service.gui.ERROR"),
                        message,
                        t)
                    .showDialog();
            }
        }
    }

    /**
     * Creates a video call through the given <tt>protocolProvider</tt>.
     *
     * @param protocolProvider the <tt>ProtocolProviderService</tt> through
     * which to make the call
     * @param contact the <tt>Contact</tt> to call
     * @param uiContact the <tt>UIContactImpl</tt> we're calling
     * @param stringContact the contact string to call
     *
     * @throws OperationFailedException thrown if the call operation fails
     * @throws ParseException thrown if the contact string is malformated
     */
    private static void internalCallVideo(
                                    ProtocolProviderService protocolProvider,
                                    Contact contact,
                                    UIContactImpl uiContact,
                                    String stringContact)
        throws  OperationFailedException,
                ParseException
    {
        OperationSetVideoTelephony telephony
            = protocolProvider.getOperationSet(
                    OperationSetVideoTelephony.class);

        Call createdCall = null;
        if (telephony != null)
        {
            if (contact != null)
            {
                createdCall = telephony.createVideoCall(contact);
            }
            else if (stringContact != null)
                createdCall = telephony.createVideoCall(stringContact);
        }

        if (uiContact != null && createdCall != null)
            addUIContactCall(uiContact, createdCall);
    }

    /**
     * Creates a call through the given <tt>protocolProvider</tt>.
     *
     * @param protocolProvider the <tt>ProtocolProviderService</tt> through
     * which to make the call
     * @param contact the <tt>Contact</tt> to call
     * @param stringContact the contact string to call
     * @param contactResource the specific <tt>ContactResource</tt> to call
     * @param uiContact the <tt>UIContactImpl</tt> we're calling
     *
     * @throws OperationFailedException thrown if the call operation fails
     * @throws ParseException thrown if the contact string is malformated
     */
    private static void internalCall(
                                ProtocolProviderService protocolProvider,
                                Contact contact,
                                String stringContact,
                                ContactResource contactResource,
                                UIContactImpl uiContact)
        throws  OperationFailedException,
                ParseException
    {
        OperationSetBasicTelephony<?> telephony
            = protocolProvider.getOperationSet(
                    OperationSetBasicTelephony.class);

        OperationSetResourceAwareTelephony resourceTelephony
            = protocolProvider.getOperationSet(
                    OperationSetResourceAwareTelephony.class);

        Call createdCall = null;

        if (resourceTelephony != null && contactResource != null)
        {
            if (contact != null)
                createdCall
                    = resourceTelephony.createCall(contact, contactResource);
            else if (!StringUtils.isNullOrEmpty(stringContact))
                createdCall = resourceTelephony.createCall(
                    stringContact, contactResource.getResourceName());
        }
        else if (telephony != null)
        {
            if (contact != null)
            {
                createdCall = telephony.createCall(contact);
            }
            else if (!StringUtils.isNullOrEmpty(stringContact))
                createdCall = telephony.createCall(stringContact);
        }

        if (uiContact != null && createdCall != null)
            addUIContactCall(uiContact, createdCall);
    }

    /**
     * Creates a call through the given <tt>protocolProvider</tt>.
     *
     * @param protocolProvider the <tt>ProtocolProviderService</tt> through
     * which to make the call
     * @param conferenceDescription the description of the conference to call
     * @param chatRoom the chat room associated with the call.
     */
    private static void internalCall(ProtocolProviderService protocolProvider,
                                     ConferenceDescription conferenceDescription,
                                     ChatRoom chatRoom)
            throws OperationFailedException
    {
        OperationSetBasicTelephony<?> telephony
                = protocolProvider.getOperationSet(
                OperationSetBasicTelephony.class);

        if (telephony != null)
        {
            telephony.createCall(conferenceDescription, chatRoom);
        }
    }

    /**
     * Returns the <tt>MetaContact</tt>, to which the given <tt>Call</tt>
     * was initially created.
     *
     * @param call the <tt>Call</tt>, which corresponding <tt>MetaContact</tt>
     * we're looking for
     * @return the <tt>UIContactImpl</tt>, to which the given <tt>Call</tt>
     * was initially created
     */
    public static UIContactImpl getCallUIContact(Call call)
    {
        if (uiContactCalls != null)
            return uiContactCalls.get(call);
        return null;
    }

    /**
     * Adds a call for a <tt>metaContact</tt>.
     *
     * @param uiContact the <tt>UIContact</tt> corresponding to the call
     * @param call the <tt>Call</tt> corresponding to the <tt>MetaContact</tt>
     */
    private static void addUIContactCall( UIContactImpl uiContact,
                                          Call call)
    {
        if (uiContactCalls == null)
            uiContactCalls = new WeakHashMap<Call, UIContactImpl>();

        uiContactCalls.put(call, uiContact);
    }

    /**
     * Creates a desktop sharing session with the given Contact or a given
     * String.
     */
    private static class CreateDesktopSharingThread
        extends Thread
    {
        /**
         * The string contact to share the desktop with.
         */
        private final String stringContact;

        /**
         * The protocol provider through which we share our desktop.
         */
        private final ProtocolProviderService protocolProvider;

        /**
         * The media device corresponding to the screen we would like to share.
         */
        private final MediaDevice mediaDevice;

        /**
         * The <tt>UIContactImpl</tt> we're calling.
         */
        private final UIContactImpl uiContact;

        /**
         * Whether user has selected sharing full screen or region.
         */
        private boolean fullscreen = false;

        /**
         * Creates a desktop sharing session thread.
         *
         * @param protocolProvider protocol provider through which we share our
         * desktop
         * @param contact the contact to share the desktop with
         * @param uiContact the <tt>UIContact</tt>, which initiated the desktop
         * sharing session
         * @param mediaDevice the media device corresponding to the screen we
         * would like to share
         */
        public CreateDesktopSharingThread(
                                    ProtocolProviderService protocolProvider,
                                    String contact,
                                    UIContactImpl uiContact,
                                    MediaDevice mediaDevice,
                                    boolean fullscreen)
        {
            this.protocolProvider = protocolProvider;
            this.stringContact = contact;
            this.uiContact = uiContact;
            this.mediaDevice = mediaDevice;
            this.fullscreen = fullscreen;
        }

        @Override
        public void run()
        {
            OperationSetDesktopStreaming desktopSharingOpSet
                = protocolProvider.getOperationSet(
                    OperationSetDesktopStreaming.class);

            /*
             * XXX If we are here and we just discover that
             * OperationSetDesktopStreaming is not supported, then we're
             * already in trouble - we've already started a whole new thread
             * just to check that a reference is null.
             */
            if (desktopSharingOpSet == null)
                return;

            Throwable exception = null;

            Call createdCall = null;
            try
            {
                if (mediaDevice != null)
                {
                    createdCall = desktopSharingOpSet.createVideoCall(
                            stringContact,
                            mediaDevice);
                }
                else
                    createdCall
                        = desktopSharingOpSet.createVideoCall(stringContact);
            }
            catch (OperationFailedException e)
            {
                exception = e;
            }
            catch (ParseException e)
            {
                exception = e;
            }
            if (exception != null)
            {
                logger.error("The call could not be created: ", exception);

                new ErrorDialog(
                        null,
                        GuiActivator.getResources().getI18NString(
                                "service.gui.ERROR"),
                        exception.getMessage(),
                        ErrorDialog.ERROR)
                    .showDialog();
            }

            if (uiContact != null && createdCall != null)
                addUIContactCall(uiContact, createdCall);


            if(createdCall != null && fullscreen)
            {
                new FullScreenShareIndicator(createdCall);
            }
        }
    }

    /**
     * Answers to all <tt>CallPeer</tt>s associated with a specific
     * <tt>Call</tt> and, optionally, does that in a telephony conference with
     * an existing <tt>Call</tt>.
     */
    private static class AnswerCallThread
        extends Thread
    {
        /**
         * The <tt>Call</tt> which is to be answered.
         */
        private final Call call;

        /**
         * The existing <tt>Call</tt>, if any, which represents a telephony
         * conference in which {@link #call} is to be answered.
         */
        private final Call existingCall;

        /**
         * The indicator which determines whether this instance is to answer
         * {@link #call} with video.
         */
        private final boolean video;

        public AnswerCallThread(Call call, Call existingCall, boolean video)
        {
            this.call = call;
            this.existingCall = existingCall;
            this.video = video;
        }

        @Override
        public void run()
        {
            if (existingCall != null)
                call.setConference(existingCall.getConference());

            ProtocolProviderService pps = call.getProtocolProvider();
            Iterator<? extends CallPeer> peers = call.getCallPeers();

            while (peers.hasNext())
            {
                CallPeer peer = peers.next();

                if (video)
                {
                    OperationSetVideoTelephony telephony
                        = pps.getOperationSet(OperationSetVideoTelephony.class);

                    try
                    {
                        telephony.answerVideoCallPeer(peer);
                    }
                    catch (OperationFailedException ofe)
                    {
                        logger.error(
                                "Could not answer " + peer + " with video"
                                    + " because of the following exception: "
                                    + ofe);
                    }
                }
                else
                {
                    OperationSetBasicTelephony<?> telephony
                        = pps.getOperationSet(OperationSetBasicTelephony.class);

                    try
                    {
                        telephony.answerCallPeer(peer);
                    }
                    catch (OperationFailedException ofe)
                    {
                        logger.error(
                                "Could not answer " + peer
                                    + " because of the following exception: ",
                                ofe);
                    }
                }
            }
        }
    }

    /**
     * Invites a list of callees to a conference <tt>Call</tt>. If the specified
     * <tt>Call</tt> is <tt>null</tt>, creates a brand new telephony conference.
     */
    private static class InviteToConferenceCallThread
        extends Thread
    {
        /**
         * The addresses of the callees to be invited into the telephony
         * conference to be organized by this instance. For further details,
         * refer to the documentation on the <tt>callees</tt> parameter of the
         * respective <tt>InviteToConferenceCallThread</tt> constructor.
         */
        private final Map<ProtocolProviderService, List<String>>
            callees;

        /**
         * The <tt>Call</tt>, if any, into the telephony conference of which
         * {@link #callees} are to be invited. If non-<tt>null</tt>, its
         * <tt>CallConference</tt> state will be shared with all <tt>Call</tt>s
         * established by this instance for the purposes of having the
         * <tt>callees</tt> into the same telephony conference.
         */
        private final Call call;

        /**
         * Initializes a new <tt>InviteToConferenceCallThread</tt> instance
         * which is to invite a list of callees to a conference <tt>Call</tt>.
         * If the specified <tt>call</tt> is <tt>null</tt>, creates a brand new
         * telephony conference.
         *
         * @param callees the addresses of the callees to be invited into a
         * telephony conference. The addresses are provided in multiple
         * <tt>List&lt;String&gt;</tt>s. Each such list of addresses is mapped
         * by the <tt>ProtocolProviderService</tt> through which they are to be
         * invited into the telephony conference. If there are multiple
         * <tt>ProtocolProviderService</tt>s in the specified <tt>Map</tt>, the
         * resulting telephony conference is known by the name
         * &quot;cross-protocol&quot;. It is also allowed to have a list of
         * addresses mapped to <tt>null</tt> which means that the new instance
         * will automatically choose a <tt>ProtocolProviderService</tt> to
         * invite the respective callees into the telephony conference.
         * @param call the <tt>Call</tt> to invite the specified
         * <tt>callees</tt> into. If <tt>null</tt>, this instance will create a
         * brand new telephony conference. Technically, a <tt>Call</tt> instance
         * is protocol/account-specific and it is possible to have
         * cross-protocol/account telephony conferences. That's why the
         * specified <tt>callees</tt> are invited into one and the same
         * <tt>CallConference</tt>: the one in which the specified <tt>call</tt>
         * is participating or a new one if <tt>call</tt> is <tt>null</tt>. Of
         * course, an attempt is made to have all callees from one and the same
         * protocol/account into one <tt>Call</tt> instance.
         */
        public InviteToConferenceCallThread(
                Map<ProtocolProviderService, List<String>> callees,
                Call call)
        {
            this.callees = callees;
            this.call = call;
        }

        /**
         * Invites {@link #callees} into a telephony conference which is
         * optionally specified by {@link #call}.
         */
        @Override
        public void run()
        {
            CallConference conference
                = (call == null) ? null : call.getConference();

            for(Map.Entry<ProtocolProviderService, List<String>> entry
                    : callees.entrySet())
            {
                ProtocolProviderService pps = entry.getKey();

                /*
                 * We'd like to allow specifying callees without specifying an
                 * associated ProtocolProviderService.
                 */
                if (pps != null)
                {
                    OperationSetBasicTelephony<?> basicTelephony
                        = pps.getOperationSet(OperationSetBasicTelephony.class);

                    if(basicTelephony == null)
                        continue;
                }

                List<String> contactList = entry.getValue();
                String[] contactArray
                    = contactList.toArray(new String[contactList.size()]);

                if (ConfigurationUtils.isNormalizePhoneNumber())
                    normalizePhoneNumbers(contactArray);

                /* Try to have a single Call per ProtocolProviderService. */
                Call ppsCall;

                if ((call != null) && call.getProtocolProvider().equals(pps))
                    ppsCall = call;
                else
                {
                    ppsCall = null;
                    if (conference != null)
                    {
                        List<Call> conferenceCalls = conference.getCalls();

                        if (pps == null)
                        {
                            /*
                             * We'd like to allow specifying callees without
                             * specifying an associated ProtocolProviderService.
                             * The simplest approach is to just choose the first
                             * ProtocolProviderService involved in the telephony
                             * conference.
                             */
                            if (call == null)
                            {
                                if (!conferenceCalls.isEmpty())
                                {
                                    ppsCall = conferenceCalls.get(0);
                                    pps = ppsCall.getProtocolProvider();
                                }
                            }
                            else
                            {
                                ppsCall = call;
                                pps = ppsCall.getProtocolProvider();
                            }
                        }
                        else
                        {
                            for (Call conferenceCall : conferenceCalls)
                            {
                                if (pps.equals(
                                        conferenceCall.getProtocolProvider()))
                                {
                                    ppsCall = conferenceCall;
                                    break;
                                }
                            }
                        }
                    }
                }

                OperationSetTelephonyConferencing telephonyConferencing
                    = pps.getOperationSet(
                            OperationSetTelephonyConferencing.class);

                try
                {
                    if (ppsCall == null)
                    {
                        ppsCall
                            = telephonyConferencing.createConfCall(
                                    contactArray,
                                    conference);
                        if (conference == null)
                            conference = ppsCall.getConference();
                    }
                    else
                    {
                        for (String contact : contactArray)
                        {
                            telephonyConferencing.inviteCalleeToCall(
                                    contact,
                                    ppsCall);
                        }
                    }
                }
                catch(Exception e)
                {
                    logger.error(
                            "Failed to invite callees: "
                                + Arrays.toString(contactArray),
                            e);
                    new ErrorDialog(
                            null,
                            GuiActivator.getResources().getI18NString(
                                    "service.gui.ERROR"),
                            e.getMessage(),
                            ErrorDialog.ERROR)
                        .showDialog();
                }
            }
        }
    }

    /**
     * Invites a list of callees to a specific conference <tt>Call</tt>. If the
     * specified <tt>Call</tt> is <tt>null</tt>, creates a brand new telephony
     * conference.
     */
    private static class InviteToConferenceBridgeThread
        extends Thread
    {
        private final ProtocolProviderService callProvider;

        private final String[] callees;

        private final Call call;

        public InviteToConferenceBridgeThread(
                                        ProtocolProviderService callProvider,
                                        String[] callees,
                                        Call call)
        {
            this.callProvider = callProvider;
            this.callees = callees;
            this.call = call;
        }

        @Override
        public void run()
        {
            OperationSetVideoBridge opSetVideoBridge
                = callProvider.getOperationSet(
                    OperationSetVideoBridge.class);

            // Normally if this method is called then this should not happen
            // but we check in order to be sure to be able to proceed.
            if (opSetVideoBridge == null || !opSetVideoBridge.isActive())
                return;

            if (ConfigurationUtils.isNormalizePhoneNumber())
                normalizePhoneNumbers(callees);

            try
            {
                if (call == null)
                {
                    opSetVideoBridge.createConfCall(callees);
                }
                else
                {
                    for (String contact : callees)
                        opSetVideoBridge.inviteCalleeToCall(contact, call);
                }
            }
            catch(Exception e)
            {
                logger.error(
                        "Failed to invite callees: "
                            + Arrays.toString(callees),
                        e);
                new ErrorDialog(
                        null,
                        GuiActivator.getResources().getI18NString(
                                "service.gui.ERROR"),
                        e.getMessage(),
                        e)
                    .showDialog();
            }
        }
    }

    /**
     * Hangs up a specific <tt>Call</tt> (i.e. all <tt>CallPeer</tt>s associated
     * with a <tt>Call</tt>), <tt>CallConference</tt> (i.e. all <tt>Call</tt>s
     * participating in a <tt>CallConference</tt>), or <tt>CallPeer</tt>.
     */
    private static class HangupCallThread
        extends Thread
    {
        private final Call call;

        private final CallConference conference;

        private final CallPeer peer;

        /**
         * Initializes a new <tt>HangupCallThread</tt> instance which is to hang
         * up a specific <tt>Call</tt> i.e. all <tt>CallPeer</tt>s associated
         * with the <tt>Call</tt>.
         *
         * @param call the <tt>Call</tt> whose associated <tt>CallPeer</tt>s are
         * to be hanged up
         */
        public HangupCallThread(Call call)
        {
            this(call, null, null);
        }

        /**
         * Initializes a new <tt>HangupCallThread</tt> instance which is to hang
         * up a specific <tt>CallConference</tt> i.e. all <tt>Call</tt>s
         * participating in the <tt>CallConference</tt>.
         *
         * @param conference the <tt>CallConference</tt> whose participating
         * <tt>Call</tt>s re to be hanged up
         */
        public HangupCallThread(CallConference conference)
        {
            this(null, conference, null);
        }

        /**
         * Initializes a new <tt>HangupCallThread</tt> instance which is to hang
         * up a specific <tt>CallPeer</tt>.
         *
         * @param peer the <tt>CallPeer</tt> to hang up
         */
        public HangupCallThread(CallPeer peer)
        {
            this(null, null, peer);
        }

        /**
         * Initializes a new <tt>HangupCallThread</tt> instance which is to hang
         * up a specific <tt>Call</tt>, <tt>CallConference</tt>, or
         * <tt>CallPeer</tt>.
         *
         * @param call the <tt>Call</tt> whose associated <tt>CallPeer</tt>s are
         * to be hanged up
         * @param conference the <tt>CallConference</tt> whose participating
         * <tt>Call</tt>s re to be hanged up
         * @param peer the <tt>CallPeer</tt> to hang up
         */
        private HangupCallThread(
                Call call,
                CallConference conference,
                CallPeer peer)
        {
            this.call = call;
            this.conference = conference;
            this.peer = peer;
        }

        @Override
        public void run()
        {
            /*
             * There is only an OperationSet which hangs up a CallPeer at a time
             * so prepare a list of all CallPeers to be hanged up.
             */
            Set<CallPeer> peers = new HashSet<CallPeer>();

            if (call != null)
            {
                Iterator<? extends CallPeer> peerIter = call.getCallPeers();

                while (peerIter.hasNext())
                    peers.add(peerIter.next());
            }

            if (conference != null)
                peers.addAll(conference.getCallPeers());

            if (peer != null)
                peers.add(peer);

            for (CallPeer peer : peers)
            {
                OperationSetBasicTelephony<?> basicTelephony
                    = peer.getProtocolProvider().getOperationSet(
                            OperationSetBasicTelephony.class);

                try
                {
                    basicTelephony.hangupCallPeer(peer);
                }
                catch (OperationFailedException ofe)
                {
                    logger.error("Could not hang up: " + peer, ofe);
                }
            }
        }
    }

    /**
     * Creates the enable local video call thread.
     */
    private static class EnableLocalVideoThread
        extends Thread
    {
        private final Call call;

        private final boolean enable;

        /**
         * Creates the enable local video call thread.
         *
         * @param call the call, for which to enable/disable
         * @param enable
         */
        public EnableLocalVideoThread(Call call, boolean enable)
        {
            this.call = call;
            this.enable = enable;
        }

        @Override
        public void run()
        {
            OperationSetVideoTelephony videoTelephony
                = call.getProtocolProvider().getOperationSet(
                        OperationSetVideoTelephony.class);
            boolean enableSucceeded = false;

            if (videoTelephony != null)
            {
                // First make sure the desktop sharing is disabled.
                if (enable && isDesktopSharingEnabled(call))
                {
                    JFrame frame = DesktopSharingFrame.getFrameForCall(call);

                    if (frame != null)
                        frame.dispose();
                }

                try
                {
                    videoTelephony.setLocalVideoAllowed(call, enable);
                    enableSucceeded = true;
                }
                catch (OperationFailedException ex)
                {
                    logger.error(
                            "Failed to toggle the streaming of local video.",
                            ex);

                    ResourceManagementService r = GuiActivator.getResources();
                    String title
                        = r.getI18NString(
                                "service.gui.LOCAL_VIDEO_ERROR_TITLE");
                    String message
                        = r.getI18NString(
                                "service.gui.LOCAL_VIDEO_ERROR_MESSAGE");

                    GuiActivator.getAlertUIService().showAlertPopup(
                            title,
                            message,
                            ex);
                }
            }

            // If the operation didn't succeeded for some reason, make sure the
            // video button doesn't remain selected.
            if (enable && !enableSucceeded)
                getActiveCallContainer(call).setVideoButtonSelected(false);
        }
    }

    /**
     * Puts on hold the given <tt>CallPeer</tt>.
     */
    private static class PutOnHoldCallPeerThread
        extends Thread
    {
        private final CallPeer callPeer;

        private final boolean isOnHold;

        public PutOnHoldCallPeerThread(CallPeer callPeer, boolean isOnHold)
        {
            this.callPeer = callPeer;
            this.isOnHold = isOnHold;
        }

        @Override
        public void run()
        {
            OperationSetBasicTelephony<?> telephony
                = callPeer.getProtocolProvider().getOperationSet(
                        OperationSetBasicTelephony.class);

            try
            {
                if (isOnHold)
                    telephony.putOnHold(callPeer);
                else
                    telephony.putOffHold(callPeer);
            }
            catch (OperationFailedException ex)
            {
                logger.error(
                        "Failed to put"
                            + callPeer.getAddress()
                            + (isOnHold ? " on hold." : " off hold."),
                        ex);
            }
        }
    }

    /**
     * Merges specific existing <tt>Call</tt>s into a specific telephony
     * conference.
     */
    private static class MergeExistingCalls
        extends Thread
    {
        /**
         * The telephony conference in which {@link #calls} are to be merged.
         */
        private final CallConference conference;

        /**
         * Second call.
         */
        private final Collection<Call> calls;

        /**
         * Initializes a new <tt>MergeExistingCalls</tt> instance which is to
         * merge specific existing <tt>Call</tt>s into a specific telephony
         * conference.
         *
         * @param conference the telephony conference in which the specified
         * <tt>Call</tt>s are to be merged
         * @param calls the <tt>Call</tt>s to be merged into the specified
         * telephony conference
         */
        public MergeExistingCalls(
                CallConference conference,
                Collection<Call> calls)
        {
            this.conference = conference;
            this.calls = calls;
        }

        /**
         * Puts off hold the <tt>CallPeer</tt>s of a specific <tt>Call</tt>
         * which are locally on hold.
         *
         * @param call the <tt>Call</tt> which is to have its <tt>CallPeer</tt>s
         * put off hold
         */
        private void putOffHold(Call call)
        {
            Iterator<? extends CallPeer> peers = call.getCallPeers();
            OperationSetBasicTelephony<?> telephony
                = call.getProtocolProvider().getOperationSet(
                        OperationSetBasicTelephony.class);

            while (peers.hasNext())
            {
                CallPeer callPeer = peers.next();
                boolean putOffHold = true;

                if(callPeer instanceof MediaAwareCallPeer)
                {
                    putOffHold
                        = ((MediaAwareCallPeer<?,?,?>) callPeer)
                            .getMediaHandler()
                                .isLocallyOnHold();
                }
                if(putOffHold)
                {
                    try
                    {
                        telephony.putOffHold(callPeer);
                        Thread.sleep(400);
                    }
                    catch(Exception ofe)
                    {
                        logger.error("Failed to put off hold.", ofe);
                    }
                }
            }
        }

        @Override
        public void run()
        {
            // conference
            for (Call call : conference.getCalls())
                putOffHold(call);

            // calls
            if (!calls.isEmpty())
            {
                for(Call call : calls)
                {
                    if (conference.containsCall(call))
                        continue;

                    putOffHold(call);

                    /*
                     * Dispose of the CallPanel associated with the Call which
                     * is to be merged.
                     */
                    closeCallContainerIfNotNecessary(conference, false);

                    call.setConference(conference);
                }
            }
        }
    }

    /**
     * Shows a warning window to warn the user that she's about to start a
     * desktop sharing session.
     *
     * @return <tt>true</tt> if the user has accepted the desktop sharing
     * session; <tt>false</tt>, otherwise
     */
    private static boolean showDesktopSharingWarning()
    {
        Boolean isWarningEnabled
            = GuiActivator.getConfigurationService().getBoolean(
                    desktopSharingWarningProperty,
                    true);

        if (isWarningEnabled.booleanValue())
        {
            ResourceManagementService resources = GuiActivator.getResources();
            MessageDialog warningDialog
                = new MessageDialog(
                        null,
                        resources.getI18NString("service.gui.WARNING"),
                        resources.getI18NString(
                                "service.gui.DESKTOP_SHARING_WARNING"),
                        true);

            switch (warningDialog.showDialog())
            {
                case MessageDialog.OK_RETURN_CODE:
                    return true;
                case MessageDialog.CANCEL_RETURN_CODE:
                    return false;
                case MessageDialog.OK_DONT_ASK_CODE:
                    GuiActivator.getConfigurationService().setProperty(
                            desktopSharingWarningProperty,
                            false);
                    return true;
            }
        }

        return true;
    }

    /**
     * Normalizes the phone numbers (if any) in a list of <tt>String</tt>
     * contact addresses or phone numbers.
     *
     * @param callees the list of contact addresses or phone numbers to be
     * normalized
     */
    private static void normalizePhoneNumbers(String callees[])
    {
        for (int i = 0 ; i < callees.length ; i++)
            callees[i] = GuiActivator.getPhoneNumberI18nService()
                .normalize(callees[i]);
    }

    /**
     * Throws a <tt>RuntimeException</tt> if the current thread is not the AWT
     * event dispatching thread.
     */
    public static void assertIsEventDispatchingThread()
    {
        if (!SwingUtilities.isEventDispatchThread())
        {
            throw new RuntimeException(
                    "The methon can be called only on the AWT event dispatching"
                        + " thread.");
        }
    }

    /**
     * Finds the <tt>CallPanel</tt>, if any, which depicts a specific
     * <tt>CallConference</tt>.
     * <p>
     * <b>Note</b>: The method can be called only on the AWT event dispatching
     * thread.
     * </p>
     *
     * @param conference the <tt>CallConference</tt> to find the depicting
     * <tt>CallPanel</tt> of
     * @return the <tt>CallPanel</tt> which depicts the specified
     * <tt>CallConference</tt> if such a <tt>CallPanel</tt> exists; otherwise,
     * <tt>null</tt>
     * @throws RuntimeException if the method is not called on the AWT event
     * dispatching thread
     */
    private static CallPanel findCallPanel(CallConference conference)
    {
        synchronized (callPanels)
        {
            return callPanels.get(conference);
        }
    }

    /**
     * Notifies {@link #callPanels} about a specific <tt>CallEvent</tt> received
     * by <tt>CallManager</tt> (because they may need to update their UI, for
     * example).
     * <p>
     * <b>Note</b>: The method can be called only on the AWT event dispatching
     * thread.
     * </p>
     *
     * @param ev the <tt>CallEvent</tt> received by <tt>CallManager</tt> which
     * is to be forwarded to <tt>callPanels</tt> for further
     * <tt>CallPanel</tt>-specific handling
     * @throws RuntimeException if the method is not called on the AWT event
     * dispatching thread
     */
    private static void forwardCallEventToCallPanels(CallEvent ev)
    {
        assertIsEventDispatchingThread();

        CallPanel[] callPanels;

        synchronized (CallManager.callPanels)
        {
            Collection<CallPanel> values = CallManager.callPanels.values();

            callPanels = values.toArray(new CallPanel[values.size()]);
        }

        for (CallPanel callPanel : callPanels)
        {
            try
            {
                callPanel.onCallEvent(ev);
            }
            catch (Exception ex)
            {
                /*
                 * There is no practical reason while the failure of a CallPanel
                 * to handle the CallEvent should cause the other CallPanels to
                 * be left out-of-date.
                 */
                logger.error("A CallPanel failed to handle a CallEvent", ex);
            }
        }
    }

    /**
     * Creates a call for the supplied operation set.
     * @param opSetClass the operation set to use to create call.
     * @param protocolProviderService the protocol provider
     * @param contact the contact address to call
     */
    static void createCall(Class<? extends OperationSet> opSetClass,
                    ProtocolProviderService protocolProviderService,
                    String contact)
    {
        createCall(opSetClass, protocolProviderService, contact, null);
    }

    /**
     * Creates a call for the supplied operation set.
     * @param opSetClass the operation set to use to create call.
     * @param protocolProviderService the protocol provider
     * @param contact the contact address to call
     *  @param uiContact the <tt>MetaContact</tt> we're calling
     */
    static void createCall(
                    Class<? extends OperationSet> opSetClass,
                    ProtocolProviderService protocolProviderService,
                    String contact,
                    UIContactImpl uiContact)
    {
        if (opSetClass.equals(OperationSetBasicTelephony.class))
        {
            createCall(protocolProviderService, contact, uiContact);
        }
        else if (opSetClass.equals(OperationSetVideoTelephony.class))
        {
            createVideoCall(protocolProviderService, contact, uiContact);
        }
        else if (opSetClass.equals(OperationSetDesktopStreaming.class))
        {
            createDesktopSharing(
                protocolProviderService, contact, uiContact);
        }
    }

    /**
     * Creates a call for the default contact of the metacontact
     *
     * @param metaContact the metacontact that will be called.
     * @param isVideo if <tt>true</tt> will create video call.
     * @param isDesktop if <tt>true</tt> will share the desktop.
     * @param shareRegion if <tt>true</tt> will share a region of the desktop.
     */
    public static void call(MetaContact metaContact,
                            boolean isVideo,
                            boolean isDesktop,
                            boolean shareRegion)
    {
        Contact contact = metaContact
            .getDefaultContact(getOperationSetForCall(isVideo, isDesktop));

        call(contact, isVideo, isDesktop, shareRegion);
    }

    /**
     * A particular contact has been selected no options to select
     * will just call it.
     * @param contact the contact to call
     * @param contactResource the specific contact resource
     * @param isVideo is video enabled
     * @param isDesktop is desktop sharing enabled
     * @param shareRegion is sharing the whole desktop or just a region.
     */
    public static void call(Contact contact,
                            ContactResource contactResource,
                            boolean isVideo,
                            boolean isDesktop,
                            boolean shareRegion)
    {
        if(isDesktop)
        {
            if(shareRegion)
            {
                createRegionDesktopSharing(
                    contact.getProtocolProvider(),
                    contact.getAddress(),
                    null);
            }
            else
                createDesktopSharing(contact.getProtocolProvider(),
                                    contact.getAddress(),
                                    null);
        }
        else
        {
            new CreateCallThread(
                    contact.getProtocolProvider(),
                    contact,
                    contactResource,
                    isVideo).start();
        }
    }

    /**
     * Creates a call to the conference described in
     * <tt>conferenceDescription</tt> through <tt>protocolProvider</tt>
     *
     * @param protocolProvider the protocol provider through which to create
     * the call
     * @param conferenceDescription the description of the conference to call
     * @param chatRoom the chat room associated with the call.
     */
    public static void call(ProtocolProviderService protocolProvider,
                            ConferenceDescription conferenceDescription,
                            ChatRoom chatRoom)
    {
        new CreateCallThread(protocolProvider, conferenceDescription, chatRoom)
            .start();
    }

    /**
     * A particular contact has been selected no options to select
     * will just call it.
     * @param contact the contact to call
     * @param isVideo is video enabled
     * @param isDesktop is desktop sharing enabled
     * @param shareRegion is sharing the whole desktop or just a region.
     */
    public static void call(Contact contact,
                            boolean isVideo,
                            boolean isDesktop,
                            boolean shareRegion)
    {
        if(isDesktop)
        {
            if(shareRegion)
            {
                createRegionDesktopSharing(
                    contact.getProtocolProvider(),
                    contact.getAddress(),
                    null);
            }
            else
                createDesktopSharing(contact.getProtocolProvider(),
                                    contact.getAddress(),
                                    null);
        }
        else
        {
            new CreateCallThread(   contact.getProtocolProvider(),
                                    contact,
                                    null,
                                    isVideo).start();
        }
    }

    /**
     * Calls a phone showing a dialog to choose a provider.
     * @param phone phone to call
     * @param isVideo if <tt>true</tt> will create video call.
     * @param isDesktop if <tt>true</tt> will share the desktop.
     * @param shareRegion if <tt>true</tt> will share a region of the desktop.
     */
    public static void call(final String phone,
                            boolean isVideo,
                            boolean isDesktop,
                            final boolean shareRegion)
    {
        call(phone, null, isVideo, isDesktop, shareRegion);
    }

    /**
     * Calls a phone showing a dialog to choose a provider.
     * @param phone phone to call
     * @param uiContact the <tt>UIContactImpl</tt> we're calling
     * @param isVideo if <tt>true</tt> will create video call.
     * @param isDesktop if <tt>true</tt> will share the desktop.
     * @param shareRegion if <tt>true</tt> will share a region of the desktop.
     */
    public static void call(final String phone,
                            final UIContactImpl uiContact,
                            boolean isVideo,
                            boolean isDesktop,
                            final boolean shareRegion)
    {
        List<ProtocolProviderService> providers =
            CallManager.getTelephonyProviders();

        if(providers.size() > 1)
        {
            ChooseCallAccountDialog chooseAccount =
                new ChooseCallAccountDialog(
                    phone,
                    getOperationSetForCall(isVideo, isDesktop),
                    providers)
            {
                    @Override
                    public void callButtonPressed()
                    {
                        if(shareRegion)
                        {
                            createRegionDesktopSharing(
                                getSelectedProvider(), phone, uiContact);
                        }
                        else
                            super.callButtonPressed();
                    }
            };
            chooseAccount.setUIContact(uiContact);
            chooseAccount.setVisible(true);
        }
        else
        {
            createCall(providers.get(0), phone, uiContact);
        }
    }

    /**
     * Obtain operation set checking the params.
     * @param isVideo if <tt>true</tt> use OperationSetVideoTelephony.
     * @param isDesktop if <tt>true</tt> use OperationSetDesktopStreaming.
     * @return the operation set, default is OperationSetBasicTelephony.
     */
    private static Class<? extends OperationSet> getOperationSetForCall(
        boolean isVideo, boolean isDesktop)
    {
        if(isVideo)
        {
            if(isDesktop)
                return OperationSetDesktopStreaming.class;
            else
                return OperationSetVideoTelephony.class;
        }
        else
            return OperationSetBasicTelephony.class;
    }

    /**
     * Call any of the supplied details.
     *
     * @param uiContactDetailList the list with details to choose for calling
     * @param uiContact the <tt>UIContactImpl</tt> to check what is enabled,
     * available.
     * @param isVideo if <tt>true</tt> will create video call.
     * @param isDesktop if <tt>true</tt> will share the desktop.
     * @param invoker the invoker component
     * @param location the location where this was invoked.
     */
    public static void call(List<UIContactDetail> uiContactDetailList,
                            UIContactImpl uiContact,
                            boolean isVideo,
                            boolean isDesktop,
                            JComponent invoker,
                            Point location)
    {
        call(uiContactDetailList,
            uiContact,
            isVideo,
            isDesktop,
            invoker,
            location,
            true);
    }

    /**
     * Call any of the supplied details.
     *
     * @param uiContactDetailList the list with details to choose for calling
     * @param uiContact the <tt>UIContactImpl</tt> to check what is enabled,
     * available.
     * @param isVideo if <tt>true</tt> will create video call.
     * @param isDesktop if <tt>true</tt> will share the desktop.
     * @param invoker the invoker component
     * @param location the location where this was invoked.
     * @param usePreferredProvider whether to use the <tt>uiContact</tt>
     * preferredProvider if provided.
     */
    private static void call(List<UIContactDetail> uiContactDetailList,
                            UIContactImpl uiContact,
                            boolean isVideo,
                            boolean isDesktop,
                            JComponent invoker,
                            Point location,
                            boolean usePreferredProvider)
    {
        ChooseCallAccountPopupMenu chooseCallAccountPopupMenu = null;

        Class<? extends OperationSet> opsetClass =
            getOperationSetForCall(isVideo, isDesktop);

        UIPhoneUtil contactPhoneUtil = null;
        if (uiContact != null
            && uiContact.getDescriptor() instanceof MetaContact)
            contactPhoneUtil = UIPhoneUtil
                .getPhoneUtil((MetaContact) uiContact.getDescriptor());

        if(contactPhoneUtil != null)
        {
            boolean addAdditionalNumbers = false;
            if(!isVideo
                || ConfigurationUtils
                        .isRouteVideoAndDesktopUsingPhoneNumberEnabled())
            {
                addAdditionalNumbers = true;
            }
            else
            {
                if(isVideo && contactPhoneUtil != null)
                {
                    // lets check is video enabled in additional numbers
                    addAdditionalNumbers =
                        contactPhoneUtil.isVideoCallEnabled() ?
                            isDesktop ?
                                contactPhoneUtil.isDesktopSharingEnabled()
                                : true
                            : false;
                }
            }

            if(addAdditionalNumbers)
            {
                uiContactDetailList.addAll(
                    contactPhoneUtil.getAdditionalNumbers());
            }
        }

        if (uiContactDetailList.size() == 1)
        {
            UIContactDetail detail = uiContactDetailList.get(0);

            ProtocolProviderService preferredProvider = null;

            if(usePreferredProvider)
                preferredProvider =
                    detail.getPreferredProtocolProvider(opsetClass);

            List<ProtocolProviderService> providers = null;
            String protocolName = null;

            if (preferredProvider != null)
            {
                if (preferredProvider.isRegistered())
                {
                    createCall(opsetClass,
                               preferredProvider,
                               detail.getAddress(),
                               uiContact);
                }

                // If we have a provider, but it's not registered we try to
                // obtain all registered providers for the same protocol as the
                // given preferred provider.
                else
                {
                    protocolName = preferredProvider.getProtocolName();
                    providers = AccountUtils.getRegisteredProviders(protocolName,
                        opsetClass);
                }
            }
            // If we don't have a preferred provider we try to obtain a
            // preferred protocol name and all registered providers for it.
            else
            {
                protocolName = detail.getPreferredProtocol(opsetClass);

                if (protocolName != null)
                    providers
                        = AccountUtils.getRegisteredProviders(protocolName,
                            opsetClass);
                else
                    providers
                        = AccountUtils.getRegisteredProviders(opsetClass);
            }

            // If our call didn't succeed, try to call through one of the other
            // protocol providers obtained above.
            if (providers != null)
            {
                int providersCount = providers.size();

                if (providersCount <= 0)
                {
                    new ErrorDialog(null,
                        GuiActivator.getResources().getI18NString(
                            "service.gui.CALL_FAILED"),
                        GuiActivator.getResources().getI18NString(
                            "service.gui.NO_ONLINE_TELEPHONY_ACCOUNT"))
                    .showDialog();
                }
                else if (providersCount == 1)
                {
                    createCall(
                        opsetClass,
                        providers.get(0),
                        detail.getAddress(),
                        uiContact);
                }
                else if (providersCount > 1)
                {
                    chooseCallAccountPopupMenu =
                        new ChooseCallAccountPopupMenu(
                            invoker, detail.getAddress(), providers,
                            opsetClass);
                }
            }
        }
        else if (uiContactDetailList.size() > 1)
        {
            chooseCallAccountPopupMenu
                = new ChooseCallAccountPopupMenu(invoker, uiContactDetailList,
                        opsetClass);
        }

        // If the choose dialog is created we're going to show it.
        if (chooseCallAccountPopupMenu != null)
        {
            if (uiContact != null)
                chooseCallAccountPopupMenu.setUIContact(uiContact);

            chooseCallAccountPopupMenu.showPopupMenu(location.x, location.y);
        }
    }


    /**
     * Call the ui contact.
     *
     * @param uiContact the contact to call.
     * @param isVideo if <tt>true</tt> will create video call.
     * @param isDesktop if <tt>true</tt> will share the desktop.
     * @param invoker the invoker component
     * @param location the location where this was invoked.
     */
    public static void call(UIContact uiContact,
                            boolean isVideo,
                            boolean isDesktop,
                            JComponent invoker,
                            Point location)
    {
        UIContactImpl uiContactImpl = null;
        if(uiContact instanceof UIContactImpl)
        {
            uiContactImpl = (UIContactImpl) uiContact;
        }

        List<UIContactDetail> telephonyContacts
            = uiContact.getContactDetailsForOperationSet(
                getOperationSetForCall(isVideo, isDesktop));

        boolean ignorePreferredProvider =
            GuiActivator.getConfigurationService().getBoolean(
                IGNORE_PREFERRED_PROVIDER_PROP, false);

        call(   telephonyContacts,
                uiContactImpl,
                isVideo,
                isDesktop,
                invoker,
                location,
                !ignorePreferredProvider);
    }

    /**
     * Tries to resolves a peer address into a display name, by reqesting the
     * <tt>ContactSourceService</tt>s. This function returns only the
     * first match.
     *
     * @param peerAddress The peer address.
     * @param listener the listener to fire change events for later resolutions
     * of display name and image, if exist.
     * @return The corresponding display name, if there is a match. Null
     * otherwise.
     */
    private static String queryContactSource(
        String peerAddress,
        DetailsResolveListener listener)
    {
        String displayName = null;

        if(!StringUtils.isNullOrEmpty(peerAddress))
        {
            ContactSourceSearcher searcher
                = new ContactSourceSearcher(peerAddress, listener);

            if(listener == null)
            {
                searcher.run();
                displayName = searcher.displayName;
            }
            else
                new Thread(searcher, searcher.getClass().getName()).start();
        }

        return displayName;
    }

    /**
     * Runnable that will search for a source contact and when found will
     * fire events to inform that display name or contact image is found.
     */
    private static class ContactSourceSearcher
        implements Runnable
    {
        private final DetailsResolveListener listener;

        private final String peerAddress;

        private String displayName;
        private byte[] displayImage;

        private ContactSourceSearcher(
            String peerAddress,
            DetailsResolveListener listener)
        {
            this.peerAddress = peerAddress;
            this.listener = listener;
        }

        @Override
        public void run()
        {
            Vector<ResolveAddressToDisplayNameContactQueryListener> resolvers
                = new Vector<ResolveAddressToDisplayNameContactQueryListener>
                    (1, 1);

            // will strip the @server-address part, as the regular expression
            // will match it
            int index = peerAddress.indexOf("@");
            String peerUserID =
                (index > -1) ? peerAddress.substring(0, index) : peerAddress;

            // searches for the whole number/username or with the @serverpart
            String quotedPeerUserID = Pattern.quote(peerUserID);
            Pattern pattern = Pattern.compile(
                "^(" + quotedPeerUserID + "|" + quotedPeerUserID + "@.*)$");

            // Queries all available resolvers
            for(ContactSourceService css : GuiActivator.getContactSources())
            {
                if(css.getType() != ContactSourceService.SEARCH_TYPE)
                    continue;

                ContactQuery query;
                if(css instanceof ExtendedContactSourceService)
                {
                    // use the pattern method of (ExtendedContactSourceService)
                    query = ((ExtendedContactSourceService)css)
                        .createContactQuery(pattern);
                }
                else
                {
                    query = css.createContactQuery(peerUserID);
                }

                if(query == null)
                    continue;

                resolvers.add(
                    new ResolveAddressToDisplayNameContactQueryListener(query));
                query.start();
            }

            long startTime = System.currentTimeMillis();

            // The detault timeout is set to 500ms.
            long timeout = listener == null ? 500 : -1;
            boolean hasRunningResolver = true;
            // Loops until we found a valid display name and image,
            // or waits for timeout if any.
            while((displayName == null || displayImage == null)
                    && hasRunningResolver
                    && (listener == null || listener.isInterested()))
            {
                hasRunningResolver = false;

                for(int i = 0; i < resolvers.size()
                    && (displayName == null || displayImage == null)
                    && (listener == null || listener.isInterested()); ++i)
                {
                    ResolveAddressToDisplayNameContactQueryListener resolver
                        = resolvers.get(i);
                    if(!resolver.isRunning())
                    {
                        if(displayName == null
                            && resolver.isFoundName())
                        {
                            displayName = resolver.getResolvedName();
                            // If this is the same result as the peer address,
                            // then that is not what we are looking for. Then,
                            // continue the search.
                            if(displayName.equals(peerAddress))
                            {
                                displayName = null;
                            }

                            if(listener != null && displayName != null)
                            {
                                // fire
                                listener.displayNameUpdated(displayName);
                            }
                        }

                        if(displayImage == null
                            && resolver.isFoundImage())
                        {
                            displayImage = resolver.getResolvedImage();

                            String name = resolver.getResolvedName();
                            // If this is the same result as the peer address,
                            // then that is not what we are looking for. Then,
                            // continue the search.
                            if(name != null && name.equals(peerAddress))
                            {
                                displayImage = null;
                            }
                            else if(listener != null && displayImage != null)
                            {
                                // fire
                                listener.imageUpdated(displayImage);
                            }
                        }
                    }
                    else
                        hasRunningResolver = true;
                }
                Thread.yield();

                if( timeout > 0 &&
                    System.currentTimeMillis() - startTime >= timeout)
                    break;
            }

            // Free lasting resolvers.
            for(int i = 0; i < resolvers.size(); ++i)
            {
                ResolveAddressToDisplayNameContactQueryListener resolver
                    = resolvers.get(i);
                if(resolver.isRunning())
                {
                    resolver.stop();
                }
            }
        }
    }

    /**
     * A listener that will be notified for found source contacts details.
     */
    public static interface DetailsResolveListener
    {
        /**
         * When a display name is found.
         * @param displayName the name that was found.
         */
        public void displayNameUpdated(String displayName);

        /**
         * The image that was found.
         * @param image the image that was found.
         */
        public void imageUpdated(byte[] image);

        /**
         * Whether the listener is still interested in the events.
         * When the window/panel using this resolver listener is closed
         * will return false;
         * @return whether the listener is still interested in the events.
         */
        public boolean isInterested();
    }
}