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
|
/*
* FigTreeFrame.java
*
* Copyright (C) 2006-2014 Andrew Rambaut
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* 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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package figtree.application;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.awt.DefaultFontMapper;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
import figtree.treeviewer.decorators.DiscreteColourDecorator;
import figtree.treeviewer.decorators.HSBDiscreteColourDecorator;
import figtree.treeviewer.painters.StatesPainter;
import jebl.evolution.align.Output;
import jebl.evolution.alignments.Alignment;
import jebl.evolution.alignments.BasicAlignment;
import jebl.evolution.graphs.Node;
import jebl.evolution.io.*;
import jebl.evolution.taxa.Taxon;
import jebl.evolution.trees.RootedTree;
import jebl.evolution.trees.Tree;
import jebl.util.Attributable;
import jam.controlpalettes.BasicControlPalette;
import jam.controlpalettes.ControlPalette;
import jam.framework.DocumentFrame;
import jam.panels.*;
import jam.toolbar.*;
import jam.util.IconUtils;
import figtree.application.menus.TreeMenuHandler;
import figtree.application.menus.FigTreeFileMenuHandler;
import figtree.treeviewer.*;
import figtree.treeviewer.TreeSelectionListener;
import figtree.treeviewer.annotations.*;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.text.NumberFormat;
import java.util.*;
import java.util.List;
/**
* Primary window for FigTree. The window contains a toolbar, a control panel and a panel displaying the
* tree. It responds to menu commands and hot keys specific to the focused window.
* @author Andrew Rambaut
* @version $Id: FigTreeApplication.java 232 2014-03-02 15:47:10Z rambaut $
*
* $HeadURL: https://figtree.googlecode.com/svn/trunk/src/figtree/application/FigTreeApplication.java $
*
* $LastChangedBy: rambaut $
* $LastChangedDate: 2014-03-02 15:47:10 +0000 (Sun, 02 Mar 2014) $
* $LastChangedRevision: 232 $
*/
public class FigTreeFrame extends DocumentFrame implements FigTreeFileMenuHandler, TreeMenuHandler {
private final ExtendedTreeViewer treeViewer;
private final ControlPalette controlPalette;
private final FigTreePanel figTreePanel;
private StatusBar statusBar;
private SearchPanel filterPanel;
private JPopupMenu filterPopup;
public FigTreeFrame(String title) {
super();
setTitle(title);
setImportAction(importAction);
// setImportAction(importCharactersAction);
setExportAction(exportTreesAction);
treeViewer = new ExtendedTreeViewer(this);
controlPalette = new BasicControlPalette(200, BasicControlPalette.DisplayMode.ONLY_ONE_OPEN);
figTreePanel = new FigTreePanel(this, treeViewer, controlPalette);
this.addWindowFocusListener(new WindowAdapter() {
public void windowGainedFocus(WindowEvent e) {
treeViewer.requestFocusInWindow();
}
});
}
public void initializeComponents() {
setSize(new java.awt.Dimension(1024, 768));
Toolbar toolBar = new Toolbar();
toolBar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.darkGray));
toolBar.setRollover(true);
toolBar.setFloatable(false);
Icon rerootToolIcon = IconUtils.getIcon(this.getClass(), "images/rerootTool.png");
Icon rotateToolIcon = IconUtils.getIcon(this.getClass(), "images/rotateTool.png");
Icon cartoonNodeToolIcon = IconUtils.getIcon(this.getClass(), "images/cartoonNodeTool.png");
Icon collapseNodeToolIcon = IconUtils.getIcon(this.getClass(), "images/collapseNodeTool.png");
Icon hilightToolIcon = IconUtils.getIcon(this.getClass(), "images/hilightTool.png");
Icon annotationToolIcon = IconUtils.getIcon(this.getClass(), "images/annotationTool.png");
Icon findToolIcon = IconUtils.getIcon(this.getClass(), "images/findTool.png");
Icon infoToolIcon = IconUtils.getIcon(this.getClass(), "images/infoTool.png");
Icon statisticsToolIcon = IconUtils.getIcon(this.getClass(), "images/statisticsTool.png");
Icon settingsToolIcon = IconUtils.getIcon(this.getClass(), "images/projectTool.png");
Icon colourToolIcon = IconUtils.getIcon(this.getClass(), "images/coloursTool.png");
Icon nextIcon = IconUtils.getIcon(this.getClass(), "images/next.png");
Icon prevIcon = IconUtils.getIcon(this.getClass(), "images/prev.png");
final ToolbarAction cartoonToolbarAction = new ToolbarAction("Cartoon", CARTOON_NODE, cartoonNodeToolIcon) {
public void actionPerformed(ActionEvent e){
cartoonAction.actionPerformed(e);
}
};
ToolbarButton cartoonToolButton = new ToolbarButton(cartoonToolbarAction, true);
cartoonToolButton.setFocusable(false);
toolBar.addComponent(cartoonToolButton);
final ToolbarAction collapseToolbarAction = new ToolbarAction("Collapse", COLLAPSE_NODE, collapseNodeToolIcon) {
public void actionPerformed(ActionEvent e){
collapseAction.actionPerformed(e);
}
};
ToolbarButton collapseToolButton = new ToolbarButton(collapseToolbarAction, true);
collapseToolButton.setFocusable(false);
toolBar.addComponent(collapseToolButton);
final ToolbarAction rerootToolbarAction = new ToolbarAction("Reroot", ROOT_ON_BRANCH, rerootToolIcon) {
public void actionPerformed(ActionEvent e){
rerootAction.actionPerformed(e);
}
};
ToolbarButton rerootToolButton = new ToolbarButton(rerootToolbarAction, true);
rerootToolButton.setFocusable(false);
toolBar.addComponent(rerootToolButton);
final ToolbarAction rotateToolbarAction = new ToolbarAction("Rotate", ROTATE_NODE, rotateToolIcon) {
public void actionPerformed(ActionEvent e){
rotateAction.actionPerformed(e);
}
};
ToolbarButton rotateToolButton = new ToolbarButton(rotateToolbarAction, true);
rotateToolButton.setFocusable(false);
toolBar.addComponent(rotateToolButton);
final ToolbarAction annotateToolbarAction = new ToolbarAction("Annotate", ANNOTATE, annotationToolIcon) {
public void actionPerformed(ActionEvent e){
annotateAction.actionPerformed(e);
}
};
ToolbarButton annotationToolButton = new ToolbarButton(annotateToolbarAction, true);
annotationToolButton.setFocusable(false);
toolBar.addComponent(annotationToolButton);
final ToolbarAction colourToolbarAction = new ToolbarAction("Colour", COLOUR, colourToolIcon) {
public void actionPerformed(ActionEvent e){
colourAction.actionPerformed(e);
}
};
ToolbarButton colourToolButton = new ToolbarButton(colourToolbarAction, true);
colourToolButton.setFocusable(false);
toolBar.addComponent(colourToolButton);
final ToolbarAction hilightToolbarAction = new ToolbarAction("Hilight", HILIGHT, hilightToolIcon) {
public void actionPerformed(ActionEvent e){
hilightAction.actionPerformed(e);
}
};
ToolbarButton hilightToolButton = new ToolbarButton(hilightToolbarAction, true);
hilightToolButton.setFocusable(false);
toolBar.addComponent(hilightToolButton);
toolBar.addSeparator();
final ToolbarAction findToolbarAction = new ToolbarAction("Find", "Find Taxa...", findToolIcon) {
public void actionPerformed(ActionEvent e){
findAction.actionPerformed(e);
}
};
JButton findToolButton = new ToolbarButton(findToolbarAction);
findToolButton.setFocusable(false);
toolBar.addComponent(findToolButton);
findToolButton.setEnabled(true);
// final ToolbarAction infoToolbarAction = new ToolbarAction("Get Info", "Get Info...", infoToolIcon) {
// public void actionPerformed(ActionEvent e){
// getInfoAction.actionPerformed(e);
// }
// };
// JButton infoToolButton = new ToolbarButton(infoToolbarAction);
// toolBar.addComponent(infoToolButton);
// JButton settingsToolButton = new ToolbarButton(
// new ToolbarAction("Statistics", "Statistics...", statisticsToolIcon) {
// public void actionPerformed(ActionEvent e){
// treeViewer.showStatistics();
// }
// });
// settingsToolButton.putClientProperty("Quaqua.Button.style", "toolBarRollover");
// toolBar.addComponent(settingsToolButton);
// settingsToolButton.setEnabled(false);
toolBar.addSeparator();
Box box1 = Box.createHorizontalBox();
final JToggleButton toggle1 = new JToggleButton("Node");
toggle1.setFocusable(false);
toggle1.putClientProperty("JButton.buttonType", "segmentedTextured");
toggle1.putClientProperty("JButton.segmentPosition", "first");
toggle1.putClientProperty( "Quaqua.Button.style", "toggleWest");
final JToggleButton toggle2 = new JToggleButton("Clade");
toggle2.setFocusable(false);
toggle2.putClientProperty("JButton.buttonType", "segmentedTextured");
toggle2.putClientProperty("JButton.segmentPosition", "middle");
toggle2.putClientProperty( "Quaqua.Button.style", "toggleCenter");
final JToggleButton toggle3 = new JToggleButton("Taxa");
toggle3.setFocusable(false);
toggle3.putClientProperty("JButton.buttonType", "segmentedTextured");
toggle3.putClientProperty("JButton.segmentPosition", "last");
toggle3.putClientProperty( "Quaqua.Button.style", "toggleEast");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(toggle1);
buttonGroup.add(toggle2);
buttonGroup.add(toggle3);
toggle1.setSelected(true);
toggle1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
treeViewer.setSelectionMode(TreePaneSelector.SelectionMode.NODE);
}
}
});
toggle2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
treeViewer.setSelectionMode(TreePaneSelector.SelectionMode.CLADE);
}
}
});
toggle3.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
treeViewer.setSelectionMode(TreePaneSelector.SelectionMode.TAXA);
}
}
});
box1.add(Box.createVerticalStrut(annotationToolIcon.getIconHeight()));
box1.add(toggle1);
box1.add(toggle2);
box1.add(toggle3);
toolBar.addComponent(new GenericToolbarItem("Selection Mode", "What aspect of the tree is selected when it is clicked", box1));
toolBar.addFlexibleSpace();
final ToolbarAction prevTreeToolbarAction =
new ToolbarAction(null, "Previous Tree...", prevIcon) {
public void actionPerformed(ActionEvent e){
if (treeViewer.isRootingOn() && treeViewer.getRootingType() == TreePane.RootingType.USER_ROOTING) {
JOptionPane.showMessageDialog(FigTreeFrame.this, "Cannot switch trees when user rooting option is on.\n" +
"Turn this option off to switch trees",
"Unable to switch trees",
JOptionPane.ERROR_MESSAGE);
} else {
treeViewer.showPreviousTree();
}
}
};
JButton prevTreeToolButton = new ToolbarButton(prevTreeToolbarAction, true);
prevTreeToolButton.setFocusable(false);
prevTreeToolButton.putClientProperty("JButton.buttonType", "segmentedTextured");
prevTreeToolButton.putClientProperty("JButton.segmentPosition", "first");
prevTreeToolButton.putClientProperty( "Quaqua.Button.style", "toggleWest");
final ToolbarAction nextTreeToolbarAction =
new ToolbarAction(null, "Next Tree...", nextIcon) {
public void actionPerformed(ActionEvent e){
if (treeViewer.isRootingOn() && treeViewer.getRootingType() == TreePane.RootingType.USER_ROOTING) {
JOptionPane.showMessageDialog(FigTreeFrame.this, "Cannot switch trees when user rooting option is on.\n" +
"Turn this option off to switch trees",
"Unable to switch trees",
JOptionPane.ERROR_MESSAGE);
} else {
treeViewer.showNextTree();
}
}
};
JButton nextTreeToolButton = new ToolbarButton(nextTreeToolbarAction, true);
nextTreeToolButton.setFocusable(false);
nextTreeToolButton.putClientProperty("JButton.buttonType", "segmentedTextured");
nextTreeToolButton.putClientProperty("JButton.segmentPosition", "last");
nextTreeToolButton.putClientProperty( "Quaqua.Button.style", "toggleEast");
nextTreeToolbarAction.setEnabled(treeViewer.getCurrentTreeIndex() < treeViewer.getTreeCount() - 1);
prevTreeToolbarAction.setEnabled(treeViewer.getCurrentTreeIndex() > 0);
Box box2 = Box.createHorizontalBox();
box2.add(Box.createVerticalStrut(annotationToolIcon.getIconHeight()));
box2.add(prevTreeToolButton);
box2.add(nextTreeToolButton);
toolBar.addComponent(new GenericToolbarItem("Prev/Next", "Navigate through the trees", box2));
TreeViewerListener l = new TreeViewerListener() {
public void treeChanged() {
boolean nextTreeEnabled = treeViewer.getCurrentTreeIndex() < treeViewer.getTreeCount() - 1;
nextTreeAction.setEnabled(nextTreeEnabled);
nextTreeToolbarAction.setEnabled(nextTreeEnabled);
boolean prevTreeEnabled = treeViewer.getCurrentTreeIndex() > 0;
previousTreeAction.setEnabled(prevTreeEnabled);
prevTreeToolbarAction.setEnabled(prevTreeEnabled);
}
public void treeSettingsChanged() {
// nothing to do
}
};
treeViewer.addTreeViewerListener(l);
l.treeChanged();
toolBar.addFlexibleSpace();
filterPopup = new JPopupMenu();
final ButtonGroup bg = new ButtonGroup();
boolean first = true;
for (TreeViewer.TextSearchType searchType : TreeViewer.TextSearchType.values()) {
final JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(searchType.toString());
if (first) {
menuItem.setSelected(true);
first = false;
}
filterPopup.add(menuItem);
bg.add(menuItem);
}
filterPanel = new SearchPanel("Filter", filterPopup, true);
// filterPanel.getSearchText().requestFocus();
filterPanel.addSearchPanelListener(new SearchPanelListener() {
/**
* Called when the user requests a search by pressing return having
* typed a search string into the text field. If the continuousUpdate
* flag is true then this method is called when the user types into
* the text field.
*
* @param searchString the user's search string
*/
public void searchStarted(String searchString) {
Enumeration e = bg.getElements();
String value = null;
while (e.hasMoreElements()) {
AbstractButton button = (AbstractButton)e.nextElement();
if (button.isSelected()) {
value = button.getText();
}
}
for (TreeViewer.TextSearchType searchType : TreeViewer.TextSearchType.values()) {
if (searchType.toString().equals(value)) {
treeViewer.selectTaxa(searchType, searchString, false);
}
}
}
/**
* Called when the user presses the cancel search button or presses
* escape while the search is in focus.
*/
public void searchStopped() {
treeViewer.clearSelectedTaxa();
}
});
JPanel panel3 = new JPanel(new FlowLayout());
panel3.add(filterPanel);
toolBar.addComponent(panel3);
statusBar = new StatusBar("FigTree");
statusBar.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createMatteBorder(1, 0, 0, 0, Color.darkGray),
BorderFactory.createMatteBorder(1, 0, 0, 0, Color.lightGray)),
BorderFactory.createEmptyBorder(2, 12, 2, 12)));
statusBar.setOpaque(false);
statusBar.setStatusProvider(treeViewer.getStatusProvider());
JPanel topPanel = new JPanel(new BorderLayout(0,0));
topPanel.add(toolBar, BorderLayout.NORTH);
getContentPane().setLayout(new java.awt.BorderLayout(0, 0));
getContentPane().add(topPanel, BorderLayout.NORTH);
getContentPane().add(figTreePanel, BorderLayout.CENTER);
getContentPane().add(statusBar, BorderLayout.SOUTH);
TreeSelectionListener l2 = new TreeSelectionListener() {
public void selectionChanged() {
boolean hasSelection = treeViewer.hasSelection();
cartoonToolbarAction.setEnabled(hasSelection);
cartoonAction.setEnabled(hasSelection);
collapseToolbarAction.setEnabled(hasSelection);
collapseAction.setEnabled(hasSelection);
// clearCollapsedAction.setEnabled(hasSelection);
hilightToolbarAction.setEnabled(hasSelection);
hilightAction.setEnabled(hasSelection);
clearHilightingAction.setEnabled(hasSelection);
// midpointRootAction.setEnabled(hasSelection);
rerootToolbarAction.setEnabled(hasSelection);
rerootAction.setEnabled(hasSelection);
clearRootingAction.setEnabled(hasSelection);
rotateToolbarAction.setEnabled(hasSelection);
rotateAction.setEnabled(hasSelection);
// increasingNodeOrderAction.setEnabled(hasSelection);
// decreasingNodeOrderAction.setEnabled(hasSelection);
// clearRotationsAction.setEnabled(hasSelection);
annotateToolbarAction.setEnabled(hasSelection);
// annotateNodesFromTipsAction.setEnabled(hasSelection);
// annotateTipsFromNodesAction.setEnabled(hasSelection);
annotateAction.setEnabled(hasSelection);
// clearAnnotationsAction.setEnabled(hasSelection);
colourToolbarAction.setEnabled(hasSelection);
colourAction.setEnabled(hasSelection);
clearColouringAction.setEnabled(hasSelection);
}
};
treeViewer.addTreeSelectionListener(l2);
l2.selectionChanged();
getCutAction().setEnabled(false);
getCopyAction().setEnabled(true);
getDeleteAction().setEnabled(false);
getSelectAllAction().setEnabled(true);
getFindAction().setEnabled(true);
getZoomWindowAction().setEnabled(false);
}
private void defineAnnotations() {
Collection<AnnotationDefinition> definitions = treeViewer.getAnnotationDefinitions().values();
if (annotationDefinitionsDialog == null) {
annotationDefinitionsDialog = new AnnotationDefinitionsDialog(this);
}
annotationDefinitionsDialog.showDialog(definitions);
treeViewer.setAnnotationDefinitions(annotationDefinitionsDialog.getAnnotations());
treeViewer.fireAnnotationsChanged();
}
private void annotateNodesFromTips() {
List<String> annotationNames = new ArrayList<String>();
annotationNames.add("Colour");
annotationNames.addAll(treeViewer.getAnnotationDefinitions().keySet());
annotationNames.add("Name");
if (selectAnnotationDialog == null) {
selectAnnotationDialog = new SelectAnnotationDialog(this);
}
int result = selectAnnotationDialog.showDialog(annotationNames);
if (result == JOptionPane.CANCEL_OPTION || result == JOptionPane.CLOSED_OPTION) {
return;
}
String annotationName = selectAnnotationDialog.getAnnotationName();
if (annotationName.equals("Colour")) {
annotationName = "!color";
}
treeViewer.annotateNodesFromTips(annotationName);
setDirty();
}
private void annotateTipsFromNodes() {
List<String> annotationNames = new ArrayList<String>();
annotationNames.add("Colour");
annotationNames.addAll(treeViewer.getAnnotationDefinitions().keySet());
if (selectAnnotationDialog == null) {
selectAnnotationDialog = new SelectAnnotationDialog(this);
}
if (selectAnnotationDialog.showDialog(annotationNames) != JOptionPane.CANCEL_OPTION) {
String annotationName = selectAnnotationDialog.getAnnotationName();
if (annotationName.equals("Colour")) {
annotationName = "!color";
}
treeViewer.annotateTipsFromNodes(annotationName);
setDirty();
}
}
private void cartoonSelected() {
treeViewer.cartoonSelectedNodes();
}
private void collapseSelected() {
treeViewer.collapseSelectedNodes();
}
private void hilightSelected() {
Color color = JColorChooser.showDialog(this, "Select Colour", lastColor);
if (color != null) {
treeViewer.hilightSelectedNodes(color);
setDirty();
lastColor = color;
}
}
private void rerootTree() {
Set<Node> nodes = treeViewer.getSelectedNodes();
if (nodes.size() != 1 ) {
JOptionPane.showMessageDialog(this,
"Exactly one branch must be selected to re-root the tree." ,
"Annotating Tree",
JOptionPane.WARNING_MESSAGE);
return;
}
treeViewer.rerootOnSelectedBranch();
}
private void rotateTree() {
treeViewer.rotateSelectedNode();
}
private void annotateSelected() {
treeViewer.setToolMode(TreePaneSelector.ToolMode.SELECT);
List<AnnotationDefinition> definitions = new ArrayList<AnnotationDefinition>();
definitions.add(new AnnotationDefinition("Name", "!name", AnnotationDefinition.Type.STRING));
definitions.addAll(treeViewer.getAnnotationDefinitions().values());
if (annotationDialog == null) {
annotationDialog = new AnnotationDialog(this);
}
Set<Node> nodes = treeViewer.getSelectedNodes();
Set<Node> tips = treeViewer.getSelectedTips();
Attributable item = null;
if (nodes.size() + tips.size() == 1 ) {
if (nodes.size() == 1) {
item = nodes.iterator().next();
}else if (tips.size() == 1) {
item = tips.iterator().next();
}
} else {
int result = JOptionPane.showConfirmDialog(this,
"More than one node selected for annotation. This operation\n" +
"may overwrite existing annotations. Do you wish to continue?" ,
"Annotating Tree",
JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.CANCEL_OPTION || result == JOptionPane.CLOSED_OPTION) {
return;
}
}
if (annotationDialog.showDialog(definitions, item) != JOptionPane.CANCEL_OPTION) {
AnnotationDefinition newDefinition = annotationDialog.getDefinition();
List<AnnotationDefinition> defs = new ArrayList<AnnotationDefinition>(treeViewer.getAnnotationDefinitions().values());
if (!defs.contains(newDefinition)) {
defs.add(newDefinition);
treeViewer.setAnnotationDefinitions(defs);
}
String code = newDefinition.getCode();
Object value = annotationDialog.getValue();
treeViewer.annotateSelected(code, value);
setDirty();
}
}
private void copySelectedAnnotations() {
// todo This function is disabled as it is not completely implemented
// treeViewer.setToolMode(TreePaneSelector.ToolMode.SELECT);
//
// List<AnnotationDefinition> definitions = new ArrayList<AnnotationDefinition>();
// definitions.add(new AnnotationDefinition("Name", "!name", AnnotationDefinition.Type.STRING));
// definitions.addAll(treeViewer.getAnnotationDefinitions().values());
//
// if (copyAnnotationDialog == null) {
// copyAnnotationDialog = new AnnotationDialog(this, true);
// }
//
// Set<Node> nodes = treeViewer.getSelectedNodes();
// Set<Node> tips = treeViewer.getSelectedTips();
//
// Attributable item = null;
// if (nodes.size() + tips.size() == 1 ) {
// if (nodes.size() == 1) {
// item = nodes.iterator().next();
// }else if (tips.size() == 1) {
// item = tips.iterator().next();
// }
// } else {
// int result = JOptionPane.showConfirmDialog(this,
// "More than one node selected for annotation. This operation\n" +
// "may overwrite existing annotations. Do you wish to continue?" ,
// "Annotating Tree",
// JOptionPane.WARNING_MESSAGE);
// if (result == JOptionPane.CANCEL_OPTION || result == JOptionPane.CLOSED_OPTION) {
// return;
// }
// }
// if (annotationDialog.showDialog(definitions, item) != JOptionPane.CANCEL_OPTION) {
// String code = annotationDialog.getDefinition().getCode();
// String code2 = annotationDialog.getDestinationDefinition().getCode();
//
// treeViewer.copySelected(code, value);
// setDirty();
// }
}
private static Color lastColor = Color.GRAY;
private void colourSelected() {
treeViewer.setToolMode(TreePaneSelector.ToolMode.SELECT);
Color color = JColorChooser.showDialog(this, "Select Colour", lastColor);
if (color != null) {
treeViewer.annotateSelected("!color", color);
setDirty();
lastColor = color;
}
}
public boolean readFromFile(File file) throws IOException {
Reader reader = null;
try {
reader = new FileReader(file);
boolean isNexus = isNexus(reader);
ProgressMonitorInputStream in = new ProgressMonitorInputStream(
this,
"Reading " + file.getName(),
new FileInputStream(file));
in.getProgressMonitor().setMillisToDecideToPopup(1000);
in.getProgressMonitor().setMillisToPopup(1000);
reader = new InputStreamReader(in);
boolean success = readData(reader, isNexus);
reader.close();
return success;
} catch (IOException ioe) {
if (reader != null) {
reader.close();
}
throw ioe;
}
}
public boolean readFromURL(URL url) throws IOException {
InputStream in = url.openStream();
Reader reader = new InputStreamReader(url.openStream());
boolean isNexus = isNexus(reader);
reader.close();
reader = new InputStreamReader(url.openStream());
return readData(reader, isNexus);
}
private boolean isNexus(Reader reader) throws IOException {
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
while (line != null && line.length() == 0) {
line = bufferedReader.readLine();
}
return (line != null && line.toUpperCase().contains("#NEXUS"));
}
public boolean readFromString(String string) throws IOException {
boolean isNexus = string.substring(0, 80).toUpperCase().contains("#NEXUS");
return readData(new StringReader(string), isNexus);
}
protected boolean readData(Reader reader, boolean isNexus) throws IOException {
List<Tree> trees = new ArrayList<Tree>();
boolean hasSettings = false;
try {
Map<String, Object> settings = new HashMap<String, Object>();
// First of all, fully populate the settings map so that
// all the settings have defaults
controlPalette.getSettings(settings);
if (isNexus) {
FigTreeNexusImporter importer = new FigTreeNexusImporter(reader);
while (importer.hasTree()) {
Tree tree = importer.importNextTree();
trees.add(tree);
}
// Try to find a figtree block and if found, parse the settings
while (true) {
try {
importer.findNextBlock();
if (importer.getNextBlockName().equalsIgnoreCase("FIGTREE")) {
importer.parseFigTreeBlock(settings);
hasSettings = true;
}
} catch (EOFException ex) {
break;
}
}
} else {
NewickImporter importer = new NewickImporter(reader, true);
while (importer.hasTree()) {
Tree tree = importer.importNextTree();
trees.add(tree);
}
}
if (trees.size() == 0) {
throw new ImportException("This file contained no trees.");
}
checkLabelAttribute(trees);
treeViewer.setTrees(trees);
controlPalette.setSettings(settings);
} catch (ImportException ie) {
JOptionPane.showMessageDialog(this, "Error reading tree file: \n" + ie.getMessage(),
"Import Error",
JOptionPane.ERROR_MESSAGE);
return false;
}
if (!hasSettings) {
// If there weren't settings in the file then this wasn't a TreeDraw
// created document so we don't want to be able to overwrite it without
// explicit action of the user...
setDirty();
clearFile();
}
return true;
}
/**
* This version loads the trees in a thread but this needs more thought in order
* to tie in to the JAM framework correctly
*/
// protected boolean readData(final Reader reader, final boolean isNexus) {
//
// final JFrame frame = this;
// Thread readThread = new Thread () {
// public void run() {
// try {
//
// final List<Tree> trees = new ArrayList<Tree>();
//
// boolean hasSettings = false;
//
// final Map<String, Object> settings = new HashMap<String, Object>();
// // First of all, fully populate the settings map so that
// // all the settings have defaults
// controlPalette.getSettings(settings);
//
// if (isNexus) {
// FigTreeNexusImporter importer = new FigTreeNexusImporter(reader);
// while (importer.hasTree()) {
// Tree tree = importer.importNextTree();
// trees.add(tree);
// }
// // Try to find a figtree block and if found, parse the settings
// while (true) {
// try {
// importer.findNextBlock();
// if (importer.getNextBlockName().equalsIgnoreCase("FIGTREE")) {
// importer.parseFigTreeBlock(settings);
// hasSettings = true;
// }
// } catch (EOFException ex) {
// break;
// }
// }
// } else {
// NewickImporter importer = new NewickImporter(reader, true);
// while (importer.hasTree()) {
// Tree tree = importer.importNextTree();
// trees.add(tree);
// }
// }
//
// if (trees.size() == 0) {
// throw new ImportException("This file contained no trees.");
// }
//
// final boolean hasSettings2 = hasSettings;
//
// EventQueue.invokeLater (
// new Runnable () {
// public void run () {
// treeViewer.setTrees(trees);
// controlPalette.setSettings(settings);
//
// if (!hasSettings2) {
// // If there weren't settings in the file then this wasn't a TreeDraw
// // created document so we don't want to be able to overwrite it without
// // explicit action of the user...
// setDirty();
// clearFile();
// }
// }
// });
//
// } catch (final ImportException ie) {
// EventQueue.invokeLater (
// new Runnable () {
// public void run () {
// JOptionPane.showMessageDialog(frame, "Error reading tree file: " + ie.getMessage(),
// "Import Error",
// JOptionPane.ERROR_MESSAGE);
// }
// });
// } catch (final InterruptedIOException iioex) {
// // The cancel dialog button was pressed - do nothing
// } catch (final IOException ioex) {
// EventQueue.invokeLater (
// new Runnable () {
// public void run () {
// JOptionPane.showMessageDialog(frame, "File I/O Error: " + ioex.getMessage(),
// "File I/O Error",
// JOptionPane.ERROR_MESSAGE);
// }
// });
// }
//
// }
// };
// readThread.start();
//
// return true;
// }
private void checkLabelAttribute(List<Tree> trees) {
boolean hasLabel = false;
for (Tree tree : trees) {
for (Node node : tree.getNodes()) {
if (node.getAttribute("label") != null) {
hasLabel = true;
}
}
}
if (hasLabel) {
String labelName = null;
do {
labelName = JOptionPane.showInputDialog(
"The node/branches of the tree are labelled\n" +
"(i.e., with bootstrap values or posterior probabilities).\n\n" +
"Please select a name for these values.", "label");
if (labelName == null) {
labelName = "label";
}
labelName = labelName.trim();
if (labelName.length() == 0) {
Toolkit.getDefaultToolkit().beep();
}
} while (labelName == null || labelName.length() == 0);
if (!labelName.equals("label")) {
for (Tree tree : trees) {
for (Node node : tree.getNodes()) {
Object value = node.getAttribute("label");
if (value != null) {
node.removeAttribute("label");
node.setAttribute(labelName, value);
}
}
}
}
}
}
protected boolean writeToFile(File file) throws IOException {
Map<String, Object> settings = new TreeMap<String, Object>();
controlPalette.getSettings(settings);
FileWriter writer = new FileWriter(file);
FigTreeNexusExporter exporter = new FigTreeNexusExporter(writer, true);
exporter.exportTrees(treeViewer.getTrees());
exporter.writeFigTreeBlock(settings);
writer.close();
return true;
}
public final void doImport() {
FileDialog dialog = new FileDialog(this,
"Import Annotations File...",
FileDialog.LOAD);
dialog.setVisible(true);
if (dialog.getFile() != null) {
File file = new File(dialog.getDirectory(), dialog.getFile());
try {
Map<AnnotationDefinition, Map<Taxon, Object>> annotations = importAnnotationsFromFile(file);
treeViewer.setTaxonAnnotations(annotations);
// Hack to show tips states...
// String[] annotationNames = new String[annotations.keySet().size()];
// DiscreteColourDecorator[] decorators = new DiscreteColourDecorator[annotations.keySet().size()];
//
// int i = 0;
// for (AnnotationDefinition definition: annotations.keySet()) {
// Map<Taxon, Object> annotation = annotations.get(definition);
// annotationNames[i] = definition.getName();
// decorators[i] = new HSBDiscreteColourDecorator(annotationNames[i], annotation.keySet());
// i++;
// }
// treeViewer.setTipLabelPainter(new StatesPainter(annotationNames, decorators));
} catch (FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(this, "Unable to open file: File not found",
"Unable to open file",
JOptionPane.ERROR_MESSAGE);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "Unable to read file: " + ioe.getMessage(),
"Unable to read file",
JOptionPane.ERROR_MESSAGE);
}
}
}
protected Map<AnnotationDefinition, Map<Taxon, Object>> importAnnotationsFromFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
List<String> taxa = new ArrayList<String>();
String line = reader.readLine();
String[] labels = line.split("\t");
Map<String, List<String>> columns = new HashMap<String, List<String>>();
for (int i = 1; i < labels.length; i++) {
columns.put(labels[i], new ArrayList<String>());
}
line = reader.readLine();
while (line != null) {
String[] values = line.split("\t");
if (values.length > 0) {
taxa.add(values[0]);
for (int i = 1; i < values.length; i++) {
if (i < labels.length) {
List<String> column = columns.get(labels[i]);
column.add(values[i]);
}
}
}
line = reader.readLine();
}
Map<AnnotationDefinition, Map<Taxon, Object>> annotations = new TreeMap<AnnotationDefinition, Map<Taxon, Object>>();
NumberFormat nf = NumberFormat.getInstance();
for (int i = 1; i < labels.length; i++) {
List<String> column = columns.get(labels[i]);
boolean isInteger = true;
boolean isNumber = true;
boolean isBoolean = true;
for (String valueString : column) {
if (!valueString.equalsIgnoreCase("TRUE") && !valueString.equalsIgnoreCase("FALSE")) {
isBoolean = false;
try {
double number = Double.parseDouble(valueString);
if (Math.round(number) != number) {
isInteger = false;
}
} catch (NumberFormatException pe) {
isInteger = false;
isNumber = false;
}
}
}
Map<Taxon, Object> values = new HashMap<Taxon, Object>();
AnnotationDefinition ad;
int j = 0;
for (String valueString : column) {
Taxon taxon = Taxon.getTaxon(taxa.get(j));
if (isBoolean) {
values.put(taxon, new Boolean(valueString));
} else if (isInteger) {
values.put(taxon, new Integer(valueString));
} else if (isNumber) {
values.put(taxon, new Double(valueString));
} else {
values.put(taxon, valueString);
}
j++;
}
Set<Object> valueSet = new HashSet<Object>(values.values());
if (isBoolean) {
ad = new AnnotationDefinition(labels[i], AnnotationDefinition.Type.BOOLEAN );
} else if (isInteger) {
ad = new AnnotationDefinition(labels[i], AnnotationDefinition.Type.INTEGER );
} else if (isNumber) {
ad = new AnnotationDefinition(labels[i], AnnotationDefinition.Type.REAL );
} else {
String[] valueArray = new String[valueSet.size()];
valueSet.toArray(valueArray);
ad = new AnnotationDefinition(labels[i], AnnotationDefinition.Type.STRING);
//ad.setOptions(valueArray);
}
annotations.put(ad, values);
}
return annotations;
}
private void doImportCharacters() {
FileDialog dialog = new FileDialog(this,
"Import Characters File...",
FileDialog.LOAD);
dialog.setVisible(true);
if (dialog.getFile() != null) {
File file = new File(dialog.getDirectory(), dialog.getFile());
try {
importCharactersFromFile(file);
} catch (FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(this, "Unable to open file: File not found",
"Unable to open file",
JOptionPane.ERROR_MESSAGE);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "Unable to read file: " + ioe.getMessage(),
"Unable to read file",
JOptionPane.ERROR_MESSAGE);
}
}
}
protected boolean importCharactersFromFile(File file) throws FileNotFoundException, IOException {
final String fileName = file.getName();
SequenceImporter importer = new NexusImporter(new FileReader(file));
try {
Alignment alignment = new BasicAlignment(importer.importSequences());
treeViewer.setCharacters(alignment);
} catch (ImportException ie) {
JOptionPane.showMessageDialog(this, "Error reading characters file: " + ie.getMessage(),
"Import Error",
JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
private void doImportColourScheme() {
FileDialog dialog = new FileDialog(this,
"Import Colour Scheme...",
FileDialog.LOAD);
dialog.setVisible(true);
if (dialog.getFile() != null) {
File file = new File(dialog.getDirectory(), dialog.getFile());
try {
importColourSchemeFromFile(file);
} catch (FileNotFoundException fnfe) {
JOptionPane.showMessageDialog(this, "Unable to open file: File not found",
"Unable to open file",
JOptionPane.ERROR_MESSAGE);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "Unable to read file: " + ioe.getMessage(),
"Unable to read file",
JOptionPane.ERROR_MESSAGE);
}
}
}
protected boolean importColourSchemeFromFile(File file) throws FileNotFoundException, IOException {
final String fileName = file.getName();
SequenceImporter importer = new NexusImporter(new FileReader(file));
try {
Alignment alignment = new BasicAlignment(importer.importSequences());
treeViewer.setCharacters(alignment);
} catch (ImportException ie) {
JOptionPane.showMessageDialog(this, "Error reading characters file: " + ie.getMessage(),
"Import Error",
JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
public final void doExport() {
if (exportTreeDialog == null) {
exportTreeDialog = new ExportTreeDialog(this);
}
if (exportTreeDialog.showDialog() == JOptionPane.OK_OPTION) {
FileDialog dialog = new FileDialog(this,
"Export Tree File...",
FileDialog.SAVE);
dialog.setVisible(true);
if (dialog.getFile() != null) {
File file = new File(dialog.getDirectory(), dialog.getFile());
FileWriter writer = null;
try {
writer = new FileWriter(file);
writeTreeFile(writer,
exportTreeDialog.getFormat(),
exportTreeDialog.allTrees(),
exportTreeDialog.asDisplayed(),
exportTreeDialog.includeFigTreeBlock(),
exportTreeDialog.includeAnnotations(),
false);
writer.close();
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "Error writing tree file: " + ioe.getMessage(),
"Export Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
}
public final void doExportGraphic(GraphicFormat format) {
FileDialog dialog = new FileDialog(this,
"Export " + format.getName() + " File...",
FileDialog.SAVE);
String name = this.getFile().getName() + "." + format.getName().toLowerCase();
dialog.setFile(name);
dialog.setVisible(true);
if (dialog.getFile() != null) {
File file = new File(dialog.getDirectory(), dialog.getFile());
try {
OutputStream stream = new FileOutputStream(file);
exportGraphics(format, treeViewer.getContentPane(), stream);
stream.flush();
stream.close();
} catch(DocumentException de) {
JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de,
"Export PDF Error",
JOptionPane.ERROR_MESSAGE);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "Error writing tree file: " + ioe.getMessage(),
"Export Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public final static void exportGraphics(GraphicFormat format, JComponent comp, OutputStream stream) throws IOException, DocumentException {
switch (format) {
case PNG:
case GIF:
case BMP:
case JPEG:
exportGraphicsFile(format, comp, stream);
break;
case EPS:
throw new UnsupportedOperationException("EPS not handled");
case SVG:
exportSVGFile(comp, stream);
break;
case PDF:
exportPDFFile(comp, stream);
break;
default:
throw new UnsupportedOperationException("Format not handled: " + format);
}
}
private final static void exportGraphicsFile(GraphicFormat format, JComponent component, OutputStream stream) throws IOException {
int imageType = BufferedImage.TYPE_INT_RGB;
if (format == GraphicFormat.PNG) {
// PNG allows an alpha channel
imageType = BufferedImage.TYPE_INT_ARGB;
}
BufferedImage bi = new BufferedImage(component.getSize().width, component.getSize().height, imageType);
Graphics g = bi.createGraphics();
if (format != GraphicFormat.PNG) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, bi.getWidth(), bi.getHeight());
}
component.paint(g);
g.dispose();
ImageIO.write(bi, format.getName(), stream);
}
private final static void exportSVGFile(JComponent component, OutputStream stream) throws IOException {
// Get a DOMImplementation and create an XML document
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
// Create an instance of the SVG Generator
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
component.paint(svgGenerator);
Element svgRoot = svgGenerator.getRoot();
Rectangle2D bounds = component.getBounds();
String viewBox = "0 0 " + bounds.getWidth() + " " + bounds.getHeight();
svgRoot.setAttributeNS(null, svgGenerator.SVG_VIEW_BOX_ATTRIBUTE, viewBox);
svgRoot.setAttributeNS(null, svgGenerator.SVG_WIDTH_ATTRIBUTE, Double.toString(bounds.getWidth()));
svgRoot.setAttributeNS(null, svgGenerator.SVG_HEIGHT_ATTRIBUTE, Double.toString(bounds.getHeight()));
// Write svg file
Writer out = new OutputStreamWriter(stream, "UTF-8");
svgGenerator.stream(svgRoot, out, true /* use css */, false /* escaped */);
}
public final static void exportPDFFile(JComponent component, OutputStream stream) throws DocumentException {
Rectangle2D bounds = component.getBounds();
Document document = new Document(new com.itextpdf
.text.Rectangle((float)bounds.getWidth(), (float)bounds.getHeight()));
// step 2
PdfWriter writer;
writer = PdfWriter.getInstance(document, stream);
// step 3
document.open();
// step 4
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate((float)bounds.getWidth(), (float)bounds.getHeight());
Graphics2D g2d = tp.createGraphics((float)bounds.getWidth(), (float)bounds.getHeight(), new DefaultFontMapper());
component.print(g2d);
g2d.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
}
public void doCopy() {
StringWriter writer = new StringWriter();
try {
if (treeViewer.getSelectionMode() == TreePaneSelector.SelectionMode.TAXA) {
writeTaxa(writer);
} else {
writeTreeFile(writer, ExportTreeDialog.Format.NEXUS, true, false, false, true, true);
}
} catch (IOException e) {
e.printStackTrace();
}
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection selection = new StringSelection(writer.toString());
clipboard.setContents(selection, selection);
}
public void doPaste() {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transfer = clipboard.getContents(null);
if (transfer.isDataFlavorSupported(DataFlavor.stringFlavor)) {
try {
String clip = (String)transfer.getTransferData(DataFlavor.stringFlavor);
boolean isNexus = clip.substring(0, Math.min(80, clip.length())).toUpperCase().contains("#NEXUS");
Reader reader = new StringReader(clip);
List<Tree> trees = new ArrayList<Tree>();
TreeImporter importer;
if (isNexus) {
importer = new FigTreeNexusImporter(reader);
} else {
importer = new NewickImporter(reader, true);
}
while (importer.hasTree()) {
Tree tree = importer.importNextTree();
trees.add(tree);
}
if (trees.size() == 0) {
throw new ImportException("This clipboard contained no trees.");
}
treeViewer.addTrees(trees);
// Show the first of the new trees
treeViewer.showNextTree();
setDirty();
} catch (ImportException ie) {
JOptionPane.showMessageDialog(this, "Error reading trees on clipboard: " + ie.getMessage(),
"Import Error",
JOptionPane.ERROR_MESSAGE);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "Error reading trees on clipboard: " + ioe.getMessage(),
"Import Error",
JOptionPane.ERROR_MESSAGE);
} catch (UnsupportedFlavorException e) {
JOptionPane.showMessageDialog(this, "Clipboard data is not compatible",
"Import Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public void doSelectAll() {
treeViewer.selectAll();
}
protected void writeTaxa(Writer writer) throws IOException {
PrintWriter printWriter = new PrintWriter(writer);
for (Taxon taxon : treeViewer.getSelectedTaxa()) {
printWriter.println(taxon.getName());
}
writer.close();
}
protected void writeTreeFile(Writer writer, ExportTreeDialog.Format format,
boolean writeAllTrees,
boolean writeAsDisplayed,
boolean writeFigTreeBlock,
boolean writeAnnotations,
boolean writeSelectedSubtree) throws IOException {
Map<String, Object> settings = null;
if (writeFigTreeBlock) {
settings = new TreeMap<String, Object>();
controlPalette.getSettings(settings);
}
List<Tree> trees = new ArrayList<Tree>();
if (writeSelectedSubtree) {
RootedTree tree = treeViewer.getSelectedSubtree();
if (tree != null) {
trees.add(tree);
}
} else {
trees.addAll(treeViewer.getTreesAsViewed());
}
if (trees.size() > 0) {
switch (format) {
case NEWICK:
NewickExporter newickExporter = new NewickExporter(writer);
newickExporter.exportTrees(trees);
break;
case NEXUS:
FigTreeNexusExporter nexusExporter = new FigTreeNexusExporter(writer, writeAnnotations);
nexusExporter.exportTrees(trees);
if (settings != null) {
nexusExporter.writeFigTreeBlock(settings);
}
break;
case JSON:
JSONTreeExporter jsonExporter = new JSONTreeExporter(writer, writeAnnotations);
jsonExporter.exportTrees(trees);
break;
}
}
writer.close();
}
public final void doFind() {
if (findPanel == null) {
findPanel = new FindPanel(findAllAction, null);
findPanel.setOpaque(false);
treeViewer.addAnnotationsListener(new AnnotationsListener() {
public void annotationsChanged() {
List<AnnotationDefinition> definitions = new ArrayList<AnnotationDefinition>(
treeViewer.getAnnotationDefinitions().values());
findPanel.setup(definitions);
}
});
List<AnnotationDefinition> definitions = new ArrayList<AnnotationDefinition>(
treeViewer.getAnnotationDefinitions().values());
findPanel.setup(definitions);
}
if (figTreePanel.getUtilityPanel() != findPanel) {
figTreePanel.showUtilityPanel(findPanel);
} else {
figTreePanel.hideUtilityPanel();
}
}
public final void doFindAll() {
FindPanel.Target target = findPanel.getSearchTarget();
String targetString = findPanel.getSearchTargetString();
if (findPanel.isNumericSearchType()) {
TreeViewer.NumberSearchType searchType = findPanel.getNumberSearchType();
Number searchValue = findPanel.getSearchValue();
if (target == FindPanel.Target.TAXON_LABEL) {
throw new IllegalArgumentException("Can't do numeric search on taxon labels");
} else if (target == FindPanel.Target.BRANCH_LENGTH) {
treeViewer.selectNodes("!length", searchType, searchValue);
} else if (target == FindPanel.Target.NODE_AGE) {
treeViewer.selectNodes("!height", searchType, searchValue);
} else if (target == FindPanel.Target.ANY_ANNOTATION) {
throw new IllegalArgumentException("Can't do numeric search on all annotations");
} else {
treeViewer.selectNodes(targetString, searchType, searchValue);
}
} else {
TreeViewer.TextSearchType searchType = findPanel.getTextSearchType();
String searchText = findPanel.getSearchText();
boolean caseSensitive = findPanel.isCaseSensitive();
if (target == FindPanel.Target.TAXON_LABEL) {
treeViewer.selectTaxa("!name", searchType, searchText, caseSensitive);
} else if (target == FindPanel.Target.BRANCH_LENGTH) {
throw new IllegalArgumentException("Can't do text search on branch lengths");
} else if (target == FindPanel.Target.NODE_AGE) {
throw new IllegalArgumentException("Can't do text search on node ages");
} else if (target == FindPanel.Target.ANY_ANNOTATION) {
treeViewer.selectNodes(null, searchType, searchText, caseSensitive);
} else {
treeViewer.selectNodes(targetString, searchType, searchText, caseSensitive);
}
}
}
public final void doFindNext() {
}
public final void doGetInfo() {
// List<AnnotationDefinition> definitions = treeViewer.getAnnotationDefinitions();
// JPanel panel = new FindPanel(definitions);
// panel.setOpaque(false);
// figTreePanel.showUtilityPanel(panel);
}
public JComponent getExportableComponent() {
return treeViewer.getContentPane();
}
@Override
public Action getImportColourSchemeAction() {
return importColourSchemeAction;
}
@Override
public Action getExportColourSchemeAction() {
return exportColourSchemeAction;
}
public Action getExportTreesAction() {
return exportTreesAction;
}
// public Action getExportGraphicAction() {
// return exportGraphicAction;
// }
public Action getExportPDFAction() {
return exportPDFAction;
}
public Action getExportPNGGraphicAction() {
return exportPNGGraphicAction;
}
public Action getExportJPEGGraphicAction() {
return exportJPEGGraphicAction;
}
public Action getExportSVGGraphicAction() {
return exportSVGAction;
}
public Action getNextTreeAction() {
return nextTreeAction;
}
public Action getPreviousTreeAction() {
return previousTreeAction;
}
public Action getCartoonAction() {
return cartoonAction;
}
public Action getCollapseAction() {
return collapseAction;
}
public Action getClearCollapsedAction() {
return clearCollapsedAction;
}
public Action getMidpointRootAction() {
return midpointRootAction;
}
public Action getRerootAction() {
return rerootAction;
}
public Action getClearRootingAction() {
return clearRootingAction;
}
public Action getIncreasingNodeOrderAction() {
return increasingNodeOrderAction;
}
public Action getDecreasingNodeOrderAction() {
return decreasingNodeOrderAction;
}
public Action getRotateAction() {
return rotateAction;
}
public Action getClearRotationsAction() {
return clearRotationsAction;
}
public Action getAnnotateAction() {
return annotateAction;
}
public Action getCopyAnnotationsAction() {
return copyAnnotationsAction;
}
public Action getAnnotateNodesFromTipsAction() {
return annotateNodesFromTipsAction;
}
public Action getAnnotateTipsFromNodesAction() {
return annotateTipsFromNodesAction;
}
public AbstractAction getClearAnnotationsAction() {
return clearAnnotationsAction;
}
public AbstractAction getDefineAnnotationsAction() {
return defineAnnotationsAction;
}
public Action getColourAction() {
return colourAction;
}
public Action getClearColouringAction() {
return clearColouringAction;
}
public Action getHilightAction() {
return hilightAction;
}
public Action getClearHilightingAction() {
return clearHilightingAction;
}
public Action getFindAction() {
return findAction;
}
private AbstractAction importAction = new AbstractAction("Import Annotations...") {
public void actionPerformed(ActionEvent ae) {
doImport();
}
};
private AbstractAction importCharactersAction = new AbstractAction("Import Characters...") {
public void actionPerformed(ActionEvent ae) {
doImportCharacters();
}
};
private AbstractAction importColourSchemeAction = new AbstractAction("Import Colour Scheme...") {
public void actionPerformed(ActionEvent ae) {
doImportColourScheme();
}
};
private AbstractAction exportColourSchemeAction = new AbstractAction("Export Colour Scheme...") {
public void actionPerformed(ActionEvent ae) {
// doExportColourScheme();
}
};
private AbstractAction exportTreesAction = new AbstractAction("Export Trees...") {
public void actionPerformed(ActionEvent ae) {
doExport();
}
};
// private AbstractAction exportGraphicAction = new AbstractAction("Export Graphic...") {
// public void actionPerformed(ActionEvent ae) {
// doExportGraphic(GraphicFormat.PNG);
// }
// };
private AbstractAction exportPNGGraphicAction = new AbstractAction("Export PNG...") {
public void actionPerformed(ActionEvent ae) {
doExportGraphic(GraphicFormat.PNG);
}
};
private AbstractAction exportJPEGGraphicAction = new AbstractAction("Export JPEG...") {
public void actionPerformed(ActionEvent ae) {
doExportGraphic(GraphicFormat.JPEG);
}
};
private AbstractAction exportSVGAction = new AbstractAction("Export SVG...") {
public void actionPerformed(ActionEvent ae) {
doExportGraphic(GraphicFormat.SVG);
}
};
private AbstractAction exportPDFAction = new AbstractAction("Export PDF...") {
public void actionPerformed(ActionEvent ae) {
doExportGraphic(GraphicFormat.PDF);
}
};
private AbstractAction nextTreeAction =
new AbstractAction(NEXT_TREE) {
public void actionPerformed(ActionEvent e){
treeViewer.showNextTree();
}
};
private AbstractAction previousTreeAction =
new AbstractAction(PREVIOUS_TREE) {
public void actionPerformed(ActionEvent e){
treeViewer.showPreviousTree();
}
};
private AbstractAction cartoonAction = new AbstractAction(CARTOON_NODE) {
public void actionPerformed(ActionEvent e){
cartoonSelected();
}
};
private AbstractAction collapseAction = new AbstractAction(COLLAPSE_NODE) {
public void actionPerformed(ActionEvent e){
collapseSelected();
}
};
private AbstractAction clearCollapsedAction = new AbstractAction(CLEAR_COLLAPSED) {
public void actionPerformed(ActionEvent e){
treeViewer.clearCollapsedNodes();
}
};
private AbstractAction rerootAction = new AbstractAction(ROOT_ON_BRANCH) {
public void actionPerformed(ActionEvent e){
rerootTree();
}
};
private AbstractAction midpointRootAction = new AbstractAction(MIDPOINT_ROOT) {
public void actionPerformed(ActionEvent e){
figTreePanel.toggleMidpointRoot();
}
};
private AbstractAction clearRootingAction = new AbstractAction(CLEAR_ROOTING) {
public void actionPerformed(ActionEvent e){
treeViewer.clearRooting();
}
};
private AbstractAction rotateAction = new AbstractAction(ROTATE_NODE) {
public void actionPerformed(ActionEvent e){
rotateTree();
}
};
private AbstractAction clearRotationsAction = new AbstractAction(CLEAR_ROTATIONS) {
public void actionPerformed(ActionEvent e){
treeViewer.clearRotations();
}
};
private AbstractAction increasingNodeOrderAction = new AbstractAction(INCREASING_NODE_ORDER) {
public void actionPerformed(ActionEvent e){
figTreePanel.toggleIncreasingNodeOrder();
}
};
private AbstractAction decreasingNodeOrderAction = new AbstractAction(DECREASING_NODE_ORDER) {
public void actionPerformed(ActionEvent e){
figTreePanel.toggleDecreasingNodeOrder();
}
};
private AbstractAction annotateAction = new AbstractAction(ANNOTATE) {
public void actionPerformed(ActionEvent ae) {
annotateSelected();
}
};
private AbstractAction copyAnnotationsAction = new AbstractAction(COPY_ANNOTATION_VALUES) {
public void actionPerformed(ActionEvent ae) {
copySelectedAnnotations();
}
};
private AbstractAction annotateNodesFromTipsAction = new AbstractAction(ANNOTATE_NODES_FROM_TIPS) {
public void actionPerformed(ActionEvent ae) {
annotateNodesFromTips();
}
};
private AbstractAction annotateTipsFromNodesAction = new AbstractAction(ANNOTATE_TIPS_FROM_NODES) {
public void actionPerformed(ActionEvent ae) {
annotateTipsFromNodes();
}
};
private AbstractAction clearAnnotationsAction = new AbstractAction(CLEAR_ANNOTATIONS) {
public void actionPerformed(ActionEvent ae) {
// treeViewer.clearAnnotation();
}
};
private AbstractAction defineAnnotationsAction = new AbstractAction(DEFINE_ANNOTATIONS) {
public void actionPerformed(ActionEvent ae) {
defineAnnotations();
}
};
private AbstractAction colourAction = new AbstractAction(COLOUR) {
public void actionPerformed(ActionEvent ae) {
colourSelected();
}
};
private AbstractAction clearColouringAction = new AbstractAction(CLEAR_COLOURING) {
public void actionPerformed(ActionEvent ae) {
treeViewer.clearColouring();
}
};
private AbstractAction hilightAction = new AbstractAction(HILIGHT) {
public void actionPerformed(ActionEvent ae) {
hilightSelected();
}
};
private AbstractAction clearHilightingAction = new AbstractAction(CLEAR_HILIGHTING) {
public void actionPerformed(ActionEvent ae) {
treeViewer.clearHilighting();
}
};
private AbstractAction findAction = new AbstractAction("Find...") {
public void actionPerformed(ActionEvent ae) {
doFind();
}
};
private AbstractAction findAllAction = new AbstractAction("Find") {
public void actionPerformed(ActionEvent ae) {
doFindAll();
}
};
// private AbstractAction findNextAction = new AbstractAction("Find Next") {
// public void actionPerformed(ActionEvent ae) {
// doFindNext();
// }
// };
private AbstractAction getInfoAction = new AbstractAction("Get Info...") {
public void actionPerformed(ActionEvent ae) {
doGetInfo();
}
};
private ExportTreeDialog exportTreeDialog = null;
private FindPanel findPanel = null;
private AnnotationDefinitionsDialog annotationDefinitionsDialog = null;
private AnnotationDialog annotationDialog = null;
private AnnotationDialog copyAnnotationDialog = null;
private SelectAnnotationDialog selectAnnotationDialog = null;
}
|