This file is indexed.

/usr/lib/python2.7/dist-packages/radialnet/gui/RadialNet.py is in zenmap 7.40-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# vim: set encoding=utf-8 :

# ***********************IMPORTANT NMAP LICENSE TERMS************************
# *                                                                         *
# * The Nmap Security Scanner is (C) 1996-2016 Insecure.Com LLC. Nmap is    *
# * also a registered trademark of Insecure.Com LLC.  This program is free  *
# * software; you may redistribute and/or modify it under the terms of the  *
# * GNU General Public License as published by the Free Software            *
# * Foundation; Version 2 ("GPL"), BUT ONLY WITH ALL OF THE CLARIFICATIONS  *
# * AND EXCEPTIONS DESCRIBED HEREIN.  This guarantees your right to use,    *
# * modify, and redistribute this software under certain conditions.  If    *
# * you wish to embed Nmap technology into proprietary software, we sell    *
# * alternative licenses (contact sales@nmap.com).  Dozens of software      *
# * vendors already license Nmap technology such as host discovery, port    *
# * scanning, OS detection, version detection, and the Nmap Scripting       *
# * Engine.                                                                 *
# *                                                                         *
# * Note that the GPL places important restrictions on "derivative works",  *
# * yet it does not provide a detailed definition of that term.  To avoid   *
# * misunderstandings, we interpret that term as broadly as copyright law   *
# * allows.  For example, we consider an application to constitute a        *
# * derivative work for the purpose of this license if it does any of the   *
# * following with any software or content covered by this license          *
# * ("Covered Software"):                                                   *
# *                                                                         *
# * o Integrates source code from Covered Software.                         *
# *                                                                         *
# * o Reads or includes copyrighted data files, such as Nmap's nmap-os-db   *
# * or nmap-service-probes.                                                 *
# *                                                                         *
# * o Is designed specifically to execute Covered Software and parse the    *
# * results (as opposed to typical shell or execution-menu apps, which will *
# * execute anything you tell them to).                                     *
# *                                                                         *
# * o Includes Covered Software in a proprietary executable installer.  The *
# * installers produced by InstallShield are an example of this.  Including *
# * Nmap with other software in compressed or archival form does not        *
# * trigger this provision, provided appropriate open source decompression  *
# * or de-archiving software is widely available for no charge.  For the    *
# * purposes of this license, an installer is considered to include Covered *
# * Software even if it actually retrieves a copy of Covered Software from  *
# * another source during runtime (such as by downloading it from the       *
# * Internet).                                                              *
# *                                                                         *
# * o Links (statically or dynamically) to a library which does any of the  *
# * above.                                                                  *
# *                                                                         *
# * o Executes a helper program, module, or script to do any of the above.  *
# *                                                                         *
# * This list is not exclusive, but is meant to clarify our interpretation  *
# * of derived works with some common examples.  Other people may interpret *
# * the plain GPL differently, so we consider this a special exception to   *
# * the GPL that we apply to Covered Software.  Works which meet any of     *
# * these conditions must conform to all of the terms of this license,      *
# * particularly including the GPL Section 3 requirements of providing      *
# * source code and allowing free redistribution of the work as a whole.    *
# *                                                                         *
# * As another special exception to the GPL terms, Insecure.Com LLC grants  *
# * permission to link the code of this program with any version of the     *
# * OpenSSL library which is distributed under a license identical to that  *
# * listed in the included docs/licenses/OpenSSL.txt file, and distribute   *
# * linked combinations including the two.                                  *
# *                                                                         *
# * Any redistribution of Covered Software, including any derived works,    *
# * must obey and carry forward all of the terms of this license, including *
# * obeying all GPL rules and restrictions.  For example, source code of    *
# * the whole work must be provided and free redistribution must be         *
# * allowed.  All GPL references to "this License", are to be treated as    *
# * including the terms and conditions of this license text as well.        *
# *                                                                         *
# * Because this license imposes special exceptions to the GPL, Covered     *
# * Work may not be combined (even as part of a larger work) with plain GPL *
# * software.  The terms, conditions, and exceptions of this license must   *
# * be included as well.  This license is incompatible with some other open *
# * source licenses as well.  In some cases we can relicense portions of    *
# * Nmap or grant special permissions to use it in other open source        *
# * software.  Please contact fyodor@nmap.org with any such requests.       *
# * Similarly, we don't incorporate incompatible open source software into  *
# * Covered Software without special permission from the copyright holders. *
# *                                                                         *
# * If you have any questions about the licensing restrictions on using     *
# * Nmap in other works, are happy to help.  As mentioned above, we also    *
# * offer alternative license to integrate Nmap into proprietary            *
# * applications and appliances.  These contracts have been sold to dozens  *
# * of software vendors, and generally include a perpetual license as well  *
# * as providing for priority support and updates.  They also fund the      *
# * continued development of Nmap.  Please email sales@nmap.com for further *
# * information.                                                            *
# *                                                                         *
# * If you have received a written license agreement or contract for        *
# * Covered Software stating terms other than these, you may choose to use  *
# * and redistribute Covered Software under those terms instead of these.   *
# *                                                                         *
# * Source is provided to this software because we believe users have a     *
# * right to know exactly what a program is going to do before they run it. *
# * This also allows you to audit the software for security holes.          *
# *                                                                         *
# * Source code also allows you to port Nmap to new platforms, fix bugs,    *
# * and add new features.  You are highly encouraged to send your changes   *
# * to the dev@nmap.org mailing list for possible incorporation into the    *
# * main distribution.  By sending these changes to Fyodor or one of the    *
# * Insecure.Org development mailing lists, or checking them into the Nmap  *
# * source code repository, it is understood (unless you specify otherwise) *
# * that you are offering the Nmap Project (Insecure.Com LLC) the           *
# * unlimited, non-exclusive right to reuse, modify, and relicense the      *
# * code.  Nmap will always be available Open Source, but this is important *
# * because the inability to relicense code has caused devastating problems *
# * for other Free Software projects (such as KDE and NASM).  We also       *
# * occasionally relicense the code to third parties as discussed above.    *
# * If you wish to specify special license conditions of your               *
# * contributions, just say so when you send them.                          *
# *                                                                         *
# * This program is distributed in the hope that it will be useful, but     *
# * WITHOUT ANY WARRANTY; without even the implied warranty of              *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the Nmap      *
# * license file for more details (it's in a COPYING file included with     *
# * Nmap, and also available from https://svn.nmap.org/nmap/COPYING)        *
# *                                                                         *
# ***************************************************************************/

import gtk
import math
import time
import copy
import cairo
import gobject

import radialnet.util.drawing as drawing
import radialnet.util.geometry as geometry
import radialnet.util.misc as misc

from radialnet.core.Coordinate import PolarCoordinate, CartesianCoordinate
from radialnet.core.Interpolation import Linear2DInterpolator
from radialnet.core.Graph import Graph, Node
from radialnet.gui.NodeWindow import NodeWindow
from radialnet.gui.Image import Icons, get_pixels_for_cairo_image_surface

from zenmapCore.BasePaths import fs_enc

REGION_COLORS = [(1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0)]
REGION_RED = 0
REGION_YELLOW = 1
REGION_GREEN = 2

SQUARE_TYPES = ['router', 'switch', 'wap']

ICON_DICT = {'router': 'router',
             'switch': 'switch',
             'wap': 'wireless',
             'firewall': 'firewall'}

POINTER_JUMP_TO = 0
POINTER_INFO = 1
POINTER_GROUP = 2
POINTER_FILL = 3

LAYOUT_SYMMETRIC = 0
LAYOUT_WEIGHTED = 1

INTERPOLATION_CARTESIAN = 0
INTERPOLATION_POLAR = 1

FILE_TYPE_PDF = 1
FILE_TYPE_PNG = 2
FILE_TYPE_PS = 3
FILE_TYPE_SVG = 4


class RadialNet(gtk.DrawingArea):
    """
    Radial network visualization widget
    """
    def __init__(self, layout=LAYOUT_SYMMETRIC):
        """
        Constructor method of RadialNet widget class
        @type  number_of_rings: number
        @param number_of_rings: Number of rings in radial layout
        """
        self.__center_of_widget = (0, 0)
        self.__graph = None

        self.__number_of_rings = 0
        self.__ring_gap = 30
        self.__min_ring_gap = 10

        self.__layout = layout
        self.__interpolation = INTERPOLATION_POLAR
        self.__interpolation_slow_in_out = True

        self.__animating = False
        self.__animation_rate = 1000 / 60  # 60Hz (human perception factor)
        self.__number_of_frames = 60

        self.__scale = 1.0
        # rotated so that single-host traceroute doesn't have overlapping hosts
        self.__rotate = 225
        self.__translation = (0, 0)

        self.__button1_press = False
        self.__button2_press = False
        self.__button3_press = False

        self.__last_motion_point = None

        self.__fisheye = False
        self.__fisheye_ring = 0
        self.__fisheye_spread = 0.5
        self.__fisheye_interest = 2

        self.__show_address = True
        self.__show_hostname = True
        self.__show_icon = True
        self.__show_latency = False
        self.__show_ring = True
        self.__show_region = True
        self.__region_color = REGION_RED

        self.__node_views = dict()
        self.__last_group_node = None

        self.__pointer_status = POINTER_JUMP_TO

        self.__sorted_nodes = list()

        self.__icon = Icons()

        super(RadialNet, self).__init__()

        self.connect('expose_event', self.expose)
        self.connect('button_press_event', self.button_press)
        self.connect('button_release_event', self.button_release)
        self.connect('motion_notify_event', self.motion_notify)
        self.connect('enter_notify_event', self.enter_notify)
        self.connect('leave_notify_event', self.leave_notify)
        self.connect('key_press_event', self.key_press)
        self.connect('key_release_event', self.key_release)
        self.connect('scroll_event', self.scroll_event)

        self.add_events(gtk.gdk.BUTTON_PRESS_MASK |
                        gtk.gdk.BUTTON_RELEASE_MASK |
                        gtk.gdk.ENTER_NOTIFY |
                        gtk.gdk.LEAVE_NOTIFY |
                        gtk.gdk.MOTION_NOTIFY |
                        gtk.gdk.NOTHING |
                        gtk.gdk.KEY_PRESS_MASK |
                        gtk.gdk.KEY_RELEASE_MASK |
                        gtk.gdk.POINTER_MOTION_HINT_MASK |
                        gtk.gdk.POINTER_MOTION_MASK |
                        gtk.gdk.SCROLL_MASK)

        self.set_flags(gtk.CAN_FOCUS)
        self.grab_focus()

    def graph_is_not_empty(function):
        """
        Decorator function to prevent the execution when graph not is set
        @type  function: function
        @param function: Protected function
        """
        def check_graph_status(*args):
            if args[0].__graph is None:
                return False
            return function(*args)

        return check_graph_status

    def not_is_in_animation(function):
        """
        Decorator function to prevent the execution when graph is animating
        @type  function: function
        @param function: Protected function
        """
        def check_animation_status(*args):
            if args[0].__animating:
                return False
            return function(*args)

        return check_animation_status

    def save_drawing_to_file(self, file, type=FILE_TYPE_PNG):
        """
        """
        allocation = self.get_allocation()

        if type == FILE_TYPE_PDF:
            self.surface = cairo.PDFSurface(file,
                    allocation.width,
                    allocation.height)
        elif type == FILE_TYPE_PNG:
            self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                    allocation.width,
                    allocation.height)
        elif type == FILE_TYPE_PS:
            self.surface = cairo.PSSurface(file,
                    allocation.width,
                    allocation.height)
        elif type == FILE_TYPE_SVG:
            self.surface = cairo.SVGSurface(file,
                    allocation.width,
                    allocation.height)
        else:
            raise TypeError('unknown surface type')

        context = cairo.Context(self.surface)

        context.rectangle(0, 0, allocation.width, allocation.height)
        context.set_source_rgb(1.0, 1.0, 1.0)
        context.fill()

        self.__draw(context)

        if type == FILE_TYPE_PNG:
            # write_to_png requires a str, not unicode, in py2cairo 1.8.10 and
            # earlier.
            self.surface.write_to_png(fs_enc(file))

        self.surface.flush()
        self.surface.finish()

        return True

    def get_slow_inout(self):
        """
        """
        return self.__interpolation_slow_in_out

    def set_slow_inout(self, value):
        """
        """
        self.__interpolation_slow_in_out = value

    def get_region_color(self):
        """
        """
        return self.__region_color

    def set_region_color(self, value):
        """
        """
        self.__region_color = value

    def get_show_region(self):
        """
        """
        return self.__show_region

    def set_show_region(self, value):
        """
        """
        self.__show_region = value
        self.queue_draw()

    def get_pointer_status(self):
        """
        """
        return self.__pointer_status

    def set_pointer_status(self, pointer_status):
        """
        """
        self.__pointer_status = pointer_status

    def get_show_address(self):
        """
        """
        return self.__show_address

    def get_show_hostname(self):
        """
        """
        return self.__show_hostname

    def get_show_ring(self):
        """
        """
        return self.__show_ring

    def set_show_address(self, value):
        """
        """
        self.__show_address = value
        self.queue_draw()

    def set_show_hostname(self, value):
        """
        """
        self.__show_hostname = value
        self.queue_draw()

    def set_show_ring(self, value):
        """
        """
        self.__show_ring = value
        self.queue_draw()

    def get_min_ring_gap(self):
        """
        """
        return self.__min_ring_gap

    @graph_is_not_empty
    @not_is_in_animation
    def set_min_ring_gap(self, value):
        """
        """
        self.__min_ring_gap = int(value)

        if self.__ring_gap < self.__min_ring_gap:
            self.__ring_gap = self.__min_ring_gap

        self.__update_nodes_positions()
        self.queue_draw()

        return True

    def get_number_of_frames(self):
        """
        """
        return self.__number_of_frames

    @not_is_in_animation
    def set_number_of_frames(self, number_of_frames):
        """
        """
        if number_of_frames > 2:

            self.__number_of_frames = int(number_of_frames)
            return True

        self.__number_of_frames = 3
        return False

    @not_is_in_animation
    def update_layout(self):
        """
        """
        if self.__graph is None:
            return
        self.__animating = True
        self.__calc_interpolation(self.__graph.get_main_node())
        self.__livens_up()

    @not_is_in_animation
    def set_layout(self, layout):
        """
        """
        if self.__layout != layout:

            self.__layout = layout

            if self.__graph is not None:

                self.__animating = True
                self.__calc_interpolation(self.__graph.get_main_node())
                self.__livens_up()

            return True

        return False

    def get_layout(self):
        """
        """
        return self.__layout

    @not_is_in_animation
    def set_interpolation(self, interpolation):
        """
        """
        self.__interpolation = interpolation

        return True

    def get_interpolation(self):
        """
        """
        return self.__interpolation

    def get_number_of_rings(self):
        """
        """
        return self.__number_of_rings

    def get_fisheye_ring(self):
        """
        """
        return self.__fisheye_ring

    def get_fisheye_interest(self):
        """
        """
        return self.__fisheye_interest

    def get_fisheye_spread(self):
        """
        """
        return self.__fisheye_spread

    def get_fisheye(self):
        """
        """
        return self.__fisheye

    def set_fisheye(self, enable):
        """
        """
        self.__fisheye = enable

        self.__update_nodes_positions()
        self.queue_draw()

    def set_fisheye_ring(self, value):
        """
        """
        self.__fisheye_ring = value
        self.__check_fisheye_ring()

        self.__update_nodes_positions()
        self.queue_draw()

    def set_fisheye_interest(self, value):
        """
        """
        self.__fisheye_interest = value

        self.__update_nodes_positions()
        self.queue_draw()

    def set_fisheye_spread(self, value):
        """
        """
        self.__fisheye_spread = value

        self.__update_nodes_positions()
        self.queue_draw()

    def get_show_icon(self):
        """
        """
        return self.__show_icon

    def set_show_icon(self, value):
        """
        """
        self.__show_icon = value
        self.queue_draw()

    def get_show_latency(self):
        """
        """
        return self.__show_latency

    def set_show_latency(self, value):
        """
        """
        self.__show_latency = value
        self.queue_draw()

    def get_scale(self):
        """
        """
        return self.__scale

    def get_zoom(self):
        """
        """
        return int(round(self.__scale * 100))

    def set_scale(self, scale):
        """
        """
        if scale >= 0.01:

            self.__scale = scale
            self.queue_draw()

    def set_zoom(self, zoom):
        """
        """
        if float(zoom) >= 1:

            self.set_scale(float(zoom) / 100.0)
            self.queue_draw()

    def get_ring_gap(self):
        """
        """
        return self.__ring_gap

    @not_is_in_animation
    def set_ring_gap(self, ring_gap):
        """
        """
        if ring_gap >= self.__min_ring_gap:

            self.__ring_gap = ring_gap
            self.__update_nodes_positions()
            self.queue_draw()

    def scroll_event(self, widget, event):
        """
        """
        if event.direction == gtk.gdk.SCROLL_UP:
            self.set_scale(self.__scale + 0.01)

        if event.direction == gtk.gdk.SCROLL_DOWN:
            self.set_scale(self.__scale - 0.01)

        self.queue_draw()

    @graph_is_not_empty
    @not_is_in_animation
    def key_press(self, widget, event):
        """
        """
        key = gtk.gdk.keyval_name(event.keyval)

        if key == 'KP_Add':
            self.set_ring_gap(self.__ring_gap + 1)

        elif key == 'KP_Subtract':
            self.set_ring_gap(self.__ring_gap - 1)

        elif key == 'Page_Up':
            self.set_scale(self.__scale + 0.01)

        elif key == 'Page_Down':
            self.set_scale(self.__scale - 0.01)

        self.queue_draw()

        return True

    @graph_is_not_empty
    def key_release(self, widget, event):
        """
        """
        key = gtk.gdk.keyval_name(event.keyval)

        if key == 'c':
            self.__translation = (0, 0)

        elif key == 'r':
            self.__show_ring = not self.__show_ring

        elif key == 'a':
            self.__show_address = not self.__show_address

        elif key == 'h':
            self.__show_hostname = not self.__show_hostname

        elif key == 'i':
            self.__show_icon = not self.__show_icon

        elif key == 'l':
            self.__show_latency = not self.__show_latency

        self.queue_draw()

        return True

    @graph_is_not_empty
    @not_is_in_animation
    def enter_notify(self, widget, event):
        """
        """
        self.grab_focus()
        return False

    @graph_is_not_empty
    @not_is_in_animation
    def leave_notify(self, widget, event):
        """
        """
        for node in self.__graph.get_nodes():
            node.set_draw_info({'over': False})

        self.queue_draw()

        return False

    @graph_is_not_empty
    def button_press(self, widget, event):
        """
        Drawing callback
        @type  widget: GtkWidget
        @param widget: Gtk widget superclass
        @type  event: GtkEvent
        @param event: Gtk event of widget
        @rtype: boolean
        @return: Indicator of the event propagation
        """
        result = self.__get_node_by_coordinate(self.get_pointer())

        if event.button == 1:
            self.__button1_press = True

        # animate if node is pressed
        if self.__pointer_status == POINTER_JUMP_TO and event.button == 1:

            # prevent double animation
            if self.__animating:
                return False

            if result is not None:

                node, point = result
                main_node = self.__graph.get_main_node()

                if node != main_node:

                    if node.get_draw_info('group'):

                        node.set_draw_info({'group': False})
                        node.set_subtree_info({'grouped': False,
                                               'group_node': None})

                    self.__animating = True
                    self.__calc_interpolation(node)
                    self.__livens_up()

        # group node if it's pressed
        elif self.__pointer_status == POINTER_GROUP and event.button == 1:

            # prevent group on animation
            if self.__animating:
                return False

            if result is not None:

                node, point = result
                main_node = self.__graph.get_main_node()

                if node != main_node:

                    if node.get_draw_info('group'):

                        node.set_draw_info({'group': False})
                        node.set_subtree_info({'grouped': False,
                                               'group_node': None})

                    else:

                        self.__last_group_node = node

                        node.set_draw_info({'group': True})
                        node.set_subtree_info({'grouped': True,
                                               'group_node': node})

                self.__animating = True
                self.__calc_interpolation(self.__graph.get_main_node())
                self.__livens_up()

        # setting to show node's region
        elif self.__pointer_status == POINTER_FILL and event.button == 1:

            if result is not None:

                node, point = result

                if node.get_draw_info('region') == self.__region_color:
                    node.set_draw_info({'region': None})

                else:
                    node.set_draw_info({'region': self.__region_color})

                self.queue_draw()

        # show node details
        elif event.button == 3 or self.__pointer_status == POINTER_INFO:

            if event.button == 3:
                self.__button3_press = True

            if result is not None:

                xw, yw = self.window.get_origin()
                node, point = result
                x, y = point

                if node in self.__node_views.keys():

                    self.__node_views[node].present()

                elif node.get_draw_info('scanned'):

                    view = NodeWindow(node, (int(xw + x), int(yw + y)))

                    def close_view(view, event, node):
                        view.destroy()
                        del self.__node_views[node]

                    view.connect("delete-event", close_view, node)
                    view.show_all()
                    self.__node_views[node] = view

        return False

    @graph_is_not_empty
    def button_release(self, widget, event):
        """
        Drawing callback
        @type  widget: GtkWidget
        @param widget: Gtk widget superclass
        @type  event: GtkEvent
        @param event: Gtk event of widget
        @rtype: boolean
        @return: Indicator of the event propagation
        """
        if event.button == 1:
            self.__button1_press = False

        if event.button == 2:
            self.__button2_press = False

        if event.button == 3:
            self.__button3_press = False

        self.grab_focus()

        return False

    @graph_is_not_empty
    def motion_notify(self, widget, event):
        """
        Drawing callback
        @type  widget: GtkWidget
        @param widget: Gtk widget superclass
        @type  event: GtkEvent
        @param event: Gtk event of widget
        @rtype: boolean
        @return: Indicator of the event propagation
        """
        xc, yc = self.__center_of_widget
        pointer = self.get_pointer()

        for node in self.__graph.get_nodes():
            node.set_draw_info({'over': False})

        result = self.__get_node_by_coordinate(self.get_pointer())

        if result is not None:
            result[0].set_draw_info({'over': True})

        elif self.__button1_press and self.__last_motion_point is not None:

            ax, ay = pointer
            ox, oy = self.__last_motion_point
            tx, ty = self.__translation

            self.__translation = (tx + ax - ox, ty - ay + oy)

        self.__last_motion_point = pointer

        self.grab_focus()
        self.queue_draw()

        return False

    def expose(self, widget, event):
        """
        Drawing callback
        @type  widget: GtkWidget
        @param widget: Gtk widget superclass
        @type  event: GtkEvent
        @param event: Gtk event of widget
        @rtype: boolean
        @return: Indicator of the event propagation
        """
        allocation = self.get_allocation()

        context = widget.window.cairo_create()

        context.rectangle(*event.area)
        context.set_source_rgb(1.0, 1.0, 1.0)
        context.fill()

        self.__draw(context)

        return False

    @graph_is_not_empty
    def __draw(self, context):
        """
        Drawing method
        """
        # getting allocation reference
        allocation = self.get_allocation()

        self.__center_of_widget = (allocation.width / 2,
                                   allocation.height / 2)

        aw, ah = allocation.width, allocation.height
        xc, yc = self.__center_of_widget

        ax, ay = self.__translation

        # xc = 320 yc = 240

        # -1.5 | -0.5 ( 480,  360)
        # -1.0 |  0.0 ( 320,  240)
        # -0.5 |  0.5 ( 160,  120)
        #  0.0 |  1.0 (   0,    0)
        #  0.5 |  1.5 (-160, -120)
        #  1.0 |  2.0 (-320, -240)
        #  1.5 |  2.5 (-480, -360)

        # scaling and translate
        factor = -(self.__scale - 1)

        context.translate(xc * factor + ax, yc * factor - ay)

        if self.__scale != 1.0:
            context.scale(self.__scale, self.__scale)

        # drawing over node's region
        if self.__show_region and not self.__animating:

            for node in self.__sorted_nodes:

                not_grouped = not node.get_draw_info('grouped')

                if node.get_draw_info('region') is not None and not_grouped:

                    x, y = node.get_cartesian_coordinate()
                    xc, yc = self.__center_of_widget
                    r, g, b = REGION_COLORS[node.get_draw_info('region')]

                    start, final = node.get_draw_info('range')

                    i_radius = node.get_coordinate_radius()
                    f_radius = self.__calc_radius(self.__number_of_rings - 1)

                    is_fill_all = abs(final - start) == 360

                    final = math.radians(final + self.__rotate)
                    start = math.radians(start + self.__rotate)

                    context.move_to(xc, yc)
                    context.set_source_rgba(r, g, b, 0.1)
                    context.new_path()
                    context.arc(xc, yc, i_radius, -final, -start)
                    context.arc_negative(xc, yc, f_radius, -start, -final)
                    context.close_path()
                    context.fill()
                    context.stroke()

                    if not is_fill_all:

                        context.set_source_rgb(r, g, b)
                        context.set_line_width(1)

                        xa, ya = PolarCoordinate(
                                i_radius, final).to_cartesian()
                        xb, yb = PolarCoordinate(
                                f_radius, final).to_cartesian()

                        context.move_to(xc + xa, yc - ya)
                        context.line_to(xc + xb, yc - yb)
                        context.stroke()

                        xa, ya = PolarCoordinate(
                                i_radius, start).to_cartesian()
                        xb, yb = PolarCoordinate(
                                f_radius, start).to_cartesian()

                        context.move_to(xc + xa, yc - ya)
                        context.line_to(xc + xb, yc - yb)
                        context.stroke()

        # drawing network rings
        if self.__show_ring and not self.__animating:

            for i in range(1, self.__number_of_rings):

                radius = self.__calc_radius(i)

                context.arc(xc, yc, radius, 0, 2 * math.pi)
                context.set_source_rgb(0.8, 0.8, 0.8)
                context.set_line_width(1)
                context.stroke()

        # drawing nodes and your connections
        for edge in self.__graph.get_edges():

            # check group constraints for edges
            a, b = edge.get_nodes()

            a_is_grouped = a.get_draw_info('grouped')
            b_is_grouped = b.get_draw_info('grouped')

            a_is_group = a.get_draw_info('group')
            b_is_group = b.get_draw_info('group')

            a_group = a.get_draw_info('group_node')
            b_group = b.get_draw_info('group_node')

            a_is_child = a in b.get_draw_info('children')
            b_is_child = b in a.get_draw_info('children')

            last_group = self.__last_group_node
            groups = [a_group, b_group]

            if last_group in groups and last_group is not None:
                self.__draw_edge(context, edge)

            elif not a_is_grouped or not b_is_grouped:

                if not (a_is_group and b_is_child or
                        b_is_group and a_is_child):
                    self.__draw_edge(context, edge)

            elif a_group != b_group:
                self.__draw_edge(context, edge)

        for node in reversed(self.__sorted_nodes):

            # check group constraints for nodes
            group = node.get_draw_info('group_node')
            grouped = node.get_draw_info('grouped')

            if group == self.__last_group_node or not grouped:
                self.__draw_node(context, node)

    def __draw_edge(self, context, edge):
        """
        Draw the connection between two nodes
        @type  : Edge
        @param : The second node that will be connected
        """
        a, b = edge.get_nodes()

        xa, ya = a.get_cartesian_coordinate()
        xb, yb = b.get_cartesian_coordinate()
        xc, yc = self.__center_of_widget

        a_children = a.get_draw_info('children')
        b_children = b.get_draw_info('children')

        latency = edge.get_weights_mean()

        # check if isn't an hierarchy connection
        if a not in b_children and b not in a_children:
            context.set_source_rgba(1.0, 0.6, 0.1, 0.8)

        elif a.get_draw_info('no_route') or b.get_draw_info('no_route'):
            context.set_source_rgba(0.0, 0.0, 0.0, 0.8)

        else:
            context.set_source_rgba(0.1, 0.5, 1.0, 0.8)

        # calculating line thickness by latency
        if latency is not None:

            min = self.__graph.get_min_edge_mean_weight()
            max = self.__graph.get_max_edge_mean_weight()

            if max != min:
                thickness = (latency - min) * 4 / (max - min) + 1

            else:
                thickness = 1

            context.set_line_width(thickness)

        else:

            context.set_dash([2, 2])
            context.set_line_width(1)

        context.move_to(xc + xa, yc - ya)
        context.line_to(xc + xb, yc - yb)
        context.stroke()

        context.set_dash([1, 0])

        if not self.__animating and self.__show_latency:

            if latency is not None:

                context.set_font_size(8)
                context.set_line_width(1)
                context.move_to(xc + (xa + xb) / 2 + 1,
                                     yc - (ya + yb) / 2 + 4)
                context.show_text(str(round(latency, 2)))
                context.stroke()

    def __draw_node(self, context, node):
        """
        Draw nodes and your information
        @type  : NetNode
        @param : The node to be drawn
        """
        x, y = node.get_cartesian_coordinate()
        xc, yc = self.__center_of_widget
        r, g, b = node.get_draw_info('color')
        radius = node.get_draw_info('radius')

        type = node.get_info('device_type')

        x_gap = radius + 2
        y_gap = 0

        # draw group indication
        if node.get_draw_info('group'):

            x_gap += 5

            if type in SQUARE_TYPES:
                context.rectangle(xc + x - radius - 5,
                                       yc - y - radius - 5,
                                       2 * radius + 10,
                                       2 * radius + 10)

            else:
                context.arc(xc + x, yc - y, radius + 5, 0, 2 * math.pi)

            context.set_source_rgb(1.0, 1.0, 1.0)
            context.fill_preserve()

            if node.deep_search_child(self.__graph.get_main_node()):
                context.set_source_rgb(0.0, 0.0, 0.0)

            else:
                context.set_source_rgb(0.1, 0.5, 1.0)

            context.set_line_width(2)
            context.stroke()

        # draw over node
        if node.get_draw_info('over'):

            context.set_line_width(0)

            if type in SQUARE_TYPES:
                context.rectangle(xc + x - radius - 5,
                                       yc - y - radius - 5,
                                       2 * radius + 10,
                                       2 * radius + 10)

            else:
                context.arc(xc + x, yc - y, radius + 5, 0, 2 * math.pi)

            context.set_source_rgb(0.1, 0.5, 1.0)
            context.fill_preserve()
            context.stroke()

        # draw node
        if type in SQUARE_TYPES:
            context.rectangle(xc + x - radius,
                                   yc - y - radius,
                                   2 * radius,
                                   2 * radius)

        else:
            context.arc(xc + x, yc - y, radius, 0, 2 * math.pi)

        # draw icons
        if not self.__animating and self.__show_icon:

            icons = list()

            if type in ICON_DICT.keys():
                icons.append(self.__icon.get_pixbuf(ICON_DICT[type]))

            if node.get_info('filtered'):
                icons.append(self.__icon.get_pixbuf('padlock'))

            for icon in icons:

                stride, data = get_pixels_for_cairo_image_surface(icon)

                # Cairo documentation says that the correct way to obtain a
                # legal stride value is using the function
                # cairo.ImageSurface.format_stride_for_width().
                # But this method is only available since cairo 1.6. So we are
                # using the stride returned by
                # get_pixels_for_cairo_image_surface() function.
                surface = cairo.ImageSurface.create_for_data(data,
                        cairo.FORMAT_ARGB32,
                        icon.get_width(),
                        icon.get_height(),
                        stride)

                context.set_source_surface(surface,
                        round(xc + x + x_gap),
                        round(yc - y + y_gap - 6))
                context.paint()

                x_gap += 13

        # draw node text
        context.set_source_rgb(r, g, b)
        context.fill_preserve()

        if node.get_draw_info('valid'):
            context.set_source_rgb(0.0, 0.0, 0.0)

        else:
            context.set_source_rgb(0.1, 0.5, 1.0)

        if not self.__animating and self.__show_address:

            context.set_font_size(8)
            context.move_to(round(xc + x + x_gap),
                                 round(yc - y + y_gap + 4))

            hostname = node.get_info('hostname')

            if hostname is not None and self.__show_hostname:
                context.show_text(hostname)

            elif node.get_info('ip') is not None:
                context.show_text(node.get_info('ip'))

        context.set_line_width(1)
        context.stroke()

    def __check_fisheye_ring(self):
        """
        """
        if self.__fisheye_ring >= self.__number_of_rings:
            self.__fisheye_ring = self.__number_of_rings - 1

    def __set_number_of_rings(self, value):
        """
        """
        self.__number_of_rings = value
        self.__check_fisheye_ring()

    def __fisheye_function(self, ring):
        """
        """
        distance = abs(self.__fisheye_ring - ring)
        level_of_detail = self.__ring_gap * self.__fisheye_interest
        spread_distance = distance - distance * self.__fisheye_spread

        value = level_of_detail / (spread_distance + 1)

        if value < self.__min_ring_gap:
            value = self.__min_ring_gap

        return value

    @graph_is_not_empty
    @not_is_in_animation
    def __update_nodes_positions(self):
        """
        """
        for node in self.__sorted_nodes:

            if node.get_draw_info('grouped'):

                # deep group check
                group = node.get_draw_info('group_node')

                while group.get_draw_info('group_node') is not None:
                    group = group.get_draw_info('group_node')

                ring = group.get_draw_info('ring')
                node.set_coordinate_radius(self.__calc_radius(ring))

            else:
                ring = node.get_draw_info('ring')
                node.set_coordinate_radius(self.__calc_radius(ring))

    @graph_is_not_empty
    def __get_node_by_coordinate(self, point):
        """
        """
        xc, yc = self.__center_of_widget

        for node in self.__graph.get_nodes():

            if node.get_draw_info('grouped'):
                continue

            ax, ay = self.__translation

            xn, yn = node.get_cartesian_coordinate()
            center = (xc + xn * self.__scale + ax, yc - yn * self.__scale - ay)
            radius = node.get_draw_info('radius') * self.__scale

            type = node.get_info('device_type')

            if type in SQUARE_TYPES:
                if geometry.is_in_square(point, radius, center):
                    return node, center

            else:
                if geometry.is_in_circle(point, radius, center):
                    return node, center

        return None

    def __calc_radius(self, ring):
        """
        """
        if self.__fisheye:

            radius = 0

            while ring > 0:

                radius += self.__fisheye_function(ring)
                ring -= 1

        else:
            radius = ring * self.__ring_gap

        return radius

    @graph_is_not_empty
    def __arrange_nodes(self):
        """
        """
        new_nodes = set([self.__graph.get_main_node()])
        old_nodes = set()

        number_of_needed_rings = 1
        ring = 0

        # while new nodes were found
        while len(new_nodes) > 0:

            tmp_nodes = set()

            # for each new nodes
            for node in new_nodes:

                old_nodes.add(node)

                # set ring location
                node.set_draw_info({'ring': ring})

                # check group constraints
                if (node.get_draw_info('group') or
                        node.get_draw_info('grouped')):
                    children = node.get_draw_info('children')

                else:

                    # getting connections and fixing multiple fathers
                    children = set()
                    for child in self.__graph.get_node_connections(node):
                        if child in old_nodes or child in new_nodes:
                            continue
                        if child.get_draw_info('grouped'):
                            continue
                        children.add(child)

                # setting father foreign
                for child in children:
                    child.set_draw_info({'father': node})

                node.set_draw_info(
                        {'children': misc.sort_children(children, node)})
                tmp_nodes.update(children)

            # check group influence in number of rings
            for node in tmp_nodes:

                if not node.get_draw_info('grouped'):

                    number_of_needed_rings += 1
                    break

            # update new nodes set
            new_nodes.update(tmp_nodes)
            new_nodes.difference_update(old_nodes)

            ring += 1

        self.__set_number_of_rings(number_of_needed_rings)

    def __weighted_layout(self):
        """
        """
        # calculating the space needed by each node
        self.__graph.get_main_node().set_draw_info({'range': (0, 360)})
        new_nodes = set([self.__graph.get_main_node()])

        self.__graph.get_main_node().calc_needed_space()

        while len(new_nodes) > 0:

            node = new_nodes.pop()

            # add only no grouped nodes
            children = set()
            for child in node.get_draw_info('children'):

                if not child.get_draw_info('grouped'):
                    children.add(child)
                    new_nodes.add(child)

            if len(children) > 0:

                min, max = node.get_draw_info('range')

                node_total = max - min
                children_need = node.get_draw_info('children_need')

                for child in children:

                    child_need = child.get_draw_info('space_need')
                    child_total = node_total * child_need / children_need

                    theta = child_total / 2 + min + self.__rotate

                    child.set_coordinate_theta(theta)
                    child.set_draw_info({'range': (min, min + child_total)})

                    min += child_total

    def __symmetric_layout(self):
        """
        """
        self.__graph.get_main_node().set_draw_info({'range': (0, 360)})
        new_nodes = set([self.__graph.get_main_node()])

        while len(new_nodes) > 0:

            node = new_nodes.pop()

            # add only no grouped nodes
            children = set()
            for child in node.get_draw_info('children'):

                if not child.get_draw_info('grouped'):
                    children.add(child)
                    new_nodes.add(child)

            if len(children) > 0:

                min, max = node.get_draw_info('range')
                factor = float(max - min) / len(children)

                for child in children:

                    theta = factor / 2 + min + self.__rotate

                    child.set_coordinate_theta(theta)
                    child.set_draw_info({'range': (min, min + factor)})

                    min += factor

    @graph_is_not_empty
    def __calc_layout(self, reference):
        """
        """
        # selecting layout algorithm
        if self.__layout == LAYOUT_SYMMETRIC:
            self.__symmetric_layout()

        elif self.__layout == LAYOUT_WEIGHTED:
            self.__weighted_layout()

        # rotating focus' children to keep orientation
        if reference is not None:

            father, angle = reference
            theta = father.get_coordinate_theta()
            factor = theta - angle

            for node in self.__graph.get_nodes():

                theta = node.get_coordinate_theta()
                node.set_coordinate_theta(theta - factor)

                a, b = node.get_draw_info('range')
                node.set_draw_info({'range': (a - factor, b - factor)})

    @graph_is_not_empty
    def __calc_node_positions(self, reference=None):
        """
        """
        # set nodes' hierarchy
        self.__arrange_nodes()
        self.calc_sorted_nodes()

        # set nodes' coordinate radius
        for node in self.__graph.get_nodes():

            ring = node.get_draw_info('ring')
            node.set_coordinate_radius(self.__calc_radius(ring))

        # set nodes' coordinate theta
        self.__calc_layout(reference)

    def __calc_interpolation(self, focus):
        """
        """
        old_main_node = self.__graph.get_main_node()
        self.__graph.set_main_node(focus)

        # getting initial coordinates
        for node in self.__graph.get_nodes():

            if self.__interpolation == INTERPOLATION_POLAR:
                coordinate = node.get_polar_coordinate()

            elif self.__interpolation == INTERPOLATION_CARTESIAN:
                coordinate = node.get_cartesian_coordinate()

            node.set_draw_info({'start_coordinate': coordinate})

        father = focus.get_draw_info('father')

        # calculate nodes positions (and father orientation)?
        if father is not None:

            xa, ya = father.get_cartesian_coordinate()
            xb, yb = focus.get_cartesian_coordinate()

            angle = math.atan2(yb - ya, xb - xa)
            angle = math.degrees(angle)

            self.__calc_node_positions((father, 180 + angle))

        else:
            self.__calc_node_positions()

        # steps for slow-in/slow-out animation
        steps = range(self.__number_of_frames)

        for i in range(len(steps) / 2):
            steps[self.__number_of_frames - 1 - i] = steps[i]

        # normalize angles and calculate interpolated points
        for node in self.__sorted_nodes:

            l2di = Linear2DInterpolator()

            # change grouped nodes coordinate
            if node.get_draw_info('grouped'):

                group_node = node.get_draw_info('group_node')
                a, b = group_node.get_draw_info('final_coordinate')

                if self.__interpolation == INTERPOLATION_POLAR:
                    node.set_polar_coordinate(a, b)

                elif self.__interpolation == INTERPOLATION_CARTESIAN:
                    node.set_cartesian_coordinate(a, b)

            # change interpolation method
            if self.__interpolation == INTERPOLATION_POLAR:

                coordinate = node.get_polar_coordinate()
                node.set_draw_info({'final_coordinate': coordinate})

                # adjusting polar coordinates
                ri, ti = node.get_draw_info('start_coordinate')
                rf, tf = node.get_draw_info('final_coordinate')

                # normalization [0, 360]
                ti = geometry.normalize_angle(ti)
                tf = geometry.normalize_angle(tf)

                # against longest path
                ti, tf = geometry.calculate_short_path(ti, tf)

                # main node goes direct to center (no arc)
                if node == self.__graph.get_main_node():
                    tf = ti

                # old main node goes direct to new position (no arc)
                if node == old_main_node:
                    ti = tf

                node.set_draw_info({'start_coordinate': (ri, ti)})
                node.set_draw_info({'final_coordinate': (rf, tf)})

            elif self.__interpolation == INTERPOLATION_CARTESIAN:

                coordinate = node.get_cartesian_coordinate()
                node.set_draw_info({'final_coordinate': coordinate})

            # calculate interpolated points
            ai, bi = node.get_draw_info('start_coordinate')
            af, bf = node.get_draw_info('final_coordinate')

            l2di.set_start_point(ai, bi)
            l2di.set_final_point(af, bf)

            if self.__interpolation_slow_in_out:
                points = l2di.get_weighed_points(
                        self.__number_of_frames, steps)

            else:
                points = l2di.get_points(self.__number_of_frames)

            node.set_draw_info({'interpolated_coordinate': points})

        return True

    def __livens_up(self, index=0):
        """
        """
        if self.__graph is None:
            # Bail out if the graph became empty during an animation.
            self.__last_group_node = None
            self.__animating = False
            return False

        # prepare interpolated points
        if index == 0:

            # prevent unnecessary animation
            no_need_to_move = True

            for node in self.__graph.get_nodes():

                ai, bi = node.get_draw_info('start_coordinate')
                af, bf = node.get_draw_info('final_coordinate')

                start_c = round(ai), round(bi)
                final_c = round(af), round(bf)

                if start_c != final_c:
                    no_need_to_move = False

            if no_need_to_move:

                self.__animating = False
                return False

        # move all nodes for pass 'index'
        for node in self.__graph.get_nodes():

            a, b = node.get_draw_info('interpolated_coordinate')[index]

            if self.__interpolation == INTERPOLATION_POLAR:
                node.set_polar_coordinate(a, b)

            elif self.__interpolation == INTERPOLATION_CARTESIAN:
                node.set_cartesian_coordinate(a, b)

        self.queue_draw()

        # animation continue condition
        if index < self.__number_of_frames - 1:
            gobject.timeout_add(self.__animation_rate,  # time to recall
                                self.__livens_up,       # recursive call
                                index + 1)              # next iteration
        else:
            self.__last_group_node = None
            self.__animating = False

        return False

    @not_is_in_animation
    def set_graph(self, graph):
        """
        Set graph to be displayed in layout
        @type  : Graph
        @param : Set the graph used in visualization
        """
        if graph.get_number_of_nodes() > 0:

            self.__graph = graph

            self.__calc_node_positions()
            self.queue_draw()

        else:
            self.__graph = None

    def get_scanned_nodes(self):
        """
        """
        nodes = list()
        if self.__graph is None:
            return nodes

        for node in self.__graph.get_nodes():

            if node.get_draw_info('scanned'):
                nodes.append(node)

        return nodes

    def get_graph(self):
        """
        """
        return self.__graph

    def set_empty(self):
        """
        """
        del(self.__graph)
        self.__graph = None

        self.queue_draw()

    def get_rotation(self):
        """
        """
        return self.__rotate

    @graph_is_not_empty
    def set_rotation(self, angle):
        """
        """
        delta = angle - self.__rotate
        self.__rotate = angle

        for node in self.__graph.get_nodes():

            theta = node.get_coordinate_theta()
            node.set_coordinate_theta(theta + delta)

        self.queue_draw()

    def get_translation(self):
        """
        """
        return self.__translation

    @graph_is_not_empty
    def set_translation(self, translation):
        """
        """
        self.__translation = translation
        self.queue_draw()

    def is_empty(self):
        """
        """
        return self.__graph is None

    def is_in_animation(self):
        """
        """
        return self.__animating

    def calc_sorted_nodes(self):
        """
        """
        self.__sorted_nodes = list(self.__graph.get_nodes())
        self.__sorted_nodes.sort(key=lambda n: n.get_draw_info('ring'))


class NetNode(Node):
    """
    Node class for radial network widget
    """
    def __init__(self):
        """
        """
        self.__draw_info = dict()
        """Hash with draw information"""
        self.__coordinate = PolarCoordinate()

        super(NetNode, self).__init__()

    def get_host(self):
        """
        Set the HostInfo that this node represents
        """
        return self.get_data()

    def set_host(self, host):
        """
        Set the HostInfo that this node represents
        """
        self.set_data(host)

    def get_info(self, info):
        """Return various information extracted from the host set with
        set_host."""
        host = self.get_data()
        if host is not None:
            if info == "number_of_open_ports":
                return host.get_port_count_by_states(["open"])
            elif info == "vulnerability_score":
                num_open_ports = host.get_port_count_by_states(["open"])
                if num_open_ports < 3:
                    return 0
                elif num_open_ports < 7:
                    return 1
                else:
                    return 2
            elif info == "addresses":
                addresses = []
                if host.ip is not None:
                    addresses.append(host.ip)
                if host.ipv6 is not None:
                    addresses.append(host.ipv6)
                if host.mac is not None:
                    addresses.append(host.mac)
                return addresses
            elif info == "ip":
                for addr in (host.ip, host.ipv6, host.mac):
                    if addr:
                        return addr.get("addr")
            elif info == "hostnames":
                hostnames = []
                for hostname in host.hostnames:
                    copy = {}
                    copy["name"] = hostname.get("hostname", "")
                    copy["type"] = hostname.get("hostname_type", "")
                    hostnames.append(copy)
                return hostnames
            elif info == "hostname":
                return host.get_hostname()
            elif info == "uptime":
                if host.uptime.get("seconds") or host.uptime.get("lastboot"):
                    return host.uptime
            elif info == "device_type":
                osmatch = host.get_best_osmatch()
                if osmatch is None:
                    return None
                osclasses = osmatch['osclasses']
                if len(osclasses) == 0:
                    return None
                types = ["router", "wap", "switch", "firewall"]
                for type in types:
                    if type in osclasses[0].get("type", "").lower():
                        return type
            elif info == "os":
                os = {}

                # osmatches
                if len(host.osmatches) > 0 and \
                   host.osmatches[0]["accuracy"] != "" and \
                   host.osmatches[0]["name"] != "":
                    if os is None:
                        os = {}
                    os["matches"] = host.osmatches
                    os["matches"][0]["db_line"] = 0     # not supported

                    os_classes = []
                    for osclass in host.osmatches[0]["osclasses"]:
                        os_class = {}

                        os_class["type"] = osclass.get("type", "")
                        os_class["vendor"] = osclass.get("vendor", "")
                        os_class["accuracy"] = osclass.get("accuracy", "")
                        os_class["os_family"] = osclass.get("osfamily", "")
                        os_class["os_gen"] = osclass.get("osgen", "")

                        os_classes.append(os_class)
                    os["classes"] = os_classes

                # ports_used
                if len(host.ports_used) > 0:
                    if os is None:
                        os = {}
                    os_portsused = []

                    for portused in host.ports_used:
                        os_portused = {}

                        os_portused["state"] = portused.get("state", "")
                        os_portused["protocol"] = portused.get("proto", "")
                        os_portused["id"] = int(portused.get("portid", "0"))

                        os_portsused.append(os_portused)

                    os["used_ports"] = os_portsused

                if len(os) > 0:
                    os["fingerprint"] = ""
                    return os
            elif info == "sequences":
                # getting sequences information
                sequences = {}
                # If all fields are empty, we don't put it into the sequences
                # list
                if reduce(lambda x, y: x + y,
                        host.tcpsequence.values(), "") != "":
                    tcp = {}
                    if host.tcpsequence.get("index", "") != "":
                        tcp["index"] = int(host.tcpsequence["index"])
                    else:
                        tcp["index"] = 0
                    tcp["class"] = ""   # not supported
                    tcp["values"] = host.tcpsequence.get(
                            "values", "").split(",")
                    tcp["difficulty"] = host.tcpsequence.get("difficulty", "")
                    sequences["tcp"] = tcp
                if reduce(lambda x, y: x + y,
                        host.ipidsequence.values(), "") != "":
                    ip_id = {}
                    ip_id["class"] = host.ipidsequence.get("class", "")
                    ip_id["values"] = host.ipidsequence.get(
                            "values", "").split(",")
                    sequences["ip_id"] = ip_id
                if reduce(lambda x, y: x + y,
                        host.tcptssequence.values(), "") != "":
                    tcp_ts = {}
                    tcp_ts["class"] = host.tcptssequence.get("class", "")
                    tcp_ts["values"] = host.tcptssequence.get(
                            "values", "").split(",")
                    sequences["tcp_ts"] = tcp_ts
                return sequences
            elif info == "filtered":
                if (len(host.extraports) > 0 and
                        host.extraports[0]["state"] == "filtered"):
                    return True
                else:
                    for port in host.ports:
                        if port["port_state"] == "filtered":
                            return True
                            break
                return False
            elif info == "ports":
                ports = list()
                for host_port in host.ports:
                    port = dict()
                    state = dict()
                    service = dict()

                    port["id"] = int(host_port.get("portid", ""))
                    port["protocol"] = host_port.get("protocol", "")

                    state["state"] = host_port.get("port_state", "")
                    state["reason"] = ""        # not supported
                    state["reason_ttl"] = ""    # not supported
                    state["reason_ip"] = ""     # not supported

                    service["name"] = host_port.get("service_name", "")
                    service["conf"] = host_port.get("service_conf", "")
                    service["method"] = host_port.get("service_method", "")
                    service["version"] = host_port.get("service_version", "")
                    service["product"] = host_port.get("service_product", "")
                    service["extrainfo"] = host_port.get(
                            "service_extrainfo", "")

                    port["state"] = state
                    port["scripts"] = None      # not supported
                    port["service"] = service

                    ports.append(port)
                return ports
            elif info == "extraports":
                # extraports
                all_extraports = list()
                for extraport in host.extraports:
                    extraports = dict()
                    extraports["count"] = int(extraport.get("count", ""))
                    extraports["state"] = extraport.get("state", "")
                    extraports["reason"] = list()       # not supported
                    extraports["all_reason"] = list()   # not supported

                    all_extraports.append(extraports)
                return all_extraports
            elif info == "trace":
                # getting traceroute information
                if len(host.trace) > 0:
                    trace = {}
                    hops = []

                    for host_hop in host.trace.get("hops", []):
                        hop = {}
                        hop["ip"] = host_hop.get("ipaddr", "")
                        hop["ttl"] = int(host_hop.get("ttl", ""))
                        hop["rtt"] = host_hop.get("rtt", "")
                        hop["hostname"] = host_hop.get("host", "")

                        hops.append(hop)

                    trace["hops"] = hops
                    trace["port"] = host.trace.get("port", "")
                    trace["protocol"] = host.trace.get("proto", "")

                    return trace
        else:  # host is None
            pass

        return None

    def get_coordinate_theta(self):
        """
        """
        return self.__coordinate.get_theta()

    def get_coordinate_radius(self):
        """
        """
        return self.__coordinate.get_radius()

    def set_coordinate_theta(self, value):
        """
        """
        self.__coordinate.set_theta(value)

    def set_coordinate_radius(self, value):
        """
        """
        self.__coordinate.set_radius(value)

    def set_polar_coordinate(self, r, t):
        """
        Set polar coordinate
        @type  r: number
        @param r: The radius of coordinate
        @type  t: number
        @param t: The angle (theta) of coordinate in radians
        """
        self.__coordinate.set_coordinate(r, t)

    def get_polar_coordinate(self):
        """
        Get cartesian coordinate
        @rtype: tuple
        @return: Cartesian coordinates (x, y)
        """
        return self.__coordinate.get_coordinate()

    def set_cartesian_coordinate(self, x, y):
        """
        Set cartesian coordinate
        """
        cartesian = CartesianCoordinate(x, y)
        r, t = cartesian.to_polar()

        self.set_polar_coordinate(r, math.degrees(t))

    def get_cartesian_coordinate(self):
        """
        Get cartesian coordinate
        @rtype: tuple
        @return: Cartesian coordinates (x, y)
        """
        return self.__coordinate.to_cartesian()

    def get_draw_info(self, info=None):
        """
        Get draw information about node
        @type  : string
        @param : Information name
        @rtype: mixed
        @return: The requested information
        """
        if info is None:
            return self.__draw_info

        return self.__draw_info.get(info)

    def set_draw_info(self, info):
        """
        Set draw information
        @type  : dict
        @param : Draw information dictionary
        """
        for key in info:
            self.__draw_info[key] = info[key]

    def deep_search_child(self, node):
        """
        """
        for child in self.get_draw_info('children'):

            if child == node:
                return True

            elif child.deep_search_child(node):
                return True

        return False

    def set_subtree_info(self, info):
        """
        """
        for child in self.get_draw_info('children'):

            child.set_draw_info(info)

            if not child.get_draw_info('group'):
                child.set_subtree_info(info)

    def calc_needed_space(self):
        """
        """
        number_of_children = len(self.get_draw_info('children'))

        sum_angle = 0
        own_angle = 0

        if number_of_children > 0 and not self.get_draw_info('group'):

            for child in self.get_draw_info('children'):

                child.calc_needed_space()
                sum_angle += child.get_draw_info('space_need')

        distance = self.get_coordinate_radius()
        size = self.get_draw_info('radius') * 2
        own_angle = geometry.angle_from_object(distance, size)

        self.set_draw_info({'children_need': sum_angle})
        self.set_draw_info({'space_need': max(sum_angle, own_angle)})