file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
AuxBlocksFooterRMA3.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma3/AuxBlocksFooterRMA3.java | /*
* AuxBlocksFooterRMA3.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.rma3;
import jloda.util.Pair;
import megan.io.IInputReader;
import megan.io.IOutputWriter;
import java.io.IOException;
import java.util.Map;
/**
* Aux-blocks footer
* Created by huson on 5/16/14.
*/
public class AuxBlocksFooterRMA3 extends BaseRMA3 {
private String auxDataFormat = "Name:String Data:Bytes";
private int count = 0;
/**
* constructor
*/
public AuxBlocksFooterRMA3() {
super("AuxDataFormat:String Count:Integer");
}
@Override
public void read(IInputReader reader, long startPos) throws IOException {
reader.seek(startPos);
setFormatDef(reader.readString());
FormatDefinition formatDefinition = FormatDefinition.fromString(getFormatDef());
for (Pair<String, FormatDefinition.Type> pair : formatDefinition.getList()) {
if (pair.getFirst().equals("AuxDataFormat"))
setAuxDataFormat(reader.readString());
else if (pair.getFirst().equals("Count"))
setCount(reader.readInt());
}
}
@Override
public void write(IOutputWriter writer) throws IOException {
writer.writeString(getFormatDef());
FormatDefinition formatDefinition = FormatDefinition.fromString(getFormatDef());
formatDefinition.startWrite();
for (Pair<String, FormatDefinition.Type> pair : formatDefinition.getList()) {
if (pair.getFirst().equals("AuxDataFormat"))
formatDefinition.write(writer, "AuxDataFormat", getAuxDataFormat());
else if (pair.getFirst().equals("Count"))
formatDefinition.write(writer, "Count", getCount());
}
formatDefinition.finishWrite();
}
/**
* auxiliary method that can be used to write auxblocks to RMA3 file
*
*/
public void writeAuxBlocks(IOutputWriter writer, Map<String, byte[]> name2AuxData) throws IOException {
setCount(name2AuxData.size());
for (String name : name2AuxData.keySet()) {
writer.writeString(name);
byte[] bytes = name2AuxData.get(name);
writer.writeInt(bytes.length);
writer.write(bytes);
}
}
/**
* read the aux blocks from a file
*
*/
public void readAuxBlocks(FileFooterRMA3 fileFooter, IInputReader reader, Map<String, byte[]> name2AuxBlock) throws IOException {
reader.seek(fileFooter.getAuxStart());
for (int i = 0; i < count && reader.getPosition() < fileFooter.getAuxFooter(); i++) {
String name = reader.readString();
int length = reader.readInt();
byte[] bytes = new byte[length];
reader.read(bytes, 0, length);
name2AuxBlock.put(name, bytes);
}
}
private String getAuxDataFormat() {
return auxDataFormat;
}
private void setAuxDataFormat(String auxDataFormat) {
this.auxDataFormat = auxDataFormat;
}
private int getCount() {
return count;
}
private void setCount(int count) {
this.count = count;
}
}
| 3,900 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
IMatch.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma3/IMatch.java | /*
* IMatch.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.rma3;
import java.io.IOException;
/**
* Match interface for RMA3 creator
* Created by huson on 10/16/14.
*/
public interface IMatch {
void clear();
void parse(String aLine) throws IOException;
int getBitScore();
float getExpected();
int getPercentIdentity();
String getQueryName();
String getRefName();
}
| 1,160 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FormatDefinition.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma3/FormatDefinition.java | /*
* FormatDefinition.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.rma3;
import jloda.util.Pair;
import megan.io.IOutputWriter;
import java.io.IOException;
import java.util.*;
/**
* Used to define the format of a binary data block in an RMA3 file
* Created by huson on 5/13/14.
*/
public class FormatDefinition {
public enum Type {
Integer, Long, Float, String, Character, Byte;
static Type getType(Object object) throws IOException {
if (object instanceof java.lang.Integer) return Integer;
if (object instanceof java.lang.Long) return Long;
if (object instanceof java.lang.Float) return Float;
if (object instanceof java.lang.String) return String;
if (object instanceof java.lang.Character) return Character;
if (object instanceof java.lang.Byte) return Byte;
throw new IOException("Unknown type: " + object.getClass().toString());
}
}
private final List<Pair<String, Type>> list = new LinkedList<>();
private final Map<String, Pair<String, Type>> map = new HashMap<>();
private Iterator<Pair<String, Type>> writerIterator = null;
private void addItem(String word, Type type) {
Pair<String, Type> pair = new Pair<>(word, type);
list.add(pair);
map.put(word, pair);
}
public void removeItem(String word) {
Pair<String, Type> pair = map.get(word);
if (pair != null) {
list.remove(pair);
map.keySet().remove(word);
}
}
public Type getItemType(String word) {
Pair<String, Type> pair = map.get(word);
if (pair != null)
return pair.getSecond();
else
return null;
}
public boolean hasItem(String word) {
return map.containsKey(word);
}
public void clear() {
list.clear();
map.clear();
}
public Iterator<Pair<String, Type>> iterator() {
return list.iterator();
}
public List<Pair<String, Type>> getList() {
return list;
}
public String toString() {
StringBuilder buf = new StringBuilder();
boolean first = true;
for (Pair<String, Type> pair : list) {
if (first)
first = false;
else
buf.append(" ");
buf.append(pair.getFirst()).append(":").append(pair.getSecond().toString());
}
return buf.toString();
}
/**
* create a format definition from a defining string
*
* @return format definition
*/
public static FormatDefinition fromString(String string) {
FormatDefinition formatDefinition = new FormatDefinition();
String[] tokens = string.split(" ");
for (String word : tokens) {
int pos = word.indexOf(":");
formatDefinition.addItem(word.substring(0, pos), Type.valueOf(word.substring(pos + 1)));
}
return formatDefinition;
}
/**
* call this when starting to write formatted output
*/
public void startWrite() {
writerIterator = null;
}
/**
* write an item to the output writer. Throws an exception of doesn't make the
* defined format
*
*/
public void write(IOutputWriter outputWriter, String label, Object value) throws IOException {
if (writerIterator == null)
writerIterator = list.iterator();
Pair<String, Type> current = writerIterator.next();
if (current == null || !label.equals(current.getFirst()))
throw new IOException("write(): Unexpected label: " + label);
switch (Type.getType(value)) {
case Integer -> outputWriter.writeInt((Integer) value);
case Long -> outputWriter.writeLong((Long) value);
case Float -> outputWriter.writeFloat((Float) value);
case String -> outputWriter.writeStringNoCompression((String) value);
case Byte -> outputWriter.write((Byte) value);
case Character -> outputWriter.writeChar((Character) value);
default -> throw new IOException("Invalid type: " + value);
}
}
public void finishWrite() throws IOException {
if (writerIterator == null)
throw new IOException("finishWrite(): nothing written");
if (writerIterator.hasNext())
throw new IOException("finishWrite(): not finished");
writerIterator = null;
}
public static void main(String[] args) {
String test = "taxon:Integer seed:Integer kegg:Integer bitScore:Float name:String";
FormatDefinition def = FormatDefinition.fromString(test);
System.err.println("Got: " + def);
}
}
| 5,497 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
BlastTabMatch.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/rma3/BlastTabMatch.java | /*
* BlastTabMatch.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.rma3;
import jloda.util.NumberUtils;
/**
* simple tab match
* Created by huson on 10/16/14.
*/
public class BlastTabMatch implements IMatch {
private int bitScore;
private float expected;
private int percentIdentity;
private String queryName;
private String refName;
@Override
public void clear() {
}
/**
* parse a blast tab line
* query id, ref id, percent identity, alignment length, number of mismatches, number of gap openings, query start, query end, subject start, subject end, Expect value, HSP bit score.
* 0 1 2 3 4 5 6 7 8 9 10 11
*
*/
@Override
public void parse(String aLine) {
String[] tokens = aLine.split("\t");
if (tokens.length == 1) {
clear();
queryName = tokens[0];
} else {
queryName = tokens[0];
refName = tokens[1];
bitScore = NumberUtils.parseInt(tokens[11]);
expected = NumberUtils.parseFloat(tokens[10]);
percentIdentity = NumberUtils.parseInt(tokens[2]);
}
}
@Override
public int getBitScore() {
return bitScore;
}
@Override
public float getExpected() {
return expected;
}
@Override
public int getPercentIdentity() {
return percentIdentity;
}
@Override
public String getQueryName() {
return queryName;
}
@Override
public String getRefName() {
return refName;
}
}
| 2,449 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClassificationViewer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/ClassificationViewer.java | /*
* ClassificationViewer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import jloda.graph.*;
import jloda.phylo.PhyloTree;
import jloda.swing.commands.CommandManager;
import jloda.swing.director.*;
import jloda.swing.export.ExportManager;
import jloda.swing.find.FindToolBar;
import jloda.swing.find.SearchManager;
import jloda.swing.format.Formatter;
import jloda.swing.graphview.*;
import jloda.swing.util.PopupMenu;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.*;
import jloda.swing.window.MenuBar;
import jloda.util.*;
import jloda.util.progress.ProgressListener;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.classification.data.SyncDataTableAndClassificationViewer;
import megan.core.Director;
import megan.core.Document;
import megan.dialogs.compare.Comparer;
import megan.dialogs.input.InputDialog;
import megan.main.MeganProperties;
import megan.util.DrawScaleBox;
import megan.viewer.gui.NodeDrawer;
import megan.viewer.gui.ViewerJTable;
import megan.viewer.gui.ViewerJTree;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import java.util.*;
/**
* Classification viewer
*
* @author Daniel Huson, 4.2015
*/
public class ClassificationViewer extends ViewerBase implements IDirectableViewer, IViewerWithFindToolBar, IViewerWithLegend, IUsesHeatMapColors {
static public final int XSTEP = 50;
static public final int YSTEP = 50;
private static final int HLEAFBOX = 200; // horizontal length of leaf box, needed for picking
private final JFrame frame;
private final StatusBar statusBar;
private final Map<Integer, NodeData> id2NodeData = new HashMap<>();
private final Map<Integer, Set<Node>> id2Nodes = new HashMap<>();
private final Map<Integer, Integer> id2rank;
private final Map<Integer, String> id2toolTip;
private final JSplitPane mainSplitPane;
private final ViewerJTable viewerJTable;
private final ViewerJTree viewerJTree;
private boolean showFindToolBar = false;
private final SearchManager searchManager;
private boolean uptodate = true;
private long lastRecomputeTimeFromDocument = -1;
private int totalAssignedReads = 0;
private final NodeSet nodesWithMovedLabels; // track node labels that have been moved
private final NodeArray<Rectangle> node2BoundingBox;
// some one-time calculations
private boolean doScrollToRight = false;
private boolean drawOnScreen = true;
private boolean mustDrawTwice = false;
private final MenuBar menuBar;
private boolean avoidSelectionBounce = false;
Classification classification;
private final boolean useReadWeights = false;
private boolean showScaleBox = ProgramProperties.get("ShowScaleBox", true);
/**
* Classification viewer
*
* @param dir the director
*/
public ClassificationViewer(final Director dir, final Classification classification, boolean visible) {
super(dir, new PhyloTree(), false);
this.classification = classification;
setDefaultEdgeDirection(EdgeView.UNDIRECTED);
setDefaultEdgeColor(Color.BLACK);
setDefaultNodeColor(Color.BLACK);
setDefaultNodeBackgroundColor(Color.WHITE);
try {
drawerType = DiagramType.valueOf(ProgramProperties.get("DrawerType" + getClassName(), DiagramType.RoundedCladogram.toString()));
} catch (Exception e) {
drawerType = DiagramType.RoundedCladogram;
}
id2rank = classification.getId2Rank();
id2toolTip = classification.getId2ToolTip();
setGraphDrawer(new DefaultGraphDrawer(this));
getGraphDrawer().setNodeDrawer(nodeDrawer);
getNodeDrawer().setStyle(doc.getDataTable().getNodeStyle(getClassName()), this instanceof MainViewer ? NodeDrawer.Style.Circle : dir.getMainViewer().getNodeDrawer().getStyle());
getNodeDrawer().setScaleBy(Arrays.asList(ProgramProperties.get(MeganProperties.TAXONOMIC_CLASSIFICATIONS, new String[]{"Taxonomy", "GTDB"})).contains(classification.getName()) ? NodeDrawer.ScaleBy.Assigned : NodeDrawer.ScaleBy.Summarized);
this.commandManager = new CommandManager(dir, this, new String[]{"megan.commands", "megan.viewer.commands"}, !ProgramProperties.isUseGUI());
node2BoundingBox = new NodeArray<>(getTree());
nodesWithMovedLabels = new NodeSet(getGraph());
setCanvasColor(Color.WHITE);
setAllowMoveNodes(false);
setAllowMoveInternalEdgePoints(false);
setFixedNodeSize(false);
setAutoLayoutLabels(true);
setAllowEdit(false);
trans.setLockXYScale(false);
trans.setTopMargin(100);
trans.setLeftMargin(150);
trans.setRightMargin(250);
setAutoLayoutLabels(false);
setPreferredSize(new Dimension(0, 0));
super.getScrollPane().getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
super.getScrollPane().setWheelScrollingEnabled(true);
super.getScrollPane().setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setGraphViewListener(new MyGraphViewListener(this, node2BoundingBox, nodesWithMovedLabels));
setPOWEREDBY(null);
trans.removeAllChangeListeners();
trans.addChangeListener(trans -> {
final Dimension ps = trans.getPreferredSize();
int x = Math.max(ps.width, ClassificationViewer.super.getScrollPane().getWidth() - 20);
int y = Math.max(ps.height, ClassificationViewer.super.getScrollPane().getHeight() - 20);
ps.setSize(x, y);
setPreferredSize(ps);
ClassificationViewer.super.getScrollPane().getViewport().setViewSize(new Dimension(x, y));
repaint();
});
statusBar = new StatusBar();
frame = new JFrame();
frame.setIconImages(ProgramProperties.getProgramIconImages());
this.menuBar = new MenuBar(this, GUIConfiguration.getMenuConfiguration(), getCommandManager());
getFrame().setJMenuBar(menuBar);
MeganProperties.addPropertiesListListener(menuBar.getRecentFilesListener());
MeganProperties.notifyListChange(ProgramProperties.RECENTFILES);
if (!(this instanceof MainViewer))
ProjectManager.addAnotherWindowWithWindowMenu(dir, menuBar.getWindowMenu());
setWindowTitle();
viewerJTable = new ViewerJTable(this);
viewerJTree = new ViewerJTree(this);
mainPanel.add(getScrollPane());
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Overview", new JScrollPane(viewerJTree));
tabbedPane.add("Heatmap", new JScrollPane(viewerJTable));
mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, tabbedPane, splitPane);
mainSplitPane.setDividerLocation(250);
mainSplitPane.setOneTouchExpandable(true);
mainSplitPane.setEnabled(true);
getFrame().getContentPane().setLayout(new BorderLayout());
JToolBar toolBar = new ToolBar(this, GUIConfiguration.getToolBarConfiguration(), getCommandManager());
getFrame().getContentPane().add(toolBar, BorderLayout.NORTH);
getFrame().getContentPane().add(mainSplitPane, BorderLayout.CENTER);
getFrame().getContentPane().add(statusBar, BorderLayout.SOUTH);
searchManager = new SearchManager(dir, this, new ClassificationViewerSearcher(getFrame(), getClassName(), this), false, true);
getFrame().pack();
getFrame().setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
final int[] geometry = ProgramProperties.get(ClassificationManager.getWindowGeometryKey(getClassName()), new int[]{100, 100, 800, 600});
if (getClassName().equals(Classification.Taxonomy))
getFrame().setLocation(geometry[0] + (ProjectManager.getNumberOfProjects() > 0 ? 20 : 0), geometry[1] + (ProjectManager.getNumberOfProjects() > 0 ? 20 : 0));
else
getFrame().setLocationRelativeTo(MainViewer.getLastActiveFrame());
getFrame().setSize(geometry[2], geometry[3]);
// add window listeners
addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e) {
componentResized(e);
}
public void componentResized(ComponentEvent event) {
if ((event.getID() == ComponentEvent.COMPONENT_RESIZED || event.getID() == ComponentEvent.COMPONENT_MOVED) &&
(getFrame().getExtendedState() & JFrame.MAXIMIZED_HORIZ) == 0
&& (getFrame().getExtendedState() & JFrame.MAXIMIZED_VERT) == 0) {
ProgramProperties.put(ClassificationManager.getWindowGeometryKey(getClassName()), new int[]{getFrame().getLocation().x, getFrame().getLocation().y, getFrame().getSize().width,
getFrame().getSize().height}
);
}
}
});
getFrame().addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent event) {
//System.err.println(getTitle()+" activiated");
//Basic.caught(new Exception());
MainViewer.setLastActiveFrame(getFrame());
if (Formatter.getInstance() != null) {
Formatter.getInstance().setViewer(dir, ClassificationViewer.this);
}
InputDialog inputDialog = InputDialog.getInstance();
if (inputDialog != null)
inputDialog.setViewer(dir, ClassificationViewer.this);
//ClassificationViewer.this.requestFocusInWindow();
}
public void windowDeactivated(WindowEvent event) {
Collection<String> selectedLabels = getSelectedNodeLabels(false);
if (selectedLabels.size() != 0) {
ProjectManager.getPreviouslySelectedNodeLabels().clear();
ProjectManager.getPreviouslySelectedNodeLabels().addAll(selectedLabels);
}
}
public void windowClosing(WindowEvent e) {
if (dir.getDocument().getProgressListener() != null)
dir.getDocument().getProgressListener().setUserCancelled(true);
if (MainViewer.getLastActiveFrame() == getFrame())
MainViewer.setLastActiveFrame(null);
}
});
this.addNodeActionListener(new NodeActionAdapter() {
public void doSelect(NodeSet nodes) {
if (!avoidSelectionBounce) {
avoidSelectionBounce = true;
Set<Integer> ids = getAllIds(nodes);
if (ids.size() > 0) {
viewerJTree.setSelected(ids, true);
viewerJTable.setSelected(ids, true);
}
if (!ClassificationViewer.this.isLocked())
getCommandManager().updateEnableState();
updateStatusBarTooltip();
avoidSelectionBounce = false;
}
}
public void doDeselect(NodeSet nodes) {
if (!avoidSelectionBounce) {
avoidSelectionBounce = true;
Set<Integer> ids = getAllIds(nodes);
if (ids.size() > 0) {
viewerJTree.setSelected(ids, false);
viewerJTable.setSelected(ids, false);
}
if (!ClassificationViewer.this.isLocked())
getCommandManager().updateEnableState();
updateStatusBarTooltip();
avoidSelectionBounce = false;
}
}
// double click: select subtree
public void doClick(NodeSet nodes, int clicks) {
if (clicks == 2) {
selectedNodes.addAll(nodes);
selectSubTreeNodes();
fireDoSelect(selectedNodes);
ClassificationViewer.this.repaint();
}
}
// double click label: inspect node
public void doClickLabel(NodeSet nodes, int clicks) {
}
});
super.getScrollPane().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent event) {
trans.fireHasChanged();
}
});
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
getScrollPane().requestFocusInWindow();
}
});
// at start up, collapse to subsystems:
for (Edge e = classification.getFullTree().getRoot().getFirstOutEdge(); e != null; e = classification.getFullTree().getRoot().getNextOutEdge(e)) {
getCollapsedIds().add((Integer) e.getTarget().getInfo());
}
setPopupListener(new GraphViewPopupListener(this, GUIConfiguration.getNodePopupConfiguration(),
GUIConfiguration.getEdgePopupConfiguration(),
GUIConfiguration.getPanelPopupConfiguration(), commandManager));
SyncDataTableAndClassificationViewer.syncCollapsedFromSummary2Viewer(doc.getDataTable(), this);
legendPanel.setPopupMenu(new PopupMenu(this, megan.chart.gui.GUIConfiguration.getLegendPanelPopupConfiguration(), commandManager));
setupKeyListener();
splitPane.setDividerLocation(1);
if (doc.getNumberOfSamples() > 1 || Arrays.asList(ProgramProperties.get(MeganProperties.TAXONOMIC_CLASSIFICATIONS, new String[]{"Taxonomy", "GTDB"})).contains(classification.getName())) {
getMainSplitPane().getLeftComponent().setMinimumSize(new Dimension());
getMainSplitPane().setDividerLocation(0);
}
getFrame().setVisible(visible);
}
/**
* display number of selected nodes etc as tooltip on status bar.
* Waits a while before doing so, because there may be multiple updates of the selection state
*/
private void updateStatusBarTooltip() {
SwingUtilities.invokeLater(() -> {
if (getSelectedNodes().size() > 0) {
double numberOfAssigned = 0;
double numberOfSummarized = 0;
for (Node v : getSelectedNodes()) {
if (v.getData() instanceof NodeData) {
NodeData nodeData = (NodeData) v.getData();
numberOfAssigned += nodeData.getCountAssigned();
numberOfSummarized += nodeData.getCountSummarized();
}
}
final String line = (String.format("Selected nodes: %,d, total assigned: %,d, total summarized: %,d", getSelectedNodes().size(),
Math.round(numberOfAssigned), Math.round(numberOfSummarized)));
//System.err.println(line);
statusBar.setToolTipText(line);
} else
statusBar.setToolTipText(null);
});
}
/**
* gets the summarized array for a fid
*
* @return summarized
*/
public float[] getSummarized(int fId) {
Node v = getANode(fId);
return getNodeData(v).getSummarized();
}
/**
* ask view to rescan itself. This is method is wrapped into a runnable
* object and put in the swing event queue to avoid concurrent
* modifications.
*
* @param what what should be updated? Possible values: Director.ALL or
* Director.TITLE
*/
public void updateView(final String what) {
if (what.equals(Director.ALL)) {
// rescan colors
final List<String> samples = doc.getSampleNames();
doc.getChartColorManager().setSampleColorPositions(samples);
for (int i = 0; i < samples.size(); i++) {
doc.setColorByIndex(i, doc.getChartColorManager().getSampleColor(samples.get(i)));
}
setFont(ProgramProperties.get(ProgramProperties.DEFAULT_FONT, getFont()));
if (lastRecomputeTimeFromDocument != dir.getDocument().getLastRecomputeTime()) {
lastRecomputeTimeFromDocument = dir.getDocument().getLastRecomputeTime();
// System.err.println("RECOMPUTING at "+lastRecomputeTimeFromDocument);
updateData();
updateTree();
}
if (hasSyncedFormatFromSummaryToViewer)
SyncDataTableAndClassificationViewer.syncFormattingFromViewer2Summary(this, doc.getDataTable());
// scroll back to previous nodes of interest
if (getPreviousNodeIdsOfInterest() != null) {
for (Integer id : getPreviousNodeIdsOfInterest()) {
Node v = getANode(id);
if (v != null) {
setSelected(v, true);
}
}
// trans.setScaleY(1);
zoomToSelection();
setPreviousNodeIdsOfInterest(null);
}
setupNodeLabels(true);
repaint();
}
final FindToolBar findToolBar = searchManager.getFindDialogAsToolBar();
if (findToolBar.isClosing()) {
showFindToolBar = false;
findToolBar.setClosing(false);
}
if (!findToolBar.isEnabled() && showFindToolBar) {
mainPanel.add(findToolBar, BorderLayout.NORTH);
findToolBar.setEnabled(true);
getFrame().getContentPane().validate();
} else if (findToolBar.isEnabled() && !showFindToolBar) {
mainPanel.remove(findToolBar);
findToolBar.setEnabled(false);
getFrame().getContentPane().validate();
}
getCommandManager().updateEnableState();
if (findToolBar.isEnabled())
findToolBar.clearMessage();
if (showLegend.equals("undefined") && doc.getNumberOfSamples() > 0 && doc.getNumberOfSamples() < 100) {
setShowLegend(doc.getNumberOfSamples() <= 1 ? "none" : "horizontal");
}
legendPanel.setStyle(getNodeDrawer().getStyle());
legendPanel.updateView();
if (doc.getNumberOfSamples() <= 1)
splitPane.setDividerLocation(1.0);
legendPanel.repaint();
setWindowTitle();
//requestFocusInWindow();
}
/**
* rescan the data in the FViewer
*
*/
private void updateData() {
ProgressListener progress = doc.getProgressListener();
boolean saveCancelable = false;
if (progress != null) {
saveCancelable = progress.isCancelable();
progress.setSubtask("updating viewer");
progress.setCancelable(false);
try {
progress.setProgress(-1);
} catch (CanceledException ignored) {
}
}
totalAssignedReads = 0;
classification.getFullTree().computeId2Data(doc.getNumberOfSamples(), doc.getDataTable().getClass2Counts(getClassName()), id2NodeData);
for (Integer fId : id2NodeData.keySet()) {
if (fId > 0) {
totalAssignedReads += id2NodeData.get(fId).getCountAssigned();
//System.err.println(classification.getName2IdMap().get(fId)+": "+id2NodeData.get(fId).getCountAssigned());
}
}
if (progress != null)
progress.setCancelable(saveCancelable);
getCommandManager().updateEnableState();
}
private boolean hasSyncedFormatFromSummaryToViewer = false;
/**
* Constructs and updates the tree
*/
public void updateTree() {
final PhyloTree tree = getTree();
if (hasSyncedFormatFromSummaryToViewer)
SyncDataTableAndClassificationViewer.syncFormattingFromViewer2Summary(this, doc.getDataTable());
classification.getFullTree().extractInducedTree(id2NodeData, getCollapsedIds(), tree, id2Nodes);
nodeDrawer.setCounts(determineMaxCount());
if (tree.getRoot() != null) {
embedTree(tree.getRoot());
}
nodesWithMovedLabels.clear();
trans.setCoordinateRect(getBBox());
Rectangle rect = new Rectangle();
trans.w2d(getBBox(), rect);
setPreferredSize(rect.getSize());
if (tree.getRoot() != null) {
for (Edge e = tree.getRoot().getFirstOutEdge(); e != null; e = tree.getRoot().getNextOutEdge(e)) {
Node v = e.getTarget();
int id = (Integer) v.getInfo();
if (id == -1 || id == -2 || id == -3 || id == -6) {
setColor(e, Color.LIGHT_GRAY);
setColor(v, Color.LIGHT_GRAY);
setLabelColor(v, Color.LIGHT_GRAY);
}
}
/*
for (Node v = tree.getFirstNode(); v != null; v = v.getNext()) {
setLabel(v, tree.getLabel(v));
// make sure that there aren't any black nodes!
if (nodeDrawer.getStyle() == NodeDrawer.Style.Circle && getBackgroundColor(v).equals(Color.BLACK))
setBackgroundColor(v, Color.WHITE);
if ((Integer) v.getInfo() >= -3 && (Integer) v.getInfo() <= -1) {
setColor(v, Color.LIGHT_GRAY);
setLabelColor(v, Color.LIGHT_GRAY);
if (v.getInDegree() > 0) {
setColor(v.getFirstInEdge(), Color.LIGHT_GRAY);
}
} else if (v.getInDegree() > 0)
setColor(v.getFirstInEdge(), Color.BLACK);
}
*/
setColor(getTree().getRoot(), Color.LIGHT_GRAY);
setLabelColor(getTree().getRoot(), Color.LIGHT_GRAY);
for (Edge e = tree.getRoot().getFirstOutEdge(); e != null; e = tree.getRoot().getNextOutEdge(e))
setColor(e, Color.LIGHT_GRAY);
if (getNumberOfDatasets() > 1 && nodeDrawer.getStyle() == NodeDrawer.Style.Circle) {
legendPanel.setStyle(getNodeDrawer().getStyle());
}
setupNodeLabels(false);
}
fitGraphToWindow();
if (!hasSyncedFormatFromSummaryToViewer) {
SyncDataTableAndClassificationViewer.syncFormattingFromSummary2Viewer(doc.getDataTable(), this);
hasSyncedFormatFromSummaryToViewer = true;
}
repaint();
updateStatusBar();
setPOWEREDBY(getMajorityRankOfLeaves());
viewerJTable.update();
viewerJTree.update();
}
/**
* get the majority rank of leaves or null
*
* @return name of majority rank or null
*/
private String getMajorityRankOfLeaves() {
if (classification.getId2Rank().size() > 0) {
int[] rank2count = new int[Byte.MAX_VALUE + 1];
int count = 0;
for (Node v = getTree().getFirstNode(); v != null; v = v.getNext()) {
if (v.getOutDegree() == 0) {
Integer rank = classification.getId2Rank().get(v.getInfo());
if (rank != null && rank > 0)
rank2count[rank]++;
count++;
}
}
for (int i = 0; i <= Byte.MAX_VALUE; i++) {
if (rank2count[(byte) i] > count / 2) {
return TaxonomicLevels.getName((byte) i);
}
}
}
return null;
}
/**
* sets the title of the window
*/
private void setWindowTitle() {
String newTitle;
if (getClassName().equals(Classification.Taxonomy))
newTitle = dir.getDocument().getTitle();
else
newTitle = getClassName() + " Viewer - " + dir.getDocument().getTitle();
if (doc.getMeganFile().isMeganServerFile())
newTitle += " (remote file)";
if (doc.getMeganFile().isReadOnly())
newTitle += " (read-only)";
else if (doc.isDirty())
newTitle += "*";
if (dir.getID() == 1)
newTitle += " - " + ProgramProperties.getProgramVersion();
else
newTitle += " - [" + dir.getID() + "] - " + ProgramProperties.getProgramVersion();
if (!getFrame().getTitle().equals(newTitle)) {
getFrame().setTitle(newTitle);
ProjectManager.updateWindowMenus();
}
}
/**
* gets the getFrame()
*
*/
public JFrame getFrame() {
// Basic.caught(new Exception());
return frame;
}
/*
* (non-Javadoc)
*
* @see jloda.director.IDirectableViewer#isUptoDate()
*/
public boolean isUptoDate() {
return uptodate;
}
/*
* (non-Javadoc)
*
* @see jloda.director.IDirectorListener#destroyView()
*/
public void destroyView() throws CanceledException {
ProgramProperties.put(ClassificationManager.getWindowGeometryKey(getClassName()), new int[]{
getFrame().getLocation().x, getFrame().getLocation().y, getFrame().getSize().width, getFrame().getSize().height});
SyncDataTableAndClassificationViewer.syncFormattingFromViewer2Summary(this, doc.getDataTable());
searchManager.getFindDialogAsToolBar().close();
getFrame().setVisible(false);
MeganProperties.removePropertiesListListener(menuBar.getRecentFilesListener());
if (MainViewer.getLastActiveFrame() == this.getFrame())
MainViewer.setLastActiveFrame(null);
dir.removeViewer(this);
getFrame().dispose();
}
/**
* gets the window menu
*
* @return window menu
*/
public JMenu getWindowMenu() {
return menuBar.getWindowMenu();
}
/*
* (non-Javadoc)
*
* @see jloda.director.IDirectorListener#lockUserInput()
*/
public void lockUserInput() {
locked = true;
statusBar.setText1("");
statusBar.setText2("Busy...");
getFrame().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
getScrollPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
getLegendPanel().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
getCommandManager().setEnableCritical(false);
searchManager.getFindDialogAsToolBar().setEnableCritical(false);
menuBar.setEnableRecentFileMenuItems(false);
}
/*
* (non-Javadoc)
*
* @see jloda.director.IDirectorListener#setUptoDate(boolean)
*/
public void setUptoDate(final boolean flag) {
uptodate = flag;
}
/*
* (non-Javadoc)
*
* @see jloda.director.IDirectorListener#unlockUserInput()
*/
public void unlockUserInput() {
locked = false;
getCommandManager().setEnableCritical(true);
searchManager.getFindDialogAsToolBar().setEnableCritical(true);
getFrame().setCursor(Cursor.getDefaultCursor());
getScrollPane().setCursor(Cursor.getDefaultCursor());
getLegendPanel().setCursor(Cursor.getDefaultCursor());
menuBar.setEnableRecentFileMenuItems(true);
updateStatusBar();
}
/**
* rescan the status bar
*/
void updateStatusBar() {
statusBar.setText1("Terms=%,d".formatted(getTree().getNumberOfNodes()));
final long totalReads = doc.getNumberOfReads();
final StringBuilder buf2 = new StringBuilder();
if (doc.getNumberOfSamples() > 1) {
Comparer.COMPARISON_MODE mode = Comparer.parseMode(doc.getDataTable().getParameters());
if (mode.equals(Comparer.COMPARISON_MODE.RELATIVE)) {
buf2.append(String.format("Relative comparison, Assigned=%,d (normalized to %,d per sample)", totalReads, Comparer.parseNormalizedTo(doc.getDataTable().getParameters())));
} else
buf2.append(String.format("Absolute comparison, Reads=%,d Assigned=%,d", totalReads, totalAssignedReads));
} else if (totalReads > 0) {
buf2.append(String.format("Reads=%,d Assigned=%,d", totalReads, totalAssignedReads));
if (doc.getReadAssignmentMode() == Document.ReadAssignmentMode.readMagnitude)
buf2.append(String.format(" (%s)", doc.getReadAssignmentMode().toString()));
} else {
if (getTree().getNumberOfNodes() > 0)
buf2.append(String.format(" total terms=%,d", getTree().getNumberOfNodes()));
}
if (Document.getVersionInfo().get(getClassName() + " tree") != null)
buf2.append(" ").append(StringUtils.skipFirstLine(Document.getVersionInfo().get(getClassName() + " tree")).replaceAll("\\s+", " "));
statusBar.setText2(buf2.toString());
}
/**
* gets the nodes associated with the given f id
*
* @return nodes or null
* todo: modify to use all nodes associated with this id
*/
public Set<Node> getNodes(int fId) {
return id2Nodes.get(fId);
}
public Set<Integer> getIds() {
return id2Nodes.keySet();
}
/**
* get a node associated with the given fId
*
* @return a node or null
*/
public Node getANode(int fId) {
Set<Node> nodes = getNodes(fId);
if (nodes != null && nodes.size() > 0)
return nodes.iterator().next();
else
return null;
}
/**
* is node with this f id selected?
*
* @return selected?
*/
public boolean isSelected(int fId) {
Node v = getANode(fId);
return v != null && getSelected(v);
}
public String getTitle() {
return getFrame().getTitle();
}
/**
* embeds a tree is a phylogram from the given root, using the given h- and v-spacing
*
*/
private void embedTree(Node root) {
removeAllInternalPoints();
node2BoundingBox.clear();
for (Node v = getTree().getFirstNode(); v != null; v = v.getNext()) {
setLocation(v, null);
getNV(v).setFixedSize(true);
}
if (getDrawerType() == DiagramType.RectangularPhylogram || getDrawerType() == DiagramType.RoundedPhylogram) {
embedPhylogramRec(root, null, 0,new Counter(0));
if (getDrawerType() == DiagramType.RoundedPhylogram) {
for (Edge e = getTree().getFirstEdge(); e != null; e = getTree().getNextEdge(e))
getEV(e).setShape(EdgeView.ROUNDED_EDGE);
}
} else // getDrawerType().equals(DiagramType.RectangularCladogram
{
embedCladogramRec(root, getMaxDistanceFromNodeToAnyLeaf(root), new Counter(0));
if (getDrawerType() == DiagramType.RoundedCladogram) {
for (Edge e = getTree().getFirstEdge(); e != null; e = getTree().getNextEdge(e))
getEV(e).setShape(EdgeView.ROUNDED_EDGE);
}
}
trans.setCoordinateRect(getBBox()); // tell the transform that this has changed
if (!isShowIntermediateLabels())
showLabels(getDegree2Nodes(), false);
}
/**
* get all non-root nodes of degree 2
*
* @return all none-root nodes of degree 2
*/
public NodeSet getDegree2Nodes() {
NodeSet nodes = new NodeSet(getTree());
for (Node v = getTree().getFirstNode(); v != null; v = v.getNext())
if (v != getTree().getRoot() && v.getDegree() == 2)
nodes.add(v);
return nodes;
}
/**
* recursively does the work
*
* @param hLevel // 0: leaf, max-value: root
* @param leavesPlaced leaves placed
* @return bounding box of subtree
*/
private Rectangle embedCladogramRec(Node v,int hLevel,Counter leavesPlaced) {
Rectangle bbox = null;
for(var w:v.children()) {
Rectangle subBox = embedCladogramRec(w, hLevel-1,leavesPlaced);
if (bbox == null)
bbox = subBox;
else
bbox.add(subBox);
}
Point location;
if (bbox == null) // no dependent subtree, make new box
{
location = new Point(0, YSTEP * (int)leavesPlaced.getAndIncrement());
bbox = new Rectangle(location.x, location.y, HLEAFBOX, YSTEP);
setLocation(v, location);
} else {
location = new Point(- XSTEP*hLevel, bbox.y + (bbox.height - YSTEP) / 2);
bbox.add(location);
setLocation(v, location);
}
final float num;
final NodeData nodeData = super.getNodeData(v);
if (nodeDrawer.getScaleBy() == NodeDrawer.ScaleBy.Summarized || (nodeDrawer.getScaleBy() == NodeDrawer.ScaleBy.Assigned && v.getOutDegree() == 0))
num = (nodeData == null ? 0 : nodeData.getCountSummarized());
else if (nodeDrawer.getScaleBy() == NodeDrawer.ScaleBy.Assigned)
num = (nodeData == null ? 0 : nodeData.getCountAssigned());
else // nodeDrawer.getScaleBy() == MeganNodeDrawer.ScaleBy.None
num = 0;
if (num > 0) {
int radius = (int) Math.max(1.0, nodeDrawer.getScaledSize(num));
this.setHeight(v, 2 * radius);
this.setWidth(v, 2 * radius);
} else {
this.setWidth(v, 1);
this.setHeight(v, 1);
}
// add bends to edges:
for (Edge f = v.getFirstOutEdge(); f != null; f = v.getNextOutEdge(f)) {
Node w = f.getOpposite(v);
if (getLocation(w) != null && getLocation(v).getY() != getLocation(w).getY()) {
List<Point2D> list = new LinkedList<>();
list.add(new Point2D.Double(getLocation(v).getX(), getLocation(w).getY()));
setInternalPoints(f, list);
}
}
node2BoundingBox.put(v, (Rectangle) bbox.clone());
return bbox;
}
/**
* recursively does the work
*
* @return bbounding box of subtree
*/
private Rectangle embedPhylogramRec(Node v, Edge e, int level, Counter numberOfLeaves) {
Rectangle bbox = null;
for (Edge f = v.getFirstAdjacentEdge(); f != null; f = v.getNextAdjacentEdge(f)) {
if (f != e) {
Rectangle subBox = embedPhylogramRec(f.getOpposite(v), f, level + 1,numberOfLeaves);
if (bbox == null)
bbox = subBox;
else
bbox.add(subBox);
}
}
Point location;
if (bbox == null) // no dependent subtree, make new box
{
location = new Point(XSTEP * level, YSTEP * (int)numberOfLeaves.getAndIncrement());
bbox = new Rectangle(location.x, location.y, HLEAFBOX, YSTEP);
setLocation(v, location);
} else {
location = new Point(XSTEP * level, bbox.y + (bbox.height - YSTEP) / 2);
bbox.add(location);
setLocation(v, location);
}
final float num;
if (nodeDrawer.getScaleBy() == NodeDrawer.ScaleBy.Summarized || (nodeDrawer.getScaleBy() == NodeDrawer.ScaleBy.Assigned && v.getOutDegree() == 0))
num = (super.getNodeData(v)).getCountSummarized();
else if (nodeDrawer.getScaleBy() == NodeDrawer.ScaleBy.Assigned)
num = (super.getNodeData(v)).getCountAssigned();
else // nodeDrawer.getScaleBy() == MeganNodeDrawer.ScaleBy.None
num = 0;
if (num > 0) {
int radius = (int) Math.max(1.0, nodeDrawer.getScaledSize(num));
this.setHeight(v, 2 * radius);
this.setWidth(v, 2 * radius);
} else {
this.setWidth(v, 1);
this.setHeight(v, 1);
}
// add bends to edges:
for (Edge f = v.getFirstAdjacentEdge(); f != null; f = v.getNextAdjacentEdge(f)) {
if (f != e) {
Node w = f.getOpposite(v);
if (getLocation(w) != null && getLocation(v).getY() != getLocation(w).getY()) {
List<Point2D> list = new LinkedList<>();
list.add(new Point2D.Double(getLocation(v).getX(), getLocation(w).getY()));
setInternalPoints(f, list);
}
}
}
node2BoundingBox.put(v, (Rectangle) bbox.clone());
return bbox;
}
/**
* Paint.
*
* @param gc0 the Graphics
*/
public void paint(Graphics gc0) {
drawOnScreen = (!ExportManager.inWriteToFileOrGetData() && !inPrint);
final Graphics2D gc = (Graphics2D) gc0;
nodeDrawer.setup(this, gc);
setBackground(canvasColor);
gc.setColor(drawOnScreen ? canvasColor : Color.WHITE);
Rectangle totalRect;
Rectangle frameRect;
frameRect = new Rectangle(super.getScrollPane().getHorizontalScrollBar().getValue(),
super.getScrollPane().getVerticalScrollBar().getValue(),
super.getScrollPane().getHorizontalScrollBar().getVisibleAmount(),
super.getScrollPane().getVerticalScrollBar().getVisibleAmount());
if (drawOnScreen)
totalRect = frameRect;
else
totalRect = trans.getPreferredRect();
if (!inPrint)
gc.fill(totalRect);
if(isShowScaleBox()) {
DrawScaleBox.draw(gc, (int) Math.round(frameRect.getX() + 5), (int) Math.round(frameRect.getY() + 5), getDocument(), nodeDrawer);
}
gc.setColor(Color.BLACK);
gc.setFont(getFont());
BasicStroke stroke = new BasicStroke(1);
gc.setStroke(stroke);
if (drawOnScreen && trans.getMagnifier().isActive())
trans.getMagnifier().draw(gc);
try {
final List<Node> drawableNodeLabels = new LinkedList<>();
final Node root = getTree().getRoot();
if (root != null)
paintRec(gc, root, drawableNodeLabels, true);
// this is where we draw the node labels
drawNodeLabels(gc, drawableNodeLabels);
} catch (Exception ex) {
Basic.caught(ex);
}
if (getFoundNode() != null) {
if (getFoundNode().getOwner() == null || !getSelected(getFoundNode()))
setFoundNode(null);
else {
Node v = getFoundNode();
NodeView nv = getNV(v);
if (nv.getLabel() != null)
nv.setLabelSize(BasicSwing.getStringSize(gc, getLabel(v), getFont(v)));
gc.setColor(ProgramProperties.SELECTION_COLOR.brighter());
final Rectangle rect = nv.getBox(trans);
if (rect != null) {
rect.grow(2, 2);
gc.fill(rect);
}
final Shape shape = nv.getLabelShape(trans);
if (nv.isLabelVisible())
gc.fill(shape);
gc.setColor(ProgramProperties.SELECTION_COLOR_DARKER);
gc.draw(shape);
nodeDrawer.drawNodeAndLabel(v, false);
}
}
drawPoweredBy(gc, frameRect);
if (doScrollToRight) {
doScrollToRight = false;
JScrollBar sbar = super.getScrollPane().getHorizontalScrollBar();
sbar.setValue(sbar.getMaximum() - trans.getRightMargin() - 200);
super.getScrollPane().getViewport().setViewPosition(new Point(
sbar.getMaximum() - trans.getRightMargin() - 200,
super.getScrollPane().getVerticalScrollBar().getValue()));
}
if (mustDrawTwice) {
mustDrawTwice = false;
repaint();
}
}
/**
* draws the powered by logo
*
*/
protected void drawPoweredBy(Graphics2D gc, Rectangle rect) {
if (getPOWEREDBY() != null && getPOWEREDBY().length() > 2) {
gc.setColor(Color.gray);
gc.setStroke(new BasicStroke(1));
gc.setFont(poweredByFont);
int width = (int) BasicSwing.getStringSize(gc, getPOWEREDBY(), gc.getFont()).getWidth();
int x = rect.x + rect.width - width - 2;
int y = rect.y + rect.height - 2;
gc.drawString(getPOWEREDBY(), x, y);
}
}
/**
* recursively draw the tree
*
*/
private void paintRec(Graphics2D gc, Node v, List<Node> drawableNodeLabels, boolean enabled) {
Rectangle bbox = node2BoundingBox.get(v);
if (bbox == null)
bbox = new Rectangle();
//bbox.width += HLEAFBOX;
final Rectangle bboxDeviceCoordinates = new Rectangle();
trans.w2d(bbox, bboxDeviceCoordinates);
/*
{
gc.setColor(Color.GREEN);
gc.draw(bboxDeviceCoordinates);
Rectangle r = (Rectangle) getVisibleRect().clone();
r.x += 5;
r.width -= 10;
r.y += 5;
r.height -= 10;
gc.draw(r);
}
*/
if (drawOnScreen && !getVisibleRect().intersects(bboxDeviceCoordinates)) // && getTree().getDegree(v) > 1)
return; // nothing visible, return
final NodeView nv = getNV(v);
if (nv.getLabel() != null) {
nv.setLabelSize(gc); // ensure label rect is set
}
/*
if (getSelected(v)) {
gc.setColor(Color.BLUE);
gc.draw(bboxDeviceCoordinates);
}
*/
nv.setEnabled(enabled);
// if height of bbox is so small that we can't see the edges, just draw a gray box:
final boolean isSmall = v.getOutDegree() > 0 && (bboxDeviceCoordinates.getHeight() / (getTree().getDegree(v) - 1) < 4);
if (isSmall) {
if (1 != ((BasicStroke) gc.getStroke()).getLineWidth())
gc.setStroke(new BasicStroke(1));
gc.setColor(Color.DARK_GRAY);
gc.fill(bboxDeviceCoordinates);
} else // draw the edges in detail
{
// use edges back-to-front so that grey edges get drawn first!
for(var f:v.outEdges()) {
var w = v.getOpposite(f);
Point2D nextToV = getNV(w).getLocation();
Point2D nextToW = getNV(v).getLocation();
if (nextToV == null || nextToW == null)
continue;
if (getInternalPoints(f) != null) {
if (getInternalPoints(f).size() != 0) {
nextToV = getInternalPoints(f).get(0);
nextToW = getInternalPoints(f).get(getInternalPoints(f).size() - 1);
}
}
final Point pv = (!drawLeavesOnly || v.getOutDegree() == 0 ? getNV(v).computeConnectPoint(nextToV, trans) :
trans.w2d(getNV(v).getLocation()));
final Point pw = (!drawLeavesOnly || w.getOutDegree() == 0 ? getNV(w).computeConnectPoint(nextToW, trans) :
trans.w2d(getNV(w).getLocation()));
final EdgeView ev = getEV(f);
ev.setEnabled(enabled);
if (ev.getLineWidth() != ((BasicStroke) gc.getStroke()).getLineWidth()) {
gc.setStroke(new BasicStroke(ev.getLineWidth()));
}
//var edgeWidth=(nodeDrawer.getStyle()== NodeDrawer.Style.Circle?NodeView.computeScaledHeight(trans,nv.getWidth()):-1);
ev.draw(gc, pv, pw, trans, getSelected(f));
ev.setLabelReferenceLocation(nextToV, nextToW, trans);
if (ev.getLabel() != null && ev.isLabelVisible()) {
ev.setLabelReferenceLocation(pv, pw, trans);
ev.setLabelSize(gc);
ev.drawLabel(gc, trans, false);
if (getSelected(f))
ev.drawLabel(gc, trans, true);
}
paintRec(gc, w, drawableNodeLabels, enabled);
}
}
if (getNV(v).getLineWidth() != ((BasicStroke) gc.getStroke()).getLineWidth()) {
gc.setStroke(new BasicStroke(getNV(v).getLineWidth()));
}
if (!drawLeavesOnly || v.getOutDegree() == 0)
nodeDrawer.draw(v, selectedNodes.contains(v));
if (getLabel(v) != null && getLabel(v).length() > 0 && !isSmall)
drawableNodeLabels.add(v);
}
private double oldXScale = 0;
private double oldYScale = 0;
/**
* we first collect all node labels to be drawn and then draw them here.
*
*/
private void drawNodeLabels(Graphics2D gc, List<Node> drawableNodeLabels) {
// if (drawableNodeLabels.size() > 350)
// setAutoLayoutLabels(false);
// if (getAutoLayoutLabels())
{
boolean scaleHasChanged = (oldXScale != trans.getScaleX() || oldYScale != trans.getScaleY());
if (scaleHasChanged) { // centerAndScale has changed, allow new layout of all labels
oldXScale = trans.getScaleX();
oldYScale = trans.getScaleY();
for (Node v : drawableNodeLabels) {
if (v == getTree().getRoot())
setLabelLayout(v, ViewBase.WEST);
else if (v.getOutDegree() == 0) // leaf
{
setLabelLayout(v, ViewBase.EAST);
} else if (v.getInDegree() == 1 && v.getOutDegree() == 1) // internal path node
{
setLabelLayout(v, ViewBase.NORTH);
} else // internal node
{
setLabelLayout(v, ViewBase.NORTHWEST);
}
}
}
List<Pair<Node, Node>> pairs = new LinkedList<>();
for (Node v : drawableNodeLabels) {
if (getNV(v) == null || !getNV(v).isLabelVisible())
continue;
final Rectangle box = getNV(v).getLabelRect(trans);
if (box != null) {
/*
{
gc.setColor(Color.GREEN);
gc.draw(box);
}
*/
// find pairs of adjacent labels:
for (Node w : drawableNodeLabels) {
if (w == v)
break;
try {
if (getGraph().getOutDegree(v) > 0 || getGraph().getOutDegree(w) > 0) {
final Rectangle rect = getNV(w).getLabelRect(trans);
if (rect != null && box.intersects(rect))
pairs.add(new Pair<>(v, w));
}
} catch (Exception ex) {
// silently ignore...
}
}
}
}
final Random random = new Random(26660);
for (int run = 0; run < 20; run++) {
boolean changed = false;
for (Iterator it = IteratorUtils.randomize(pairs.iterator(), random); it.hasNext(); ) {
Pair pair = (Pair) it.next();
Node v = (Node) pair.getFirst();
Node w = (Node) pair.getSecond();
Rectangle rv = getNV(v).getLabelRect(trans);
Rectangle rw = getNV(w).getLabelRect(trans);
if (rv != null && rw != null && rv.intersects(rw)) {
Point pv = getNV(v).getLabelPosition(trans);
Point pw = getNV(w).getLabelPosition(trans);
if (pv == null || pw == null)
continue;
if (rv.x <= rw.x) {
pv.x -= Math.max(1, rv.height / 3);
pw.x += Math.max(1, rw.height / 3);
} else {
pv.x += Math.max(1, rv.height / 3);
pw.x -= Math.max(1, rw.height / 3);
}
if (rv.y <= rw.y) {
pv.y -= Math.max(1, rv.height / 3);
pw.y += Math.max(1, rw.height / 3);
} else {
pv.y += Math.max(1, rv.height / 3);
pw.y -= Math.max(1, rw.height / 3);
}
if (getGraph().getOutDegree(v) > 0) {
getNV(v).setLabelPosition(pv.x, pv.y, trans);
changed = true;
}
if (getGraph().getOutDegree(w) > 0) {
getNV(w).setLabelPosition(pw.x, pw.y, trans);
changed = true;
}
}
}
if (!changed)
break;
}
}
// draw all labels
for (Node v : drawableNodeLabels) {
nodeDrawer.drawLabel(v, getSelected(v));
}
}
/**
* uncollapse all selected nodes
*
* @param wholeSubtree if true, uncollapse the whole subtrees below any selected nodes
*/
public void uncollapseSelectedNodes(boolean wholeSubtree) {
final Set<Integer> ids = new HashSet<>();
for (Node v = getSelectedNodes().getFirstElement(); v != null; v = getSelectedNodes().getNextElement(v)) {
if (v.getOutDegree() == 0) {
Integer vid = (Integer) v.getInfo();
ids.add(vid);
if (!wholeSubtree) // collapse all dependant nodes
setSelected(v, false);
}
}
final Set<Integer> seen = new HashSet<>();
for (int id : ids) {
getCollapsedIds().remove(id);
Node vFull = classification.getFullTree().getANode(id);
if (!wholeSubtree) // collapse all dependent nodes
{
for (Edge eFull : vFull.outEdges()) {
Node wFull = eFull.getOpposite(vFull);
Integer wid = (Integer) wFull.getInfo();
getCollapsedIds().add(wid);
}
} else
uncollapseSelectedNodesRec(vFull, ids, seen);
}
updateTree();
}
/**
* recursively does the work
*/
private void uncollapseSelectedNodesRec(Node v, Set<Integer> ids, Set<Integer> seen) {
Integer id = (Integer) v.getInfo();
if (!seen.contains(id)) {
if (ids.contains(id))
seen.add(id);
if (id != null)
getCollapsedIds().remove(id);
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
uncollapseSelectedNodesRec(e.getOpposite(v), ids, seen);
}
}
}
/**
* completely uncollapse all nodes
*/
public void uncollapseAll() {
getCollapsedIds().clear();
updateTree();
/*
if(getClassName().equalsIgnoreCase("metacyc"))
for(Node node:getTree().nodes()) {
if(node.isLeaf()) {
System.err.println(getLabel(node)+"\t"+(node.getParent().getInfo()));
}
}`
*/
}
/**
* collapse all selected nodes
*/
public void collapseSelectedNodes() {
for (Node v = getSelectedNodes().getFirstElement(); v != null; v = getSelectedNodes().getNextElement(v)) {
getCollapsedIds().add((Integer) v.getInfo());
}
updateTree();
}
/**
* collapse all nodes at subsystem level
*/
public void collapseToTop() {
getCollapsedIds().clear();
if (getTree().getRoot() != null) {
for (Edge e = getTree().getRoot().getFirstOutEdge(); e != null; e = getTree().getRoot().getNextOutEdge(e)) {
getCollapsedIds().add((Integer) e.getTarget().getInfo());
}
updateTree();
}
}
/**
* setup the node labels
*
*/
public void setupNodeLabels(boolean resetLabelPositions) {
for (Node v = getTree().getFirstNode(); v != null; v = v.getNext()) {
if (getNumberSelectedNodes() == 0 || getSelected(v)) {
StringBuilder buf = new StringBuilder();
int fId = (Integer) v.getInfo();
if (isNodeLabelNames())
buf.append(classification.getName2IdMap().get(fId));
if (isNodeLabelIds()) {
if (buf.length() > 0)
buf.append(" ");
buf.append(fId);
}
NodeData nodeData = super.getNodeData(v);
if (isShowIntermediateLabels() || !(v.getInDegree() == 1 && v.getOutDegree() == 1)) {
if (isNodeLabelAssigned()) {
if (v.getOutDegree() > 0) {
if (nodeData.getAssigned().length == 1) {
if (buf.length() > 0)
buf.append("; ");
buf.append(Math.round(nodeData.getCountAssigned()));
} else if (nodeData.getAssigned().length > 1) {
if (buf.length() > 0)
buf.append("; ");
buf.append(StringUtils.toString(nodeData.getAssigned(), 0, nodeData.getAssigned().length, " ", true));
}
} else {
if (nodeData.getSummarized().length == 1) {
if (buf.length() > 0)
buf.append("; ");
buf.append(Math.round(nodeData.getCountSummarized()));
} else if (nodeData.getAssigned().length > 1) {
if (buf.length() > 0)
buf.append("; ");
buf.append(StringUtils.toString(nodeData.getSummarized(), 0, nodeData.getSummarized().length, " ", true));
}
}
if (buf.length() > 0 && !getLabelVisible(v))
setLabelVisible(v, true); // explicitly set, make visible
}
if (isNodeLabelSummarized() && (!isNodeLabelAssigned() || v.getOutDegree() > 0)) {
if (nodeData.getSummarized().length == 1) {
if (buf.length() > 0)
buf.append("; ");
buf.append(Math.round(nodeData.getCountSummarized()));
} else if (nodeData.getAssigned().length > 1) {
if (buf.length() > 0)
buf.append("; ");
buf.append(StringUtils.toString(nodeData.getSummarized(), 0, nodeData.getSummarized().length, " ", true));
}
if (buf.length() > 0 && !getLabelVisible(v))
setLabelVisible(v, true); // explicitly set, make visible
}
}
this.setLabel(v, buf.toString());
if (resetLabelPositions) {
if (v == getTree().getRoot())
setLabelLayout(v, ViewBase.WEST);
else if (v.getOutDegree() == 0) // leaf
{
setLabelLayout(v, ViewBase.EAST);
} else if (v.getInDegree() == 1 && v.getOutDegree() == 1) // internal path node
{
setLabelLayout(v, ViewBase.NORTH);
} else // internal node
{
setLabelLayout(v, ViewBase.NORTHWEST);
}
}
}
}
}
/**
* gets the number of datasets
*
* @return number of datasets
*/
public int getNumberOfDatasets() {
return doc.getNumberOfSamples();
}
/**
* select all nodes associated with the given f ids
*
*/
public void setSelectedIds(Collection<Integer> fIds, boolean state) {
NodeSet nodesToSelect = new NodeSet(getTree());
for (Node v = getTree().getFirstNode(); v != null; v = v.getNext()) {
if (fIds.contains(v.getInfo())) {
nodesToSelect.add(v);
}
}
setSelected(nodesToSelect, state);
}
public void setLocked(boolean locked) {
this.locked = locked;
}
/**
* set the tool tip to the given node
*
*/
public void setToolTipText(Node v) {
final StringWriter writer = new StringWriter();
writer.write("<html><i>");
final Integer id = (Integer) v.getInfo();
String text = id2toolTip.get(id);
if (text == null || text.length() == 0)
text = getLabel(v);
else
text = StringUtils.fold(text, 80, "<br>");
writer.write(text);
writer.write("</i><p>");
{
List<String> list = new ArrayList<>();
for (Node w : getNodes(id)) {
while (w.getInDegree() > 0) {
w = w.getFirstInEdge().getSource();
list.add(getLabel(w));
}
String str = StringUtils.toString(CollectionUtils.reverse(list), ";");
list.clear();
writer.write(str);
writer.write("<br>");
//System.err.println(str);
}
}
{
Integer level = id2rank.get(v.getInfo());
if (level != null) {
String name = TaxonomicLevels.getName(level);
if (name != null) {
writer.write("<i>(" + name + ")</i><p>");
}
}
}
NodeData data = (super.getNodeData(v));
if (data.getCountAssigned() > 0) {
writer.write("Assigned: ");
if (data.getAssigned().length < 50) {
boolean first = true;
for (float value : data.getAssigned()) {
if (first)
first = false;
else
writer.write(", ");
writer.write("<b>" + Math.round(value) + "</b>");
}
writer.write("<p>");
} else {
Statistics statistics = new Statistics(data.getAssigned());
writer.write(String.format("<b>%,.0f - %,.0f</b> (mean: %,.0f sd: %,.0f)", statistics.getMin(), statistics.getMax(), statistics.getMean(), statistics.getStdDev()));
}
writer.write("<p>");
}
if (data.getCountSummarized() > data.getCountAssigned()) {
writer.write("Summed: ");
if (data.getSummarized().length < 50) {
boolean first = true;
for (float value : data.getSummarized()) {
if (first)
first = false;
else
writer.write(", ");
writer.write("<b>" + Math.round(value) + "</b>");
}
writer.write("<p>");
} else {
Statistics statistics = new Statistics(data.getSummarized());
writer.write(String.format("<b>%,.0f - %,.0f</b> (mean: %,.0f sd: %,.0f)", statistics.getMin(), statistics.getMax(), statistics.getMean(), statistics.getStdDev()));
}
writer.write("<p>");
}
setToolTipText(writer.toString());
}
/**
* recursively print a summary
*
*/
@Override
public void listSummaryRec(NodeSet selectedNodes, Node v, int indent, Writer outs) throws IOException {
int id = (Integer) v.getInfo();
final String name = classification.getName2IdMap().get(id);
NodeData data = (super.getNodeData(v));
if ((selectedNodes == null || selectedNodes.contains(v))) {
if (data.getCountSummarized() > 0) {
for (int i = 0; i < indent; i++)
outs.write(" ");
outs.write(name + ": " + data.getCountSummarized() + "\n");
}
}
if (getCollapsedIds().contains(id)) {
return;
}
for (Edge f = v.getFirstOutEdge(); f != null; f = v.getNextOutEdge(f)) {
listSummaryRec(selectedNodes, f.getOpposite(v), indent + 2, outs);
}
}
public boolean isShowFindToolBar() {
return showFindToolBar;
}
public void setShowFindToolBar(boolean showFindToolBar) {
if (this.showFindToolBar && !showFindToolBar)
requestFocusInWindow();
this.showFindToolBar = showFindToolBar;
}
public SearchManager getSearchManager() {
return searchManager;
}
/**
* does this viewer currently have any URLs for selected nodes?
*
* @return true, if has URLs for selected nodes
*/
public boolean hasURLsForSelection() {
return false;
}
/**
* gets list of URLs associated with selected nodes
*
* @return URLs
*/
public List<String> getURLsForSelection() {
return new ArrayList<>();
}
public Classification getClassification() {
return classification;
}
public ViewerJTable getViewerJTable() {
return viewerJTable;
}
public ViewerJTree getViewerJTree() {
return viewerJTree;
}
public String getClassName() {
if (classification != null)
return getClassName(classification.getName());
else return "?";
}
public static String getClassName(String cName) {
return cName;
}
public void setMustDrawTwice() {
mustDrawTwice = true;
}
public List<Integer> computeDisplayedIdsInSearchOrder() {
final List<Integer> list = new ArrayList<>(getTree().getNumberOfNodes());
final Stack<Node> stack = new Stack<>();
stack.add(getTree().getRoot());
while (stack.size() > 0) {
final Node v = stack.pop();
Integer id = (Integer) v.getInfo();
list.add(id);
for (Edge e = v.getLastOutEdge(); e != null; e = v.getPrevOutEdge(e))
stack.push(e.getTarget());
}
return list;
}
public List<Integer> computeAllIdsInSearchOrder() {
final PhyloTree tree = new PhyloTree();
computeInduceTreeWithNoCollapsedNodes(tree, new HashMap<>());
final List<Integer> list = new ArrayList<>(tree.getNumberOfNodes());
final Stack<Node> stack = new Stack<>();
stack.add(tree.getRoot());
while (stack.size() > 0) {
final Node v = stack.pop();
list.add((Integer) v.getInfo());
for (Edge e = v.getLastOutEdge(); e != null; e = v.getPrevOutEdge(e))
stack.push(e.getTarget());
}
return list;
}
public void computeInduceTreeWithNoCollapsedNodes(PhyloTree tree, Map<Integer, Set<Node>> id2nodes) {
tree.clear();
classification.getFullTree().extractInducedTree(id2NodeData, new HashSet<>(), tree, id2nodes);
}
public int getTotalAssignedReads() {
return totalAssignedReads;
}
JSplitPane getMainSplitPane() {
return mainSplitPane;
}
StatusBar getStatusBar() {
return statusBar;
}
@Override
public boolean useHeatMapColors() {
return getNodeDrawer().getStyle() == NodeDrawer.Style.HeatMap;
}
public void selectNodesPositiveAssigned() {
for (Node o : getGraph().nodes()) {
final Node v = o;
if (!getSelected(v) && getNodeData(v).getCountAssigned() > 0) {
setSelected(v, true);
}
}
}
public boolean isShowScaleBox() {
return showScaleBox;
}
public void setShowScaleBox(boolean showScaleBox) {
this.showScaleBox = showScaleBox;
}
/**
* gets max distance from this node to any leaf
*
* @return depth
*/
private static int getMaxDistanceFromNodeToAnyLeaf(Node v) {
var max = v.outEdgesStream(true).mapToInt(e -> getMaxDistanceFromNodeToAnyLeaf(e.getTarget()) + 1).max();
if (max.isPresent())
return max.getAsInt();
else
return 0;
}
}
| 54,650 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
PropertiesWindow.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/PropertiesWindow.java | /*
* PropertiesWindow.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ProgramProperties;
import megan.core.Document;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
/**
* the document properties window
* 5.2005 Daniel Huson
*/
public class PropertiesWindow extends JDialog {
private final JEditorPane textArea = new JEditorPane("text/html", "");
public PropertiesWindow(JFrame parent, Document doc) {
super(parent, "Properties - " + doc.getTitle() + " - " + ProgramProperties.getProgramVersion());
setSize(420, 350);
setModal(true);
setup();
setContent(doc);
BasicSwing.centerDialogInParent(this, parent);
setVisible(true);
}
private void setContent(Document doc) {
StringBuilder buf = new StringBuilder();
buf.append("<font face=\"Arial\">");
if (doc.getMeganFile().getFileName() != null) {
buf.append("<b>File: </b>").append(doc.getMeganFile().getFileName()).append("<br>");
buf.append("<b>File type: </b>").append(doc.getMeganFile().getFileType()).append("<br>");
buf.append("<b>Number of reads:</b> ").append(doc.getNumberOfReads()).append("<br><p>");
try {
buf.append(doc.getDataTable().getHeaderPrettyPrint()).append("<p>");
} catch (IOException ignored) {
}
} else {
buf.append("<b>Content type:</b> NCBI taxonomy<br>");
}
buf.append("<b>Taxonomy:</b> ").append(TaxonomyData.getTree().getNumberOfNodes()).append(" nodes, ")
.append(TaxonomyData.getTree().getNumberOfEdges()).append(" edges<br>");
buf.append("<b>Induced taxonomy:</b> ").append(doc.getDir().getMainViewer().getTree().getNumberOfNodes())
.append(" nodes, ").append(doc.getDir().getMainViewer().getTree().getNumberOfEdges()).append(" edges<br>");
if (!doc.getMeganFile().hasDataConnector() && doc.getNumberOfReads() > 0) {
buf.append("<br> Note: This data was generated and saved as a summary<br>" +
"and so you cannot modify analysis parameters or inspect matches.<br>");
}
buf.append("<br>");
for (String key : Document.getVersionInfo().keySet()) {
buf.append("<b>").append(key).append(":</b> ");
buf.append(Document.getVersionInfo().get(key)).append("<br>");
}
buf.append("</font>");
textArea.setText(buf.toString());
}
private void setup() {
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
textArea.setEditable(false);
topPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BorderLayout());
JButton okButton = new JButton(getOkAction());
bottomPanel.add(okButton, BorderLayout.EAST);
getRootPane().setDefaultButton(okButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(topPanel, BorderLayout.CENTER);
getContentPane().add(bottomPanel, BorderLayout.SOUTH);
}
private AbstractAction okaction;
private AbstractAction getOkAction() {
final PropertiesWindow me = this;
AbstractAction action = okaction;
if (action != null)
return action;
action = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
me.setVisible(false);
me.dispose();
}
};
action.putValue(AbstractAction.NAME, "OK");
return okaction = action;
}
}
| 4,532 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ViewerBase.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/ViewerBase.java | /*
* ViewerBase.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import jloda.graph.*;
import jloda.phylo.PhyloTree;
import jloda.swing.commands.CommandManager;
import jloda.swing.find.SearchManager;
import jloda.swing.graphview.GraphView;
import jloda.swing.graphview.PhyloTreeView;
import jloda.swing.util.ProgramProperties;
import jloda.util.Pair;
import megan.core.Director;
import megan.core.Document;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.*;
/**
* contains methods used both by a number of different viewers
* Daniel Huson, 12.2009
*/
abstract public class ViewerBase extends PhyloTreeView {
private final Set<Integer> collapsedIds = new HashSet<>(); // hide all nodes below these
private boolean nodeLabelNames = true;
private boolean nodeLabelIds = false;
private boolean nodeLabelAssigned = false;
private boolean nodeLabelSummarized = false;
private boolean showIntermediateLabels = false;
boolean drawLeavesOnly = false;
String showLegend = "undefined"; // vertical or horizontal or none or undefined
final Director dir;
final Document doc;
private final Set<Integer> previousNodeIdsOfInterest = new HashSet<>();
private final Set<Integer> dirtyNodeIds = new HashSet<>();
private final Set<Pair<Integer, Integer>> dirtyEdgeIds = new HashSet<>();
final JPanel mainPanel;
final LegendPanel legendPanel;
private final JScrollPane legendScrollPane;
final JSplitPane splitPane;
protected CommandManager commandManager;
public enum DiagramType {RectangularCladogram, RectangularPhylogram, RoundedCladogram, RoundedPhylogram}
DiagramType drawerType;
final NodeDrawer nodeDrawer;
/*
* constructor
*
* @param tree
* @param doEmbedding
*/
public ViewerBase(Director dir, PhyloTree tree, boolean doEmbedding) {
super(tree, doEmbedding);
this.dir = dir;
this.doc = dir.getDocument();
this.setAllowMoveInternalEdgePoints(false);
this.setAllowMoveNodes(false);
this.setAllowMoveInternalEdgePoints(false);
this.setFixedNodeSize(true);
this.setAutoLayoutLabels(true);
this.setAllowEdit(false);
this.canvasColor = Color.WHITE;
nodeDrawer = new NodeDrawer(dir.getDocument(), this);
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
legendPanel = new LegendPanel(this);
legendPanel.setStyle(nodeDrawer.getStyle());
legendScrollPane = new JScrollPane(legendPanel);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, mainPanel, legendScrollPane);
splitPane.setOneTouchExpandable(true);
splitPane.setEnabled(true);
splitPane.setResizeWeight(1.0);
splitPane.setDividerLocation(1.0);
splitPane.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent componentEvent) {
legendPanel.updateView();
if (getShowLegend().equals("none") || getShowLegend().equals("undefined"))
splitPane.setDividerLocation(1.0);
}
});
this.commandManager = new CommandManager(dir, this, new String[]{"megan.commands"}, !ProgramProperties.isUseGUI());
try {
drawerType = DiagramType.valueOf(ProgramProperties.get("DrawerType" + getClassName(), DiagramType.RoundedCladogram.toString()));
} catch (Exception e) {
drawerType = DiagramType.RoundedCladogram;
}
}
/**
* determine the maximum number of reads assigned to any node
*
* @return max number
*/
double[] determineMaxCount() {
var useSummarized=(getNodeDrawer().getScaleBy()!= NodeDrawer.ScaleBy.Assigned);
// determine maximum count of reads on any given node:
double maxSingleCount = 1;
double maxTotalCount = 1;
for(var v:getTree().nodes()) {
NodeData data = (NodeData) v.getData();
int id = (Integer) v.getInfo();
if (data != null && (id > 0 || id < -3)) {
maxTotalCount = Math.max(maxTotalCount, v.getOutDegree() == 0 || useSummarized ? data.getCountSummarized() : data.getCountAssigned());
float[] array = (v.getOutDegree() == 0 || useSummarized? data.getSummarized() : data.getAssigned());
for (float a : array)
maxSingleCount = Math.max(maxSingleCount, a);
}
}
return new double[]{maxSingleCount, maxTotalCount};
}
/**
* gets the node data
*
*/
public NodeData getNodeData(Node v) {
return (NodeData) v.getData();
}
/**
* This method returns a list of currently selected nodes.
*
* @return list of nodes
*/
public Collection<Integer> getSelectedNodeIds() {
final Set<Integer> seen = new HashSet<>();
final ArrayList<Integer> result = new ArrayList<>(getSelectedNodes().size());
try {
for (Node v = getSelectedNodes().getFirstElement(); v != null; v = getSelectedNodes().getNextElement(v)) {
final Integer id = (Integer) v.getInfo();
if (!seen.contains(id)) {
seen.add(id);
result.add(id);
}
}
} catch (NotOwnerException ignored) {
}
return result;
}
public Set<Integer> getCollapsedIds() {
return collapsedIds;
}
public void setCollapsedIds(Set<Integer> collapsedIds) {
this.collapsedIds.clear();
this.collapsedIds.addAll(collapsedIds);
}
public Set<Node> getNodes(Integer id) {
Set<Node> result = new HashSet<>();
for (Node v = getGraph().getFirstNode(); v != null; v = v.getNext()) {
Integer vid = (Integer) v.getInfo();
if (vid != null && vid.equals(id))
result.add(v);
}
return result;
}
/**
* get ids of all given nodes
*
* @return ids
*/
Set<Integer> getAllIds(NodeSet nodes) {
Set<Integer> result = new HashSet<>();
for (Node v = nodes.getFirstElement(); v != null; v = nodes.getNextElement(v)) {
result.add((Integer) v.getInfo());
}
return result;
}
/**
* setup the key listeners
*/
void setupKeyListener() {
getFrame().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent keyEvent) {
if (!keyEvent.isAltDown() && !keyEvent.isMetaDown() && !keyEvent.isControlDown()) {
boolean shift = keyEvent.isShiftDown();
switch (keyEvent.getKeyCode()) {
case KeyEvent.VK_RIGHT -> {
JScrollBar bar = getScrollPane().getHorizontalScrollBar();
bar.setValue(bar.getValue() + (shift ? bar.getBlockIncrement(1) : bar.getUnitIncrement(1)));
}
case KeyEvent.VK_LEFT -> {
JScrollBar bar = getScrollPane().getHorizontalScrollBar();
bar.setValue(bar.getValue() - (shift ? bar.getBlockIncrement(1) : bar.getUnitIncrement(1)));
}
case KeyEvent.VK_DOWN -> {
JScrollBar bar = getScrollPane().getVerticalScrollBar();
bar.setValue(bar.getValue() + (shift ? bar.getBlockIncrement(1) : bar.getUnitIncrement(1)));
}
case KeyEvent.VK_UP -> {
JScrollBar bar = getScrollPane().getVerticalScrollBar();
bar.setValue(bar.getValue() - (shift ? bar.getBlockIncrement(1) : bar.getUnitIncrement(1)));
}
}
}
}
});
}
/**
* display full names?
*
* @return display full names?
*/
public boolean isNodeLabelNames() {
return nodeLabelNames;
}
/**
* display full names rather than ids?
*
*/
public void setNodeLabelNames(boolean nodeLabelNames) {
this.nodeLabelNames = nodeLabelNames;
}
/**
* set all node labels visible or invisible
*
*/
public void showNodeLabels(boolean show) {
for (Node v = getGraph().getFirstNode(); v != null; v = v.getNext()) {
setLabelVisible(v, show);
}
}
/**
* select all nodes below any of the currently selected nodes
*/
public void selectSubTreeNodes() {
NodeSet seeds = getSelectedNodes();
NodeSet selected = new NodeSet(getGraph());
for (Node v : seeds) {
if (!selected.contains(v))
selectSubTreeNodesRec(v, selected);
}
selected.removeAll(selectedNodes);
if (selected.size() > 0) {
selectedNodes.addAll(selected);
fireDoSelect(selected);
}
}
/**
* recursively does the work
*
*/
private void selectSubTreeNodesRec(final Node v, final NodeSet selected) {
selected.add(v);
for (Edge f : v.outEdges()) {
selectSubTreeNodesRec(f.getOpposite(v), selected);
}
}
/**
* select all leaves below any of the currently selected nodes
*/
public void selectLeavesBelow() {
NodeSet seeds = getSelectedNodes();
NodeSet visited = new NodeSet(getGraph());
NodeSet selected = new NodeSet(getGraph());
for (Node v : seeds) {
if (!visited.contains(v))
selectSubTreeLeavesRec(v, visited, selected);
}
NodeSet oldSelected = new NodeSet(getGraph());
for (Node v : seeds) {
if (v.getOutDegree() > 0) {
oldSelected.add(v);
selectedNodes.remove(v);
selected.remove(v);
}
}
if (oldSelected.size() > 0)
fireDoDeselect(oldSelected);
selected.removeAll(selectedNodes);
if (selected.size() > 0) {
selectedNodes.addAll(selected);
fireDoSelect(selected);
}
}
/**
* select all nodes above
*/
public void selectNodesAbove() {
NodeSet seeds = getSelectedNodes();
NodeSet selected = new NodeSet(getGraph());
for (Node v : seeds) {
Node w = v;
while (w != null && !selected.contains(w)) {
selected.add(w);
if (w.getInDegree() > 0)
w = w.getFirstInEdge().getSource();
}
}
selected.removeAll(seeds);
if (selected.size() > 0) {
selectedNodes.addAll(selected);
fireDoSelect(selected);
}
}
/**
* recursively does the work
*
*/
private void selectSubTreeLeavesRec(final Node v, final NodeSet visited, final NodeSet selected) {
visited.add(v);
if (v.getOutDegree() == 0)
selected.add(v);
else {
for (Edge f : v.outEdges()) {
selectSubTreeLeavesRec(f.getOpposite(v), visited, selected);
}
}
}
/**
* select all leaves
*/
public void selectAllLeaves() {
NodeSet selected = new NodeSet(getGraph());
for (Node v = getGraph().getFirstNode(); v != null; v = v.getNext()) {
if (v.getOutDegree() == 0 && !selectedNodes.contains(v) && !(v.getInfo() instanceof Integer && ((Integer) v.getInfo() < 0) && ((Integer) v.getInfo() >= -3)))
selected.add(v);
}
if (selected.size() > 0) {
selectedNodes.addAll(selected);
fireDoSelect(selected);
}
}
/**
* select all internal nodes
*/
public void selectAllInternal() {
NodeSet selected = new NodeSet(getGraph());
for (Node v = getGraph().getFirstNode(); v != null; v = v.getNext())
if (v.getOutDegree() > 0 && !selectedNodes.contains(v))
selected.add(v);
if (selected.size() > 0) {
selectedNodes.addAll(selected);
fireDoSelect(selected);
}
}
/**
* select all nodes below any of the currently selected nodes
*/
public void selectAllIntermediateNodes() {
NodeSet selected = new NodeSet(getGraph());
for (Node v = getGraph().getFirstNode(); v != null; v = v.getNext())
if (v.getInDegree() == 1 && v.getOutDegree() == 1 & !selectedNodes.contains(v))
selected.add(v);
if (selected.size() > 0) {
selectedNodes.addAll(selected);
fireDoSelect(selected);
}
}
/**
* show intermediate labels?
*
*/
public void setShowIntermediateLabels(boolean show) {
showIntermediateLabels = show;
showLabels(getDegree2Nodes(), show);
}
public boolean isShowIntermediateLabels() {
return showIntermediateLabels;
}
public int getMaxNodeRadius() {
return nodeDrawer.getMaxNodeHeight();
}
public void setMaxNodeRadius(int maxNodeRadius) {
nodeDrawer.setMaxNodeHeight(maxNodeRadius);
}
/**
* select nodes by labels
*
*/
public void selectNodesByLabels(Collection<String> labels, boolean state) {
boolean changed = false;
if (labels.size() > 0) {
for (Node v = getGraph().getFirstNode(); v != null; v = v.getNext()) {
if (getLabel(v) != null && getLabel(v).length() > 0) {
String label = getLabel(v);
if (labels.contains(label) && getSelected(v) != state) {
setSelected(v, state);
changed = true;
}
}
}
}
}
/**
* gets the set of selected node labels
*
* @return selected node labels
*/
public List<String> getSelectedNodeLabels(boolean inOrder) {
List<String> selectedLabels = new LinkedList<>();
if (inOrder) {
Node v = getTree().getRoot();
if (v != null) {
Stack<Node> stack = new Stack<>();
stack.add(v);
if (getSelected(v))
selectedLabels.add(getLabel(v));
while (stack.size() > 0) {
v = stack.pop();
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
Node w = e.getTarget();
if (getSelected(w))
selectedLabels.add(getLabel(w));
stack.add(w);
}
}
}
} else {
for (Node v = getSelectedNodes().getFirstElement(); v != null; v = getSelectedNodes().getNextElement(v))
if (getLabel(v) != null)
selectedLabels.add(getLabel(v));
}
return selectedLabels;
}
public boolean isNodeLabelIds() {
return nodeLabelIds;
}
public void setNodeLabelIds(boolean nodeLabelIds) {
this.nodeLabelIds = nodeLabelIds;
}
public boolean isNodeLabelAssigned() {
return nodeLabelAssigned;
}
public void setNodeLabelAssigned(boolean nodeLabelAssigned) {
this.nodeLabelAssigned = nodeLabelAssigned;
}
public boolean isNodeLabelSummarized() {
return nodeLabelSummarized;
}
public void setNodeLabelSummarized(boolean nodeLabelSummarized) {
this.nodeLabelSummarized = nodeLabelSummarized;
}
public PhyloTree getTree() {
return (PhyloTree) getGraph();
}
/**
* get all non-root nodes of degree 2
*
* @return all none-root nodes of degree 2
*/
NodeSet getDegree2Nodes() {
NodeSet nodes = new NodeSet(getTree());
for (Node v = getTree().getFirstNode(); v != null; v = v.getNext())
if (v.getInDegree() == 1 && v.getOutDegree() == 1)
nodes.add(v);
return nodes;
}
/**
* zoom to selected nodes
*/
public void zoomToSelection() {
Rectangle2D worldRect = null;
for (Node v : getSelectedNodes()) {
if (getLocation(v) != null) {
if (worldRect == null)
worldRect = new Rectangle2D.Double(getLocation(v).getX(), getLocation(v).getY(), 0, 0);
else
worldRect.add(getLocation(v));
}
}
if (worldRect != null) {
worldRect.setRect(worldRect.getX(), worldRect.getY(), Math.max(800, worldRect.getWidth()), Math.max(800, worldRect.getHeight()));
// if (getSelectedNodes().size() > 1)
// trans.fitToSize(worldRect, getScrollPane().getViewport().getExtentSize());
Rectangle deviceRect = new Rectangle();
trans.w2d(worldRect, deviceRect);
deviceRect.y -= 40;
deviceRect.height -= 40;
scrollRectToVisible(deviceRect);
}
}
public void scrollToNode(final Node v) {
final Runnable runnable = () -> {
final Rectangle rect = getNV(v).getLabelRect(trans);
if (rect != null) {
rect.x -= 25;
rect.y -= 25;
rect.width += 50;
rect.height += 50;
scrollRectToVisible(rect);
repaint();
}
};
if (SwingUtilities.isEventDispatchThread())
runnable.run();
else SwingUtilities.invokeLater(runnable);
}
public String getShowLegend() {
return showLegend;
}
/**
* show the legend horizontal, vertical or none
*
*/
public void setShowLegend(String showLegend) {
this.showLegend = showLegend;
if (showLegend.equalsIgnoreCase("horizontal")) {
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
Dimension size = new Dimension();
splitPane.validate();
legendPanel.setSize(splitPane.getWidth(), 50);
legendPanel.draw((Graphics2D) legendPanel.getGraphics(), size);
int height = (int) size.getHeight() + 10;
legendPanel.setPreferredSize(new Dimension(splitPane.getWidth(), height));
legendPanel.validate();
splitPane.setDividerLocation(splitPane.getSize().height - splitPane.getInsets().right - splitPane.getDividerSize() - height);
} else if (showLegend.equalsIgnoreCase("vertical")) {
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
Dimension size = new Dimension();
splitPane.validate();
legendPanel.setSize(20, splitPane.getHeight());
legendPanel.draw((Graphics2D) legendPanel.getGraphics(), size);
int width = (int) size.getWidth() + 5;
legendPanel.setPreferredSize(new Dimension(width, splitPane.getHeight()));
legendPanel.validate();
splitPane.setDividerLocation(splitPane.getSize().width - splitPane.getInsets().right - splitPane.getDividerSize() - width);
} else {
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
splitPane.setDividerLocation(1.0);
}
}
public boolean isDrawLeavesOnly() {
return drawLeavesOnly;
}
public void setDrawLeavesOnly(boolean drawLeavesOnly) {
this.drawLeavesOnly = drawLeavesOnly;
}
/**
* overide GraphView.centerGraph because we don't what to center graph on resize
*/
public void centerGraph() {
}
/**
* override GraphView.fitGraphToWindow
*/
public void fitGraphToWindow() {
Dimension size = getScrollPane().getSize();
trans.fitToSize(new Dimension(size.width, size.height));
}
/**
* gets the current graphview
*
* @return graphview
*/
public GraphView getGraphView() {
return this;
}
/**
* get set of ids of all nodes whose format have been changed
*
* @return ids of dirty nodes
*/
public Set<Integer> getDirtyNodeIds() {
return dirtyNodeIds;
}
/**
* get set of ids of all dirty edges
*
* @return dirty edges
*/
public Set<Pair<Integer, Integer>> getDirtyEdgeIds() {
return dirtyEdgeIds;
}
abstract public JFrame getFrame();
/**
* recursively print a summary
*
*/
public void listSummaryRec(NodeSet selectedNodes, Node v, int indent, Writer outs) throws IOException {
System.err.println("Not implemented");
}
Set<Integer> getPreviousNodeIdsOfInterest() {
return previousNodeIdsOfInterest;
}
public void setPreviousNodeIdsOfInterest(Collection<Integer> previousNodeIdsOfInterest) {
this.previousNodeIdsOfInterest.clear();
if (previousNodeIdsOfInterest != null)
this.previousNodeIdsOfInterest.addAll(previousNodeIdsOfInterest);
}
abstract public boolean isShowFindToolBar();
abstract public void setShowFindToolBar(boolean showFindToolBar);
abstract public SearchManager getSearchManager();
public DiagramType getDrawerType() {
return drawerType;
}
public void setDrawerType(String drawerName) {
for (DiagramType aType : DiagramType.values()) {
if (drawerName.equalsIgnoreCase(aType.toString())) {
drawerType = aType;
break;
}
}
ProgramProperties.put("DrawerType" + getClassName(), drawerName);
}
public void updateTree() {
}
public NodeDrawer getNodeDrawer() {
return nodeDrawer;
}
public Director getDir() {
return dir;
}
public Document getDocument() {
return doc;
}
public LegendPanel getLegendPanel() {
return legendPanel;
}
public JScrollPane getLegendScrollPane() {
return legendScrollPane;
}
/**
* are there any reads on the selected (or all) nodes?
*
* @return true, if nodes with reads are selected
*/
public boolean hasComparableData() {
if (doc.getNumberOfSamples() >= 2) {
for (Node v = getGraph().getFirstNode(); v != null; v = v.getNext()) {
if (getSelected(v) || getSelectedNodes().size() == 0) {
NodeData data = (getNodeData(v));
if (data.getCountSummarized() > 0)
return true;
}
}
}
return false;
}
public void setupNodeLabels(boolean b) {
}
public CommandManager getCommandManager() {
return commandManager;
}
public JPanel getMainPanel() {
return mainPanel;
}
public String getClassName() {
return "ViewerBase";
}
}
| 23,992 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LegendPanel.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/LegendPanel.java | /*
* LegendPanel.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import jloda.swing.util.BasicSwing;
import megan.core.Document;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* panel for drawing legend into
* Daniel Huson, 2.2013
*/
public class LegendPanel extends JPanel {
private final ViewerBase viewer;
private final Document doc;
private Font font = Font.decode("Helvetica-NORMAL-11");
private Color fontColor = Color.BLACK;
private NodeDrawer.Style style = NodeDrawer.Style.Circle;
private JPopupMenu popupMenu = null;
/**
* constructor
*
*/
public LegendPanel(ViewerBase viewer) {
this.viewer = viewer;
doc = viewer.getDocument();
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent mouseEvent) {
if (mouseEvent.isPopupTrigger() && popupMenu != null)
popupMenu.show(LegendPanel.this, mouseEvent.getX(), mouseEvent.getY());
}
public void mouseReleased(MouseEvent mouseEvent) {
if (mouseEvent.isPopupTrigger() && popupMenu != null)
popupMenu.show(LegendPanel.this, mouseEvent.getX(), mouseEvent.getY());
}
});
}
public void setPopupMenu(JPopupMenu popupMenu) {
this.popupMenu = popupMenu;
}
/**
* draw the legend
*
*/
public void paint(Graphics graphics) {
super.paint(graphics);
Graphics2D gc = (Graphics2D) graphics;
gc.setColor(Color.WHITE);
gc.fill(getVisibleRect());
draw(gc, null);
}
/**
* rescan the view
*/
public void updateView() {
Graphics2D graphics = (Graphics2D) getGraphics();
Dimension size = new Dimension();
draw(graphics, size);
//setPreferredSize(new Dimension(getPreferredSize().width,size.height));
setPreferredSize(size);
revalidate();
}
/**
* draw a legend for dataset colors
*
*/
void draw(Graphics2D gc, Dimension size) {
if (gc != null && doc.getNumberOfSamples() > 1) {
boolean vertical = viewer.getShowLegend().equals("vertical");
if (getFont() != null)
gc.setFont(getFont());
boolean doDraw = (size == null);
int yStart = 20;
int x = 3;
int maxX = x;
if (doDraw) {
String legend = "Legend:";
gc.setColor(Color.BLACK);
gc.drawString(legend, x, yStart);
Dimension labelSize = BasicSwing.getStringSize(gc, legend, gc.getFont()).getSize();
maxX = Math.max(maxX, labelSize.width);
}
int y = yStart + (int) (1.5 * gc.getFont().getSize());
int count = 1;
for (String sampleName : doc.getSampleNames()) {
String label = doc.getSampleLabelGetter().getLabel(sampleName);
if (!label.equals(sampleName))
label += " (" + sampleName + ")";
if (style == NodeDrawer.Style.HeatMap) {
label = count + ": " + label;
}
final Dimension labelSize = BasicSwing.getStringSize(gc, label, gc.getFont()).getSize();
int boxSize = 0;
if (style != NodeDrawer.Style.HeatMap)
boxSize = labelSize.height - 2;
if (x + 12 + labelSize.width + 2 > getWidth() || vertical) {
x = 3;
y += 1.5 * gc.getFont().getSize();
}
if (doDraw) {
switch (style) {
case PieChart, BarChart, CoxComb -> {
Color color = doc.getSampleAttributeTable().getSampleColor(sampleName);
if (color == null)
color = doc.getChartColorManager().getSampleColor(sampleName);
gc.setColor(color);
gc.fillRect(x, y - boxSize, boxSize, boxSize);
gc.setColor(color.darker());
gc.drawRect(x, y - boxSize, boxSize, boxSize);
}
case Circle -> {
gc.setColor(Color.DARK_GRAY);
gc.drawRect(x, y - boxSize, boxSize, boxSize);
}
case HeatMap -> {
}
}
gc.setColor(getFontColor());
gc.drawString(label, x + boxSize + 2, y);
}
x += boxSize + 2 + labelSize.width + 10;
maxX = Math.max(maxX, x);
if (vertical)
maxX = Math.max(maxX, x);
count++;
}
if (size != null)
size.setSize(maxX, y);
}
}
public void setFont(Font font) {
this.font = font;
}
public Font getFont() {
return font;
}
public void setFontColor(Color fontColor) {
this.fontColor = fontColor;
}
private Color getFontColor() {
return fontColor;
}
public NodeDrawer.Style getStyle() {
return style;
}
public void setStyle(NodeDrawer.Style style) {
this.style = style;
}
}
| 6,236 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
GUIConfiguration.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/GUIConfiguration.java | /*
* GUIConfiguration.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import jloda.swing.util.ProgramProperties;
import jloda.swing.window.MenuConfiguration;
import megan.classification.data.ClassificationCommandHelper;
/**
* configuration for menu and toolbar
* Daniel Huson, 7.2010
*/
public class GUIConfiguration {
/**
* get the menu configuration
*
* @return menu configuration
*/
public static MenuConfiguration getMenuConfiguration() {
MenuConfiguration menuConfig = new MenuConfiguration();
menuConfig.defineMenuBar("File;Edit;Select;Options;Layout;Tree;Window;Help;");
menuConfig.defineMenu("File", "New...;|;Open...;@Open Recent;|;Open From Server...;|;Compare...;|;Import From BLAST...;@Import;Meganize DAA File...;|;Save As...;|;"
+ "Export Image...;Export Legend...;@Export;|;Page Setup...;Print...;|;Extract To New Document...;Extract Reads...;|;Reanalyze Files...;|;Properties...;|;Close;|;Quit;");
menuConfig.defineMenu("Server", "Set Server Credentials...;|;Add User...;Add Metadata...;");
menuConfig.defineMenu("Open Recent", ";");
menuConfig.defineMenu("Export", "Text (CSV) Format...;BIOM1 Format...;STAMP Format...;|;Metadata...;|;Tree...;|;"+
ProgramProperties.getIfEnabled("enable-taxon-parent-mapping","Taxon-Parent Mapping...;|;")+
"Annotations in GFF Format...;Export Read Lengths and Coverage...;Export Frame-Shift Corrected Reads...;"
+ "Export Segmentation of Reads...;|;Reads...;Matches...;Alignments...;Overlap Graph...;Gene-Centric Assembly...;|;All Individual Samples...;MEGAN Summary File...;");
menuConfig.defineMenu("Import", "Import Text (CSV) Format...;Import BIOM Format...;|;Import Metadata...;");
menuConfig.defineMenu("Edit", "Cut;Copy;Copy Image;Copy Legend;Paste;|;Edit Node Label;Edit Edge Label;Description...;|;Format...;|;Find...;Find Again;|;Colors...;|;@Preferences;");
menuConfig.defineMenu("Preferences", "Show Notifications;|;@Accession Parsing;@Taxon Disabling;|;Add Classification...;|;Use Alternative Taxonomy...;Use Default NCBI Taxonomy;|;Set Search URL...;Enable Software Feature...;");
menuConfig.defineMenu("Accession Parsing", "First Word Is Accession;Set Accession Tags;");
menuConfig.defineMenu("Taxon Disabling", "List Disabled...;|;Disable...;Enable...;|;Enable All;Disable Default;");
menuConfig.defineMenu("Select", "All Nodes;None;|;From Previous Window;|;All Leaves;All Internal Nodes;Subtree;Leaves Below;Nodes Above;Has Assigned;|;Invert;|;Select By Rank;|;Scroll To Selected;");
menuConfig.defineMenu("Layout", "Show Legend;|;Increase Font Size;Decrease Font Size;|;@Expand/Contract;|;Layout Labels;|;Show Scale Bar;|;Scale Nodes By Assigned;Scale Nodes By Summarized;"
+ "Set Max Node Height...;|;Zoom To Selection;|;Fully Contract;Fully Expand;|;"
+ "Draw Circles;Draw Pies;Draw Coxcombs;Draw Bars;Draw Heatmaps;|;Linear Scale;Sqrt Scale;Log Scale;|;Rounded Cladogram;Cladogram;Rounded Phylogram;Phylogram;|;Use Magnifier;|;Draw Leaves Only;");
menuConfig.defineMenu("Expand/Contract", "Expand Horizontal;Contract Horizontal;Expand Vertical;Contract Vertical;");
menuConfig.defineMenu("Options", "Change LCA Parameters...;Set Number Of Reads...;|;Project Assignments To Rank...;|;List Summary...;List Paths...;|;" +
"Compute Core Biome...;|;Shannon-Weaver Index...;Simpson-Reciprocal Index...;|;" + ProgramProperties.getIfEnabled("enable-decontam", "Decontam...;|;") + "Open NCBI Web Page...;Inspect...;Inspect Long Reads...;");
menuConfig.defineMenu("Tree", "Collapse;Collapse To Top;Collapse All Others;Collapse at Level...;Rank...;|;" +
"Uncollapse;Uncollapse Subtree;Uncollapse All;|;Keep Non-Prokaryotes Collapsed;Keep Non-Eukaryotes Collapsed;Keep Non-Viruses Collapsed;|;Show Names;Show IDs;Show Number of Assigned;" +
"Show Number of Summarized;|;Node Labels On;Node Labels Off;|;Show Intermediate Labels;");
menuConfig.defineMenu("Window", "Close All Other Windows...;Show Info...;|;Reset Window Location;Set Window Size...;|;Message Window...;|;" +
"Inspector Window...;Show Alignment...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;Groups Viewer...;" +
"|;Chart...;|;Chart Microbial Attributes...;|;Cluster Analysis...;|;Rarefaction Analysis...;|;");
menuConfig.defineMenu("Help", "About...;How to Cite...;|;Community Website...;Reference Manual...;|;Check For Updates...;");
return menuConfig;
}
/**
* gets the toolbar configuration
*
* @return toolbar configuration
*/
public static String getToolBarConfiguration() {
return "Open...;Print...;Export Image...;|;Find...;|;" +
"Expand Vertical;Contract Vertical;Expand Horizontal;Contract Horizontal;|;Fully Contract;Fully Expand;Scroll To Selected;|;Rounded Cladogram;Cladogram;Rounded Phylogram;Phylogram;|;" +
"Colors...;|;" +
"Collapse;Collapse To Top;Uncollapse;Uncollapse Subtree;Rank...;|;Draw Circles;Draw Pies;Draw Coxcombs;Draw Bars;Draw Heatmaps;|;Linear Scale;Sqrt Scale;Log Scale;|;" +
"Chart...;|;Inspect...;Show Alignment...;Extract Reads...;Rarefaction Analysis...;|;" +
"Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Cluster Analysis...;Samples Viewer...;|;Show Legend;|;";
}
/**
* get the configuration of the node popup menu
*
* @return config
*/
public static String getNodePopupConfiguration() {
return "Inspect...;Inspect Long Reads...;|;Show Alignment...;Extract Reads...;Gene-Centric Assembly...;Correlate To Attributes...;|;Edit Node Label;Copy Node Label;|;Collapse;|;Uncollapse;Uncollapse Subtree;|;" +
"Node Labels On;Node Labels Off;|;" + ProgramProperties.getIfEnabled("enable-show-read-length-distribution", "Show Read Length Distribution...;") + "|;Open Web Page...;Web Search...;";
}
public static String getJTreePopupConfiguration() {
return "Inspect...;Inspect Long Reads...;|;Show Alignment...;Extract Reads...;Gene-Centric Assembly...;|;Copy Node Label;|;Open Web Page...;Web Search...;";
}
public static String getJTablePopupConfiguration() {
return "Inspect...;Inspect Long Reads...;|;Show Alignment...;Extract Reads...;Gene-Centric Assembly...;|;Copy Node Label;|;Open Web Page...;Web Search...;";
}
/**
* get the configuration of the edge popup menu
*
* @return config
*/
public static String getEdgePopupConfiguration() {
return "Edit Edge Label;Copy Edge Label;";
}
/**
* gets the canvas popup configuration
*
* @return config
*/
public static String getPanelPopupConfiguration() {
return "Fully Contract;Fully Expand;|;Rounded Cladogram;Cladogram;Rounded Phylogram;Phylogram;|;Copy Image;Export Image...;";
}
public static String getSeriesListPopupConfiguration() {
return "";
}
}
| 7,995 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClassificationViewerSearcher.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/ClassificationViewerSearcher.java | /*
* ClassificationViewerSearcher.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.graph.NodeSet;
import jloda.phylo.PhyloTree;
import jloda.swing.find.IObjectSearcher;
import jloda.swing.util.ProgramProperties;
import megan.classification.ClassificationManager;
import megan.core.Director;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.*;
/**
* Class for finding and replacing node labels in an fViewer
* Daniel Huson, 10.2015
*/
public class ClassificationViewerSearcher implements IObjectSearcher {
private final String name;
private final PhyloTree graph;
private final ClassificationViewer classificationViewer;
private final Frame frame;
private Iterator<Integer> currentIterator = null;
private Integer currentId = -1;
private final Set<Integer> toSelectIds = new HashSet<>();
private final Set<Integer> toDeSelectIds = new HashSet<>();
private int numberOfObjects = 0;
private final NodeSet toSelect;
private final NodeSet toDeselect;
private boolean searchInCollapsed;
private int countCurrent = 0; // use this to cycle throug different instances of current node id
private final AbstractButton uncollapseButton;
/**
* constructor
*
* @param
*/
public ClassificationViewerSearcher(Frame frame, String name, ClassificationViewer viewer) {
this.frame = frame;
this.name = name;
this.classificationViewer = viewer;
this.graph = viewer.getTree();
toSelect = new NodeSet(graph);
toDeselect = new NodeSet(graph);
searchInCollapsed = ProgramProperties.get("FViewerSearchInCollapsed", false);
uncollapseButton = new JCheckBox();
uncollapseButton.setAction(new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
searchInCollapsed = uncollapseButton.isSelected();
currentId = null;
currentIterator = null;
ProgramProperties.put("FViewerSearchInCollapsed", searchInCollapsed);
}
});
uncollapseButton.setToolTipText("Search in collapsed nodes as well");
uncollapseButton.setText("Uncollapse");
uncollapseButton.setSelected(searchInCollapsed);
}
/**
* get the parent component
*
* @return parent
*/
public Component getParent() {
return frame;
}
/**
* get the name for this type of search
*
* @return name
*/
public String getName() {
return name;
}
/**
* goto the first object
*/
public boolean gotoFirst() {
countCurrent = 0;
if (!searchInCollapsed) {
final List<Integer> list = classificationViewer.computeDisplayedIdsInSearchOrder();
currentIterator = list.iterator();
numberOfObjects = list.size();
} else {
final List<Integer> list = classificationViewer.computeAllIdsInSearchOrder();
currentIterator = list.iterator();
numberOfObjects = list.size();
}
currentId = (currentIterator.hasNext() ? currentIterator.next() : null);
return isCurrentSet();
}
/**
* goto the next object
*/
public boolean gotoNext() {
if (currentIterator == null) {
gotoFirst();
} else if (currentIterator.hasNext())
currentId = currentIterator.next();
else {
currentIterator = null;
currentId = null;
}
return isCurrentSet();
}
/**
* goto the last object
* Not implemented
*/
public boolean gotoLast() {
currentIterator = null;
currentId = null;
return isCurrentSet();
}
/**
* goto the previous object
*/
public boolean gotoPrevious() {
currentIterator = null;
currentId = null;
return isCurrentSet();
}
/**
* is the current object selected?
*
* @return true, if selected
*/
public boolean isCurrentSelected() {
return isCurrentSet() && toSelectIds.contains(currentId);
}
/**
* set selection state of current object
*
*/
public void setCurrentSelected(boolean select) {
if (currentId != null) {
if (select)
toSelectIds.add(currentId);
else
toDeSelectIds.add(currentId);
}
if (currentId != null && select) {
Set<Node> set = classificationViewer.getNodes(currentId);
if (set.size() > 1 && countCurrent < set.size()) {
final Node[] nodes = classificationViewer.getNodes(currentId).toArray(new Node[set.size()]);
classificationViewer.setFoundNode(nodes[countCurrent++]);
} else
classificationViewer.setFoundNode(classificationViewer.getANode(currentId));
} else
classificationViewer.setFoundNode(null);
}
/**
* set select state of all objects
*
*/
public void selectAll(boolean select) {
classificationViewer.selectAllNodes(select);
classificationViewer.repaint();
}
/**
* get the label of the current object
*
* @return label
*/
public String getCurrentLabel() {
if (currentId == null)
return null;
final Node v = classificationViewer.getANode(currentId);
if (v != null)
return classificationViewer.getNV(v).getLabel();
else
return ClassificationManager.get(name, true).getName2IdMap().get(currentId);
}
/**
* set the label of the current object
*
*/
public void setCurrentLabel(String newLabel) {
// not implemented
}
/**
* is a global find possible?
*
* @return true, if there is at least one object
*/
public boolean isGlobalFindable() {
return true;
}
/**
* is a selection find possible
*
* @return true, if at least one object is selected
*/
public boolean isSelectionFindable() {
return classificationViewer.getSelectedNodes().size() > 0;
}
/**
* is the current object set?
*
* @return true, if set
*/
public boolean isCurrentSet() {
return currentIterator != null && currentId != null;
}
/**
* something has been changed or selected, rescan view
*/
public void updateView() {
Set<Integer> needToBeUncollapsed = new HashSet<>();
for (Integer id : toSelectIds) {
if (classificationViewer.getANode(id) == null) {
needToBeUncollapsed.add(id);
}
}
if (needToBeUncollapsed.size() > 0) {
Set<Integer> toDelete = new HashSet<>();
for (int t : needToBeUncollapsed) {
for (Node v : ClassificationManager.get(name, true).getFullTree().getNodes(t)) {
while (v.getInDegree() > 0) {
v = v.getFirstInEdge().getSource();
int vt = (Integer) v.getInfo();
toDelete.add(vt);
}
}
}
needToBeUncollapsed.removeAll(toDelete); // is above something that needs to be uncollapsed
// uncollapse all nodes that we want to see
for (int t : needToBeUncollapsed) {
for (Node v : ClassificationManager.get(name, true).getFullTree().getNodes(t)) {
while (v.getInDegree() > 0) {
Node w = v.getFirstInEdge().getSource();
int wt = (Integer) v.getInfo();
if (classificationViewer.getCollapsedIds().contains(wt)) {
classificationViewer.getCollapsedIds().remove(wt);
break;
}
for (Edge e = w.getFirstOutEdge(); e != null; e = w.getNextOutEdge(e)) {
Node u = e.getTarget();
if (u != v) {
classificationViewer.getCollapsedIds().add((Integer) u.getInfo());
}
}
v = w;
}
}
}
classificationViewer.updateTree();
classificationViewer.updateView(Director.ALL);
}
toSelect.clear();
for (int t : toSelectIds) {
final Set<Node> nodes = classificationViewer.getNodes(t);
if (nodes != null) {
toSelect.addAll(nodes);
}
}
toDeselect.clear();
for (int t : toDeSelectIds) {
final Set<Node> nodes = classificationViewer.getNodes(t);
if (nodes != null) {
toDeselect.addAll(nodes);
}
}
classificationViewer.selectedNodes.addAll(toSelect);
classificationViewer.fireDoSelect(toSelect);
Node v = classificationViewer.getFoundNode();
if (v == null)
v = toSelect.getLastElement();
if (v != null) {
try {
final Point p = classificationViewer.trans.w2d(classificationViewer.getLocation(v));
classificationViewer.scrollRectToVisible(new Rectangle(p.x - 60, p.y - 25, 500, 100));
} catch (Exception ex) {// happens occasionally
}
}
classificationViewer.selectedNodes.removeAll(toDeselect);
classificationViewer.fireDoDeselect(toDeselect);
toSelect.clear();
toDeselect.clear();
classificationViewer.repaint();
toSelectIds.clear();
toDeSelectIds.clear();
classificationViewer.repaint();
}
/**
* does this searcher support find all?
*
* @return true, if find all supported
*/
public boolean canFindAll() {
return true;
}
/**
* how many objects are there?
*
* @return number of objects or -1
*/
public int numberOfObjects() {
return numberOfObjects;
}
@Override
public Collection<AbstractButton> getAdditionalButtons() {
return Collections.singletonList(uncollapseButton);
}
}
| 11,219 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MainViewer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/MainViewer.java | /*
* MainViewer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import jloda.graph.Node;
import jloda.seq.BlastMode;
import jloda.swing.commands.CommandManager;
import jloda.swing.director.*;
import jloda.swing.util.ListTransferHandler;
import jloda.swing.util.PopupMenu;
import jloda.swing.util.ProgramProperties;
import jloda.util.Basic;
import jloda.util.CanceledException;
import jloda.util.FileUtils;
import megan.chart.ChartColorManager;
import megan.chart.gui.LabelsJList;
import megan.chart.gui.SyncListener;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.commands.CloseCommand;
import megan.commands.SaveCommand;
import megan.core.DataTable;
import megan.core.Director;
import megan.core.SelectionSet;
import megan.dialogs.compare.Comparer;
import megan.main.MeganProperties;
import megan.viewer.gui.NodeDrawer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* the main viewer
* Daniel Huson, 11.05
*/
public class MainViewer extends ClassificationViewer implements IDirectableViewer, IViewerWithFindToolBar, IViewerWithLegend, IMainViewer {
private static MainViewer lastActiveViewer = null;
private static JFrame lastActiveFrame = null;
private final LabelsJList seriesList;
private final SelectionSet selectedSeries;
/**
* constructor
*
*/
public MainViewer(final Director dir, boolean visible) {
super(dir, ClassificationManager.get(Classification.Taxonomy, false), visible);
//getMainSplitPane().getLeftComponent().setMinimumSize(new Dimension());
//getMainSplitPane().setDividerLocation(0.0d);
selectedSeries = doc.getSampleSelection();
if (!dir.isInternalDocument()) {
MeganProperties.notifyListChange(MeganProperties.RECENTFILES);
}
ProgramProperties.checkState();
SyncListener syncListener1 = enabledNames -> { // rescan enable state
if (doc.getDataTable().setEnabledSamples(enabledNames)) {
dir.execute("update reInduce=true;", commandManager);
}
};
seriesList = new LabelsJList(this, syncListener1, new PopupMenu(this, megan.viewer.GUIConfiguration.getSeriesListPopupConfiguration(), commandManager));
seriesList.addListSelectionListener(listSelectionEvent -> {
if (!seriesList.inSelection) {
seriesList.inSelection = true;
try {
// select series in window
Set<String> selected = new HashSet<>(seriesList.getSelectedLabels());
selectedSeries.clear();
selectedSeries.setSelected(selected, true);
} finally {
seriesList.inSelection = false;
}
}
});
seriesList.setDragEnabled(true);
seriesList.setTransferHandler(new ListTransferHandler());
selectedSeries.addSampleSelectionListener((labels, selected) -> {
if (!seriesList.inSelection) {
seriesList.inSelection = true;
try {
DefaultListModel model = (DefaultListModel) seriesList.getModel();
for (int i = 0; i < model.getSize(); i++) {
String name = seriesList.getModel().getElementAt(i);
if (selectedSeries.isSelected(name))
seriesList.addSelectionInterval(i, i + 1);
else
seriesList.removeSelectionInterval(i, i + 1);
}
} finally {
seriesList.inSelection = false;
}
}
});
getFrame().addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (dir.getDocument().getProgressListener() != null)
dir.getDocument().getProgressListener().setUserCancelled(true);
commandManager.getCommand(CloseCommand.NAME).actionPerformed(null);
}
});
getFrame().setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
collapseToDefault();
}
/**
* update view
*
* @param what what should be updated? Possible values: Director.ALL or Director.TITLE
*/
public void updateView(String what) {
if (getClassification().getName().equals("null")) // is just temporary tree
{
classification = ClassificationManager.get(Classification.Taxonomy, true);
getViewerJTree().update();
}
super.updateView(what);
updateStatusBar();
}
/**
* ask view to destroy itself
*/
public void destroyView() throws CanceledException {
JFrame saveLastActiveFrame = lastActiveFrame;
lastActiveFrame = this.getFrame();
try {
askToSaveCurrent();
} catch (CanceledException ex) {
ProjectManager.setQuitting(false);
throw ex;
}
try {
if (ProjectManager.isQuitting() && ProjectManager.getNumberOfProjects() == 1) {
if (!confirmQuit()) {
ProjectManager.setQuitting(false);
}
}
} catch (CanceledException ex) {
ProjectManager.setQuitting(false);
throw ex;
}
try {
doc.closeConnector();
}
catch (Exception ignored) {}
if (lastActiveViewer == MainViewer.this)
lastActiveViewer = null;
lastActiveFrame = saveLastActiveFrame;
if (lastActiveFrame == getFrame())
lastActiveFrame = null;
super.destroyView();
}
/**
* set the status line for given document
*/
public void updateStatusBar() {
int ntax = Math.max(0, getPhyloTree().getNumberOfNodes());
getStatusBar().setText1("Taxa=" + ntax);
StringBuilder buf2 = new StringBuilder();
final DataTable dataTable = doc.getDataTable();
if (dataTable.getNumberOfSamples() == 0 || dataTable.getTotalReads() == 0) {
if (ProgramProperties.get(MeganProperties.TAXONOMYFILE, MeganProperties.DEFAULT_TAXONOMYFILE).equals(MeganProperties.DEFAULT_TAXONOMYFILE))
buf2.append("Taxonomy");
else
buf2.append("Taxonomy=").append(FileUtils.replaceFileSuffix(FileUtils.getFileNameWithoutPath(ProgramProperties.get(MeganProperties.TAXONOMYFILE, MeganProperties.DEFAULT_TAXONOMYFILE)), ""));
if (TaxonomyData.isAvailable()) {
if (TaxonomyData.getTree().getNumberOfNodes() > 0)
buf2.append(String.format(" size=%,d,", TaxonomyData.getTree().getNumberOfNodes()));
final Set<Integer> disabledTaxa = TaxonomyData.getDisabledTaxa();
if (disabledTaxa != null && disabledTaxa.size() > 0)
buf2.append(String.format(" disabledTaxa=%,d", disabledTaxa.size()));
}
} else {
if (dataTable.getNumberOfSamples() == 1) {
buf2.append(String.format("Reads=%,d Assigned=%,d", doc.getNumberOfReads(), getTotalAssignedReads()));
buf2.append(String.format(" (%s)", doc.getReadAssignmentMode().toString()));
buf2.append(" MinScore=").append(doc.getMinScore());
if (doc.getMaxExpected() != 10000)
buf2.append(" MaxExpected=").append(doc.getMaxExpected());
if (doc.getMinPercentIdentity() > 0)
buf2.append(" MinPercentIdentity=").append(doc.getMinPercentIdentity());
buf2.append(" TopPercent=").append(doc.getTopPercent());
if (doc.getMinSupportPercent() > 0)
buf2.append(" MinSupportPercent=").append(doc.getMinSupportPercent());
if (doc.getMinSupportPercent() == 0 || doc.getMinSupport() > 1)
buf2.append(" MinSupport=").append(doc.getMinSupport());
final Set<Integer> disabledTaxa = TaxonomyData.getDisabledTaxa();
if (disabledTaxa != null && disabledTaxa.size() > 0)
buf2.append(String.format(" disabledTaxa=%,d", disabledTaxa.size()));
if (doc.isUseIdentityFilter())
buf2.append(" UseIdentityFilter=true");
buf2.append(" LCA=").append(doc.getLcaAlgorithm().toString());
if (doc.getLcaCoveragePercent() < 100f)
buf2.append(String.format(" lcaCoveragePercent=%d", Math.round(doc.getLcaCoveragePercent())));
if (doc.getMinPercentReadToCover() > 0)
buf2.append(String.format(" MinPercentReadToCover=%d", Math.round(doc.getMinPercentReadToCover())));
if (doc.getMinPercentReferenceToCover() > 0)
buf2.append(String.format(" MinPercentReferenceToCover=%d", Math.round(doc.getMinPercentReferenceToCover())));
} else {
buf2.append(String.format("Samples=%d,", doc.getNumberOfSamples()));
Comparer.COMPARISON_MODE mode = Comparer.parseMode(dataTable.getParameters());
var normalized_to = Comparer.parseNormalizedTo(dataTable.getParameters());
if (mode.equals(Comparer.COMPARISON_MODE.RELATIVE)) {
buf2.append(String.format(" Relative Comparison, Assigned=%,d (normalized to %,d per sample)", getTotalAssignedReads(), normalized_to));
} else
buf2.append(String.format(" Absolute Comparison, Reads=%,d, Assigned=%,d", doc.getNumberOfReads(), getTotalAssignedReads()));
buf2.append(String.format(" (%s)", doc.getReadAssignmentMode().toString()));
}
if (doc.getBlastMode() != BlastMode.Unknown)
buf2.append(" mode=").append(doc.getBlastMode().toString());
}
getStatusBar().setText2(buf2.toString());
}
/**
* determine whether current data needs saving and allows the user to do so, if necessary
*/
private void askToSaveCurrent() throws CanceledException {
if (ProgramProperties.isUseGUI()) {
if (doc.getMeganFile().isMeganSummaryFile() && doc.getNumberOfSamples() > 0 && doc.isDirty()) {
getFrame().toFront();
getFrame().setAlwaysOnTop(true);
try {
int result = JOptionPane.showConfirmDialog(getFrame(), "Document has been modified, save before " +
(ProjectManager.isQuitting() ? "quitting?" : "closing?"), ProgramProperties.getProgramName() + " - Save Changes?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon());
if (result == JOptionPane.YES_OPTION) {
Boolean[] canceled = new Boolean[]{false};
getCommandManager().getCommand(SaveCommand.NAME).actionPerformed(new ActionEvent(canceled, 0, "askToSave"));
if (canceled[0])
throw new CanceledException();
doc.setDirty(false);
} else if (result == JOptionPane.NO_OPTION)
doc.setDirty(false);
else if (result == JOptionPane.CANCEL_OPTION) {
throw new CanceledException();
}
} finally {
getFrame().setAlwaysOnTop(false);
}
}
}
}
/**
* ask whether user wants to quit
*/
private boolean confirmQuit() throws CanceledException {
if (ProgramProperties.isUseGUI()) {
getFrame().toFront();
int result = JOptionPane.showConfirmDialog(getLastActiveFrame(), "Quit " + ProgramProperties.getProgramName() + "?",
ProgramProperties.getProgramVersion() + " - Quit?", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon());
if (result == JOptionPane.CANCEL_OPTION) {
throw new CanceledException();
} else return result != JOptionPane.NO_OPTION;
} else
return true;
}
/**
* get the quit action
*
* @return quit action
*/
public AbstractAction getQuit() {
return CommandManager.createAction(getCommandManager().getCommand("Quit"));
}
public static JFrame getLastActiveFrame() {
return lastActiveFrame;
}
public static void setLastActiveFrame(JFrame lastActiveFrame) {
MainViewer.lastActiveFrame = lastActiveFrame;
}
/**
* gets the series color getter
*
* @return series color getter
*/
public ChartColorManager.ColorGetter getSeriesColorGetter() {
return new ChartColorManager.ColorGetter() {
private final ChartColorManager.ColorGetter colorGetter = doc.getChartColorManager().getSeriesColorGetter();
public Color get(String label) {
{
if (getNodeDrawer().getStyle() == NodeDrawer.Style.Circle || getNodeDrawer().getStyle() == NodeDrawer.Style.HeatMap)
return Color.WHITE;
else
return colorGetter.get(label);
}
}
};
}
public LabelsJList getSeriesList() {
return seriesList;
}
/**
* get name for this type of viewer
*
* @return name
*/
public String getClassName() {
return "Taxonomy";
}
/**
* collapse to default small tree
*/
public void collapseToDefault() {
getCollapsedIds().clear();
getCollapsedIds().add(2759); // eukaryota
getCollapsedIds().add(2157); // archaea
getCollapsedIds().add(2); // bacteria
getCollapsedIds().add(28384); // other sequences
getCollapsedIds().add(12908); // unclassified sequences
getCollapsedIds().add(12884); // viroids
getCollapsedIds().add(10239); // viruses
}
public void setDoReInduce(boolean b) {
// System.err.println("setDoReInduce: not implemented");
}
public void setDoReset(boolean b) {
//System.err.println("setDoReset: not implemented");
}
public Node getTaxId2Node(int taxId) {
return getANode(taxId);
}
/**
* does this viewer currently have any URLs for selected nodes?
*
* @return true, if has URLs for selected nodes
*/
public boolean hasURLsForSelection() {
return getSelectedNodes().size() > 0;
}
/**
* gets list of URLs associated with selected nodes
*
* @return URLs
*/
public java.util.List<String> getURLsForSelection() {
final ArrayList<String> urls = new ArrayList<>(getSelectedNodes().size());
for (Node v : getSelectedNodes()) {
Integer taxId = (Integer) v.getInfo();
if (taxId != null && taxId > 0) {
try {
urls.add("https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=" + taxId);
} catch (Exception e1) {
Basic.caught(e1);
}
}
}
return urls;
}
} | 16,422 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SyncDataTableAndTaxonomy.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/SyncDataTableAndTaxonomy.java | /*
* SyncDataTableAndTaxonomy.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.util.Basic;
import jloda.util.Pair;
import megan.core.ClassificationType;
import megan.core.DataTable;
import megan.core.Document;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
/**
* sync between summary and taxonomy viewer
* Daniel Huson, 6.2010
*/
public class SyncDataTableAndTaxonomy {
/**
* sync taxonomy formatting (and collapsed nodes) from summary to document
*
*/
public static void syncFormattingFromSummary2Viewer(DataTable table, MainViewer viewer) {
Document doc = viewer.getDir().getDocument();
// can't use nexus parser here because it swallows the ' quotes
final String nodeFormats = table.getNodeFormats(ClassificationType.Taxonomy.toString());
// System.err.println("Node Format: "+nodeFormats);
if (nodeFormats != null) {
int state = 0;
int idA = 0, idB = 0;
int formatA = 0;
for (int pos = 0; pos < nodeFormats.length(); pos++) {
char ch = nodeFormats.charAt(pos);
switch (state) {
case 0: // skipping spaces before taxon id
if (!Character.isSpaceChar(ch)) {
state++;
idA = pos;
}
break;
case 1: // scaning taxon id
idB = pos;
if (ch == ':')
state++;
break;
case 2: // skipping spaces before start of format
if (!Character.isSpaceChar(ch)) {
state++;
formatA = pos;
}
break;
case 3: // scanning format
if (ch == ';') {
int formatB = pos;
if (idA < idB && formatA < formatB) {
int taxId = Integer.parseInt(nodeFormats.substring(idA, idB).trim());
viewer.getDirtyNodeIds().add(taxId);
Node v = viewer.getTaxId2Node(taxId);
if (v != null) {
String format = nodeFormats.substring(formatA, formatB + 1).trim();
try {
viewer.getNV(v).read(format);
} catch (Exception e) {
Basic.caught(e);
}
}
}
state = 0;
}
break;
}
}
}
final String edgeFormats = table.getEdgeFormats(ClassificationType.Taxonomy.toString());
//System.err.println("Edge Format: "+edgeFormats);
if (edgeFormats != null) {
int state = 0;
int taxId1A = 0, taxId1B = 0;
int taxId2A = 0, taxId2B = 0;
int formatA = 0;
for (int pos = 0; pos < edgeFormats.length(); pos++) {
char ch = edgeFormats.charAt(pos);
switch (state) {
case 0: // skipping spaces before taxon id1
if (!Character.isSpaceChar(ch)) {
state++;
taxId1A = pos;
}
break;
case 1: // scanning taxon id
taxId1B = pos;
if (ch == ',')
state++;
break;
case 2: // skipping spaces before taxon id2
if (!Character.isSpaceChar(ch)) {
state++;
taxId2A = pos;
}
break;
case 3: // scanning taxon id
taxId2B = pos;
if (ch == ':')
state++;
break;
case 4: // skipping spaces before start of format
if (!Character.isSpaceChar(ch)) {
state++;
formatA = pos;
}
break;
case 5: // scanning format
if (ch == ';') {
int formatB = pos;
if (taxId1A < taxId1B && taxId2A < taxId2B && formatA < formatB) {
int taxId1 = Integer.parseInt(edgeFormats.substring(taxId1A, taxId1B).trim());
int taxId2 = Integer.parseInt(edgeFormats.substring(taxId2A, taxId2B).trim());
String format = edgeFormats.substring(formatA, formatB + 1).trim();
// System.err.println("got: <"+taxId1+">+<"+taxId2+">: <"+format+">");
Node v = viewer.getTaxId2Node(taxId1);
Node w = viewer.getTaxId2Node(taxId2);
viewer.getDirtyEdgeIds().add(new Pair<>(taxId1, taxId2));
if (v != null && w != null) {
Edge e = v.getCommonEdge(w);
if (e != null) {
try {
viewer.getEV(e).read(format);
} catch (IOException ignored) {
}
}
}
}
state = 0;
}
break;
}
//System.err.println("pos="+pos+", ch="+ch+", state="+state);
}
}
}
/**
* sync collapsed nodes from summary to main viewer
*
*/
public static void syncCollapsedFromSummaryToTaxonomyViewer(DataTable table, MainViewer mainViewer) {
Document doc = mainViewer.getDir().getDocument();
// Sync collapsed nodes:
mainViewer.getCollapsedIds().clear();
if (table.getCollapsed(ClassificationType.Taxonomy.toString()) != null)
mainViewer.getCollapsedIds().addAll(table.getCollapsed(ClassificationType.Taxonomy.toString()));
}
/**
* sync formatting of taxonomy nodes and edges (and also set of collapsed nodes) to summary
*
*/
static public void syncFormattingFromViewer2Summary(MainViewer viewer, DataTable table) {
Document doc = viewer.getDir().getDocument();
if (viewer.getDirtyNodeIds().size() > 0) {
StringBuilder buf = new StringBuilder();
for (Integer taxId : viewer.getDirtyNodeIds()) {
Node v = viewer.getTaxId2Node(taxId);
if (v != null) {
String format = viewer.getNV(v).toString(false);
buf.append(taxId).append(":").append(format);
}
}
table.setNodeFormats(ClassificationType.Taxonomy.toString(), buf.toString());
} else
table.setNodeFormats(ClassificationType.Taxonomy.toString(), null);
if (viewer.getDirtyEdgeIds().size() > 0) {
StringBuilder buf = new StringBuilder();
for (Pair<Integer, Integer> pair : viewer.getDirtyEdgeIds()) {
Node v = viewer.getTaxId2Node(pair.getFirst());
Node w = viewer.getTaxId2Node(pair.getSecond());
if (v != null && w != null) {
Edge e = v.getCommonEdge(w);
if (e != null) {
String format = viewer.getEV(e).toString(false);
buf.append(pair.getFirst()).append(",").append(pair.getSecond()).append(":").append(format);
}
}
}
table.setEdgeFormats(ClassificationType.Taxonomy.toString(), buf.toString());
} else
table.setEdgeFormats(ClassificationType.Taxonomy.toString(), null);
table.setNodeStyle(ClassificationType.Taxonomy.toString(), viewer.getNodeDrawer().getStyle().toString());
// Sync collapsed nodes:
Set<Integer> collapsed = new HashSet<>(viewer.getCollapsedIds());
table.setCollapsed(ClassificationType.Taxonomy.toString(), collapsed);
}
}
| 9,610 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MyGraphViewListener.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/MyGraphViewListener.java | /*
* MyGraphViewListener.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import jloda.fx.util.ProgramExecutorService;
import jloda.graph.*;
import jloda.phylo.PhyloTree;
import jloda.swing.graphview.*;
import jloda.swing.util.Cursors;
import jloda.util.Basic;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.util.LinkedList;
import java.util.Objects;
/**
* Listener for all GraphView events
*/
public class MyGraphViewListener implements IGraphViewListener {
private boolean inWait = false;
final static boolean hasLabelXORBug = true;
private final ViewerBase viewer;
private final PhyloTree tree;
private final NodeArray<Rectangle> node2bbox;
private final int inClick = 1;
protected final int inMove = 2;
private final int inRubberband = 3;
private final int inNewEdge = 4;
private final int inMoveNodeLabel = 5;
private final int inMoveEdgeLabel = 6;
private final int inMoveInternalEdgePoint = 7;
private final int inScrollByMouse = 8;
private final int inMoveMagnifier = 9;
private final int inResizeMagnifier = 10;
private int current;
private int downX;
private int downY;
private Rectangle selRect;
private Point prevPt;
private Point offset; // used by move node label
private final NodeSet hitNodes;
private final NodeSet hitNodeLabels;
private final EdgeSet hitEdges;
private final EdgeSet hitEdgeLabels;
private final NodeSet nodesWithMovedLabels;
private boolean inPopup = false;
// is mouse still pressed?
private boolean stillDownWithoutMoving = false;
/**
* Constructor
*
* @param gv PhyloTreeView
* @param node2bbox mapping of nodes to bounding boxes
*/
public MyGraphViewListener(ViewerBase gv, NodeArray<Rectangle> node2bbox, NodeSet nodesWithMovedLabels) {
viewer = gv;
tree = (PhyloTree) gv.getGraph();
this.node2bbox = node2bbox;
this.nodesWithMovedLabels = nodesWithMovedLabels;
hitNodes = new NodeSet(viewer.getGraph());
hitNodeLabels = new NodeSet(viewer.getGraph());
hitEdges = new EdgeSet(viewer.getGraph());
hitEdgeLabels = new EdgeSet(viewer.getGraph());
}
/**
* Mouse pressed.
*
* @param me MouseEvent
*/
public void mousePressed(MouseEvent me) {
downX = me.getX();
downY = me.getY();
selRect = null;
prevPt = null;
offset = new Point();
current = 0;
stillDownWithoutMoving = true;
viewer.requestFocusInWindow();
int magnifierHit = viewer.trans.getMagnifier().hit(downX, downY);
if (magnifierHit != Magnifier.HIT_NOTHING) {
switch (magnifierHit) {
case Magnifier.HIT_MOVE:
current = inMoveMagnifier;
viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
break;
case Magnifier.HIT_RESIZE:
current = inResizeMagnifier;
viewer.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
break;
case Magnifier.HIT_INCREASE_MAGNIFICATION:
if (viewer.trans.getMagnifier().increaseDisplacement())
viewer.repaint();
break;
case Magnifier.HIT_DECREASE_MAGNIFICATION:
if (viewer.trans.getMagnifier().decreaseDisplacement())
viewer.repaint();
break;
default:
break;
}
return;
}
getHits(downX, downY, false);
int numHitNodes = hitNodes.size();
viewer.fireDoPress(hitNodes);
int numHitNodeLabels = hitNodeLabels.size();
int numHitEdges = hitEdges.size();
int numHitEdgeLabels = hitEdgeLabels.size();
viewer.fireDoPress(hitEdges);
if (me.isPopupTrigger()) {
inPopup = true;
viewer.setCursor(Cursor.getDefaultCursor());
if (numHitNodes != 0) {
viewer.fireNodePopup(me, hitNodes);
viewer.resetCursor();
return;
} else if (numHitNodeLabels != 0) {
viewer.fireNodeLabelPopup(me, hitNodeLabels);
viewer.resetCursor();
return;
} else if (numHitEdges != 0) {
viewer.fireEdgePopup(me, hitEdges);
viewer.resetCursor();
return;
} else if (numHitEdgeLabels != 0) {
viewer.fireEdgeLabelPopup(me, hitEdgeLabels);
viewer.resetCursor();
return;
} else if (me.isPopupTrigger()) {
viewer.firePanelPopup(me);
viewer.resetCursor();
return;
}
}
if (numHitNodes == 0 && numHitNodeLabels == 0 && numHitEdges == 0 && numHitEdgeLabels == 0) {
if (me.isAltDown() || me.isShiftDown()) {
current = inRubberband;
viewer.setCursor(Cursor.getDefaultCursor());
} else {
current = inScrollByMouse;
viewer.setCursor(Cursors.getClosedHand());
if (!inWait) {
ProgramExecutorService.getInstance().execute(new Runnable() {
public void run() {
try {
inWait = true;
synchronized (this) {
Thread.sleep(500);
}
} catch (InterruptedException ignored) {
}
if (stillDownWithoutMoving) {
current = inRubberband;
viewer.setCursor(Cursor.getDefaultCursor());
}
inWait = false;
}
});
}
}
} else {
viewer.setCursor(Cursor.getDefaultCursor());
if (viewer.getAllowEdit() && numHitNodes == 1 && me.isControlDown()
&& !me.isShiftDown())
current = inNewEdge;
else if (numHitNodes == 0 && numHitEdges == 0 && numHitNodeLabels > 0) {
Node v = hitNodeLabels.getFirstElement();
try {
if (!viewer.getSelected(v) || viewer.getLabel(v) == null)
return; // move labels only of selected node
} catch (NotOwnerException ignored) {
}
current = inMoveNodeLabel;
viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
} else if (numHitNodes == 0 && numHitEdges == 0 && numHitNodeLabels == 0) {
Edge e = hitEdgeLabels.getFirstElement();
try {
if (!viewer.getSelected(e) || viewer.getLabel(e) == null)
return; // move labels only of selected edges
} catch (NotOwnerException ignored) {
}
current = inMoveEdgeLabel;
viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
} else if (viewer.isAllowMoveInternalEdgePoints() && numHitEdges == 1)
current = inMoveInternalEdgePoint;
}
}
/**
* find out what we have hit
*
*/
private void getHits(int x, int y, boolean onlyOne) {
hitNodes.clear();
hitNodeLabels.clear();
hitEdges.clear();
hitEdgeLabels.clear();
Node root = tree.getRoot();
if (root != null)
getHitsRec(x, y, root, null, onlyOne);
// need to look at all the node labels the user has dragged around
for (Node v = nodesWithMovedLabels.getFirstElement(); v != null; v = nodesWithMovedLabels.getNextElement(v)) {
if (viewer.getLabel(v) != null && viewer.getLabel(v).length() > 0 && viewer.getLocation(v) != null && viewer.getLabelVisible(v)
&& viewer.getLabelRect(v) != null && viewer.getLabelRect(v).contains(x, y))
hitNodeLabels.add(v);
if (onlyOne)
return;
}
}
/**
* recursively go down tree to find hits
*
* @return has hit something
*/
private boolean getHitsRec(int x, int y, Node v, Edge e0, boolean onlyOne) {
Rectangle bbox0 = node2bbox.get(v);
if (bbox0 == null)
return false;
Rectangle bbox = new Rectangle(bbox0.x - 100, bbox0.y - 40, bbox0.width + 1000, bbox0.height + 80);
Rectangle bboxDC = new Rectangle();
viewer.trans.w2d(bbox, bboxDC);
boolean hit = false;
try {
Rectangle labelBox = null;
final NodeView nv = viewer.getNV(v);
if (nv != null && nv.getLabel() != null && nv.getLabel().length() > 0 && nv.getLabelVisible())
labelBox = nv.getLabelRect(viewer.trans);
if (bboxDC.contains(x, y) || v.getInDegree() == 0 || v.getOutDegree() == 0
|| (labelBox != null && labelBox.contains(x, y))) // always check root and leaves
{
if (viewer.getLocation(v) != null && viewer.getBox(v).contains(x, y)) {
hitNodes.add(v);
hit = true;
if (onlyOne)
return true;
}
if (viewer.getLabel(v) != null && viewer.getLocation(v) != null && viewer.getLabelVisible(v) && viewer.getLabelRect(v) != null && viewer.getLabelRect(v).contains(x, y)) {
hitNodeLabels.add(v);
hit = true;
if (onlyOne)
return true;
}
for (Edge f = v.getFirstAdjacentEdge(); !hit && f != null; f = v.getNextAdjacentEdge(f)) {
if (f != e0) {
Node w = v.getOpposite(f);
NodeView vv = viewer.getNV(v);
NodeView wv = viewer.getNV(w);
if (vv.getLocation() == null || wv.getLocation() == null)
continue;
Point vp = vv.computeConnectPoint(wv.getLocation(), viewer.trans);
Point wp = wv.computeConnectPoint(vv.getLocation(), viewer.trans);
if (tree.findDirectedEdge(v, w) != null)
viewer.adjustBiEdge(Objects.requireNonNull(vp), Objects.requireNonNull(wp)); // adjust for parallel edge
if (viewer.getEV(f).hitEdge(vp, wp, viewer.trans, x, y, 3)) {
hitEdges.add(f);
hit = true;
if (onlyOne)
return true;
}
viewer.getEV(f).setLabelReferenceLocation(vp, wp, viewer.trans);
if (viewer.getLabel(f) != null && viewer.getLabel(f).length() > 0 && viewer.getLabelVisible(f) && viewer.getLabelRect(f) != null &&
viewer.getLabelRect(f).contains(x, y)) {
hitEdgeLabels.add(f);
hit = true;
if (onlyOne)
return true;
}
if (!hit)
hit = getHitsRec(x, y, w, f, onlyOne);
if (hit && onlyOne)
return true;
}
}
}
}
catch(NotOwnerException ignored){}
return hit;
}
/**
* find out what we have hit
*
*/
private void getHits(Rectangle rect) {
hitNodes.clear();
hitNodeLabels.clear();
hitEdges.clear();
hitEdgeLabels.clear();
Node root = tree.getRoot();
if (root != null)
getHitsRec(rect, root, null);
// need to look at all the node labels the user has dragged around
for (Node v = nodesWithMovedLabels.getFirstElement(); v != null; v = nodesWithMovedLabels.getNextElement(v)) {
if (viewer.getLabel(v) != null && viewer.getLocation(v) != null && viewer.getLabelVisible(v) && viewer.getLabelRect(v) != null
&& rect.contains(viewer.getLabelRect(v)))
hitNodeLabels.add(v);
}
}
/**
* recursively go down tree to find hits
*
* @return has hit something
*/
private boolean getHitsRec(Rectangle rect, Node v, Edge e0) {
boolean hit = false;
try {
Rectangle bbox = node2bbox.get(v);
Rectangle bboxDC = new Rectangle();
viewer.trans.w2d(bbox, bboxDC);
int height = bboxDC.height;
// grow box slightly to capture labels
bboxDC.add(bboxDC.getMinX() - 20, bboxDC.getMinY() - 20);
bboxDC.add(bboxDC.getMaxX() + 20, bboxDC.getMaxY() + 20);
if (bboxDC.intersects(rect) || v.getInDegree() == 0 || v.getOutDegree() == 0) // always check root and leaves
{
if (viewer.getLocation(v) != null && rect.contains(viewer.getBox(v))) {
hitNodes.add(v);
hit = true;
}
if (viewer.getLabel(v) != null && viewer.getLocation(v) != null && viewer.getLabelVisible(v) && viewer.getLabelRect(v) != null
&& rect.contains(viewer.getLabelRect(v))) {
hitNodeLabels.add(v);
hit = true;
}
if (viewer.getGraph().getDegree(v) > 1 && height / (viewer.getGraph().getDegree(v) - 1) < 2)
return hit; // box is too small to see
for (Edge f = v.getFirstAdjacentEdge(); f != null; f = v.getNextAdjacentEdge(f)) {
if (f != e0) {
Node w = f.getOpposite(v);
if (viewer.getLocation(v) != null && viewer.getLocation(w) != null &&
rect.contains(viewer.trans.w2d(viewer.getLocation(v)))
&& rect.contains(viewer.trans.w2d(viewer.getLocation(w))))
hitEdges.add(f);
if (viewer.getLabel(f) != null && viewer.getLabelVisible(f) && viewer.getLabelRect(f) != null &&
rect.contains(viewer.getLabelRect(f))) {
hitEdgeLabels.add(f);
hit = true;
}
if (getHitsRec(rect, w, f))
hit = true;
}
}
}
}
catch(NotOwnerException ignored){}
return hit;
}
/**
* Mouse released.
*
* @param me MouseEvent
*/
public void mouseReleased(MouseEvent me) {
viewer.resetCursor();
stillDownWithoutMoving = false;
if (current == inScrollByMouse) {
return;
}
viewer.fireDoRelease(hitNodes);
viewer.fireDoRelease(hitEdges);
if (me.isPopupTrigger()) {
inPopup = true;
viewer.setCursor(Cursor.getDefaultCursor());
if (hitNodes.size() != 0)
viewer.fireNodePopup(me, hitNodes);
else if (hitNodeLabels.size() != 0)
viewer.fireNodeLabelPopup(me, hitNodeLabels);
else if (hitEdges.size() != 0)
viewer.fireEdgePopup(me, hitEdges);
else if (hitEdgeLabels.size() != 0)
viewer.fireEdgeLabelPopup(me, hitEdgeLabels);
else
viewer.firePanelPopup(me);
viewer.resetCursor();
return;
}
if (current == inRubberband) {
Rectangle rect = new Rectangle(downX, downY, 0, 0);
rect.add(me.getX(), me.getY());
getHits(rect);
selectNodesEdges(hitNodes, hitEdges, me.isShiftDown(), me.getClickCount());
viewer.repaint();
} else if (current == inNewEdge) {
NodeSet firstHit = getHitNodes(downX, downY);
if (firstHit.size() == 1) {
Node v = firstHit.getFirstElement();
NodeSet secondHit = getHitNodes(me.getX(), me.getY());
Node w;
if (secondHit.size() == 0) {
try {
Point2D location = viewer.trans.d2w(me.getPoint());
viewer.setDefaultNodeLocation(location);
Edge e = viewer.newEdge(v, null);
if (e != null) {
w = viewer.getGraph().getTarget(e);
viewer.setLocation(w, location);
}
} catch (NotOwnerException ignored) {
}
} else if (secondHit.size() == 1) {
w = secondHit.getFirstElement();
if (w != null) {
if (v != w) {
viewer.newEdge(v, w);
}
}
}
viewer.repaint();
}
} else if (current == inMoveNodeLabel) {
viewer.repaint();
} else if (current == inMoveEdgeLabel) {
viewer.repaint();
}
}
/**
* Mouse entered.
*
* @param me MouseEvent
*/
public void mouseEntered(MouseEvent me) {
}
/**
* Mouse exited.
*
* @param me MouseEvent
*/
public void mouseExited(MouseEvent me) {
stillDownWithoutMoving = false;
}
/**
* Mouse clicked.
*
* @param me MouseEvent
*/
public void mouseClicked(MouseEvent me) {
int meX = me.getX();
int meY = me.getY();
if (inPopup) {
inPopup = false;
return;
}
getHits(meX, meY, false);
if (current == inScrollByMouse) // in navigation mode, double-click to lose selection
{
if (hitNodes.size() == 0 && hitEdges.size() == 0 && hitNodeLabels.size() == 0 && hitEdgeLabels.size() == 0) {
viewer.selectAllNodes(false);
viewer.selectAllEdges(false);
viewer.repaint();
return;
}
}
current = inClick;
if (hitNodes.size() != 0)
viewer.fireDoClick(hitNodes, me.getClickCount());
if (hitEdges.size() != 0)
viewer.fireDoClick(hitEdges, me.getClickCount());
if (hitNodeLabels.size() != 0)
viewer.fireDoClickLabel(hitNodeLabels, me.getClickCount());
if (hitEdgeLabels.size() != 0)
viewer.fireDoClickLabel(hitEdgeLabels, me.getClickCount());
if (me.getClickCount() == 1) {
if (!hitNodes.isEmpty() || !hitEdges.isEmpty())
selectNodesEdges(hitNodes, hitEdges, me.isShiftDown(), me.getClickCount());
else if (!hitNodeLabels.isEmpty() || !hitEdgeLabels.isEmpty())
selectNodesEdges(hitNodeLabels, hitEdgeLabels, me.isShiftDown(), me.getClickCount());
}
if (me.getClickCount() == 2 && viewer.getAllowEdit() && hitNodes.size() == 0 && hitEdges.size() == 0) {
// New node:
if (viewer.getAllowNewNodeDoubleClick()) {
viewer.setDefaultNodeLocation(viewer.trans.d2w(me.getPoint()));
Node v = viewer.newNode();
if (v != null) {
try {
viewer.setLocation(v, viewer.trans.d2w(me.getPoint()));
viewer.setDefaultNodeLocation(viewer.trans.d2w(new Point(meX + 10, meY + 10)));
viewer.repaint();
} catch (NotOwnerException ignored) {
}
}
}
} else if (me.getClickCount() == 3 && viewer.isAllowInternalEdgePoints() && hitNodes.size() == 0 && hitEdges.size() == 1) {
Edge e = hitEdges.getFirstElement();
try {
EdgeView ev = viewer.getEV(e);
Point vp = viewer.trans.w2d(viewer.getLocation(viewer.getGraph().getSource(e)));
Point wp = viewer.trans.w2d(viewer.getLocation(viewer.getGraph().getTarget(e)));
int index = ev.hitEdgeRank(vp, wp, viewer.trans, me.getX(), meY, 3);
java.util.List<Point2D> list = viewer.getInternalPoints(e);
Point2D aptWorld = viewer.trans.d2w(me.getPoint());
if (list == null) {
list = new LinkedList<>();
list.add(aptWorld);
viewer.setInternalPoints(e, list);
} else
list.add(index, aptWorld);
} catch (NotOwnerException ex) {
Basic.caught(ex);
}
} else if (me.getClickCount() == 2
&& ((viewer.isAllowEditNodeLabelsOnDoubleClick() && hitNodeLabels.size() > 0)
|| (viewer.isAllowEditNodeLabelsOnDoubleClick() && hitNodes.size() > 0))) {
try {
// undo node label
Node v;
if (hitNodeLabels.size() > 0)
v = hitNodeLabels.getLastElement();
else
v = hitNodes.getLastElement();
String label = viewer.getLabel(v);
label = JOptionPane.showInputDialog(viewer.getFrame(), "Edit Node Label:", label);
if (label != null && !label.equals(viewer.getLabel(v))) {
viewer.setLabel(v, label);
viewer.setLabelVisible(v, label.length() > 0);
viewer.repaint();
}
} catch (NotOwnerException ex) {
Basic.caught(ex);
}
} else if (me.getClickCount() == 2 &&
((viewer.isAllowEditEdgeLabelsOnDoubleClick() && hitEdgeLabels.size() > 0)
|| (viewer.isAllowEditEdgeLabelsOnDoubleClick() && hitEdges.size() > 0))) {
try {
Edge e;
if (hitEdgeLabels.size() > 0)
e = hitEdgeLabels.getLastElement();
else
e = hitEdges.getLastElement();
String label = viewer.getLabel(e);
label = JOptionPane.showInputDialog(viewer.getFrame(), "Edit Edge Label:", label);
if (label != null && !label.equals(viewer.getLabel(e))) {
viewer.setLabel(e, label);
viewer.setLabelVisible(e, label.length() > 0);
viewer.repaint();
}
} catch (NotOwnerException ex) {
Basic.caught(ex);
}
}
current = 0;
}
/**
* Mouse dragged.
*
* @param me MouseEvent
*/
public void mouseDragged(MouseEvent me) {
stillDownWithoutMoving = false;
if (current == inScrollByMouse) {
viewer.setCursor(Cursors.getClosedHand());
JScrollPane scrollPane = viewer.getScrollPane();
int dX = me.getX() - downX;
int dY = me.getY() - downY;
if (dY != 0) {
JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
int amount = Math.round(dY * (scrollBar.getMaximum() - scrollBar.getMinimum()) / viewer.getHeight());
if (amount != 0) {
scrollBar.setValue(scrollBar.getValue() - amount);
}
}
if (dX != 0) {
JScrollBar scrollBar = scrollPane.getHorizontalScrollBar();
int amount = Math.round(dX * (scrollBar.getMaximum() - scrollBar.getMinimum()) / viewer.getWidth());
if (amount != 0) {
scrollBar.setValue(scrollBar.getValue() - amount);
}
}
} else if (current == inRubberband) {
Graphics2D gc = (Graphics2D) viewer.getGraphics();
if (gc != null) {
gc.setXORMode(viewer.getCanvasColor());
if (selRect != null)
gc.drawRect(selRect.x, selRect.y, selRect.width, selRect.height);
selRect = new Rectangle(downX, downY, 0, 0);
selRect.add(me.getX(), me.getY());
gc.drawRect(selRect.x, selRect.y, selRect.width, selRect.height);
}
} else if (viewer.isAllowInternalEdgePoints() &&
current == inMoveInternalEdgePoint) {
Point p1 = new Point(downX, downY); // old [pos
Edge e = getHitEdges(downX, downY).getFirstElement();
downX = me.getX();
downY = me.getY();
Point p2 = new Point(downX, downY); // new pos
try {
if (e != null) {
viewer.getEV(e).moveInternalPoint(viewer.trans, p1, p2);
viewer.repaint();
}
} catch (NotOwnerException ignored) {
}
} else if (current == inMoveNodeLabel) {
if (hitNodeLabels.size() > 0) {
Node v = hitNodeLabels.getFirstElement();
try {
if (!viewer.getSelected(v) || viewer.getNV(v).getLabel() == null)
return; // move labels only of selected node
} catch (NotOwnerException e) {
return; // move labels only of selected node
}
NodeView nv = viewer.getNV(v);
Graphics2D gc = (Graphics2D) viewer.getGraphics();
if (gc != null) {
Point apt = viewer.trans.w2d(nv.getLocation());
int meX = me.getX();
int meY = me.getY();
gc.setXORMode(viewer.getCanvasColor());
if (prevPt != null) {
gc.drawLine(apt.x, apt.y, prevPt.x, prevPt.y);
} else {
prevPt = new Point(downX, downY);
Point labPt = nv.getLabelPosition(viewer.trans);
if (labPt != null) {
offset.x = labPt.x - downX;
offset.y = labPt.y - downY;
}
}
gc.drawLine(apt.x, apt.y, meX, meY);
nv.hiliteLabel(gc, viewer.trans, viewer.getFont());
int labX = meX + offset.x;
int labY = meY + offset.y;
nv.setLabelPositionRelative(labX - apt.x, labY - apt.y);
nv.hiliteLabel(gc, viewer.trans, viewer.getFont());
prevPt.x = meX;
prevPt.y = meY;
nodesWithMovedLabels.add(v);
}
}
} else if (current == inMoveEdgeLabel) {
if (hitEdgeLabels.size() > 0) {
try {
Edge e = hitEdgeLabels.getFirstElement();
try {
if (!viewer.getSelected(e) || viewer.getEV(e).getLabel() == null)
return; // move labels only of selected edges
} catch (NotOwnerException ex) {
return; // move labels only of selected edges
}
EdgeView ev = viewer.getEV(e);
Point2D nextToV;
Point2D nextToW;
Graph G = viewer.getGraph();
NodeView vv = viewer.getNV(G.getSource(e));
NodeView wv = viewer.getNV(G.getTarget(e));
nextToV = wv.getLocation();
nextToW = vv.getLocation();
if (viewer.getInternalPoints(e) != null) {
if (viewer.getInternalPoints(e).size() != 0) {
nextToV = viewer.getInternalPoints(e).get(0);
nextToW = viewer.getInternalPoints(e).get(viewer.getInternalPoints(e).size() - 1);
}
}
Point pv = vv.computeConnectPoint(nextToV, viewer.trans);
Point pw = wv.computeConnectPoint(nextToW, viewer.trans);
if (G.findDirectedEdge(G.getTarget(e), G.getSource(e)) != null)
viewer.adjustBiEdge(Objects.requireNonNull(pv), Objects.requireNonNull(pw)); // want parallel bi-edges
Graphics2D gc = (Graphics2D) viewer.getGraphics();
if (gc != null) {
ev.setLabelReferenceLocation(nextToV, nextToW, viewer.trans);
ev.setLabelSize(gc);
Point apt = ev.getLabelReferencePoint();
int meX = me.getX();
int meY = me.getY();
gc.setXORMode(viewer.getCanvasColor());
if (prevPt != null)
gc.drawLine(apt.x, apt.y, prevPt.x, prevPt.y);
else {
prevPt = new Point(downX, downY);
Point labPt = ev.getLabelPosition(viewer.trans);
offset.x = Objects.requireNonNull(labPt).x - downX;
offset.y = labPt.y - downY;
}
gc.drawLine(apt.x, apt.y, meX, meY);
ev.hiliteLabel(gc, viewer.trans);
int labX = meX + offset.x;
int labY = meY + offset.y;
ev.setLabelPositionRelative(labX - apt.x, labY - apt.y);
ev.hiliteLabel(gc, viewer.trans);
prevPt.x = meX;
prevPt.y = meY;
}
} catch (NotOwnerException ex) {
Basic.caught(ex);
}
}
} else if (current == inNewEdge) {
Graphics gc = viewer.getGraphics();
if (gc != null) {
gc.setXORMode(viewer.getCanvasColor());
if (selRect != null) // we misuse the selRect here...
gc.drawLine(downX, downY, selRect.x, selRect.y);
selRect = new Rectangle(me.getX(), me.getY(), 0, 0);
gc.drawLine(downX, downY, me.getX(), me.getY());
}
} else if (current == inMoveMagnifier) {
int meX = me.getX();
int meY = me.getY();
if (meX != downX || meY != downY) {
viewer.trans.getMagnifier().move(downX, downY, meX, meY);
downX = meX;
downY = meY;
viewer.repaint();
}
} else if (current == inResizeMagnifier) {
int meY = me.getY();
if (meY != downY) {
viewer.trans.getMagnifier().resize(downY, meY);
downX = me.getX();
downY = meY;
viewer.repaint();
}
}
}
/**
* Mouse moved.
*
* @param me MouseEvent
*/
public void mouseMoved(MouseEvent me) {
stillDownWithoutMoving = false;
if (!viewer.isLocked()) {
Node v = getAHitNodeOrNodeLabel(me.getX(), me.getY());
if (v != null)
viewer.setToolTipText(v);
else
viewer.setToolTipText((String) null);
} else
viewer.setToolTipText((String) null);
}
/**
* Updates the selection of nodes and edges.
*
* @param hitNodes NodeSet
* @param hitEdges EdgeSet
* @param shift boolean
* @param clicks int
*/
private void selectNodesEdges(NodeSet hitNodes, EdgeSet hitEdges, boolean shift, int clicks) {
if (hitNodes.size() == 1) // in this case, only do node selection
hitEdges.clear();
Graph G = viewer.getGraph();
boolean changed = false;
// no shift, deselect everything:
if (!shift && (viewer.getNumberSelectedNodes() > 0 || viewer.getNumberSelectedEdges() > 0)) {
viewer.selectAllNodes(false);
viewer.selectAllEdges(false);
changed = true;
}
try {
if ((clicks > 0 || viewer.isAllowRubberbandNodes()) && hitNodes.size() > 0) {
for (Node v = G.getFirstNode(); v != null; v = G.getNextNode(v)) {
if (hitNodes.contains(v)) {
if (!shift) {
viewer.setSelected(v, true);
changed = true;
if (clicks > 1)
break;
} else // shift==true
{
//
viewer.setSelected(v, !viewer.getSelected(v));
changed = true;
}
}
}
}
if ((clicks > 0 || viewer.isAllowRubberbandEdges()) && hitEdges.size() > 0) {
for (Edge e = G.getFirstEdge(); e != null; e = G.getNextEdge(e)) {
if (hitEdges.contains(e)) {
if (!shift) {
if (clicks == 0 || viewer.getNumberSelectedNodes() == 0) {
viewer.setSelected(e, true);
// selectedNodes.insert(tree.source(e));
// selectedNodes.insert(tree.target(e));
changed = true;
}
if (clicks > 1)
break;
} else // shift==true
{
// selectedNodes.insert(tree.source(e));
// selectedNodes.insert(tree.target(e));
// selectedEdges.member(e)
viewer.setSelected(e, !viewer.getSelected(e));
changed = true;
}
}
}
}
} finally {
if (changed)
viewer.repaint();
}
}
/**
* Get the hit nodes.
*
* @param rect Rectangle
* @return hit_nodes NodeSet
*/
NodeSet getHitNodes(Rectangle rect) {
getHits(rect);
return hitNodes;
}
/**
* Get the hit nodes.
*
* @param x int
* @param y int
* @return hit_nodes NodeSet
*/
private NodeSet getHitNodes(int x, int y) {
getHits(x, y, false);
return hitNodes;
}
/**
* Get the hit nodes.
*
* @param x int
* @param y int
* @return hit_nodes NodeSet
*/
private Node getAHitNodeOrNodeLabel(int x, int y) {
getHits(x, y, true);
if (hitNodes.size() > 0)
return hitNodes.getFirstElement();
if (hitNodeLabels.size() > 0)
return hitNodeLabels.getFirstElement();
return null;
}
/**
* Get the hit node labels.
*
* @param x int
* @param y int
* @return nodes whose labels have been hit
*/
NodeSet getHitNodeLabels(int x, int y) {
getHits(x, y, false);
return hitNodeLabels;
}
/**
* Get the hit edge labels.
*
* @param x int
* @param y int
* @return edges whose labels have been hit
*/
EdgeSet getHitEdgeLabels(int x, int y) {
getHits(x, y, false);
return hitEdgeLabels;
}
/**
* Get the hit edges.
*
* @param rect Rectangle
* @return hit_edges EdgeSet
*/
EdgeSet getHitEdges(Rectangle rect) {
getHits(rect);
return hitEdges;
}
/**
* Get the hit edges.
*
* @param x int
* @param y int
* @return hit_edges EdgeSet
*/
private EdgeSet getHitEdges(int x, int y) {
getHits(x, y, false);
return hitEdges;
}
// KeyListener methods:
/**
* Key typed
*
* @param ke Keyevent
*/
public void keyTyped(KeyEvent ke) {
}
/**
* Key pressed
*
* @param ke KeyEvent
*/
public void keyPressed(KeyEvent ke) {
JScrollPane scrollPane = viewer.getScrollPane();
if (ke.getKeyCode() == KeyEvent.VK_LEFT) {
JScrollBar scrollBar = scrollPane.getHorizontalScrollBar();
if (!ke.isShiftDown() && scrollBar.getVisibleAmount() < scrollBar.getMaximum()) {
scrollBar.setValue(scrollBar.getValue() + scrollBar.getBlockIncrement(1));
} else {
double scale = viewer.trans.getScaleX() / 1.1;
if (scale >= MainViewer.XMIN_SCALE)
viewer.trans.composeScale(1 / 1.1, 1.0);
}
} else if (ke.getKeyCode() == KeyEvent.VK_RIGHT) {
JScrollBar scrollBar = scrollPane.getHorizontalScrollBar();
if (!ke.isShiftDown() && scrollBar.getVisibleAmount() < scrollBar.getMaximum()) {
scrollBar.setValue(scrollBar.getValue() - scrollBar.getBlockIncrement(1));
} else { //centerAndScale
double scale = 1.1 * viewer.trans.getScaleX();
if (scale <= MainViewer.XMAX_SCALE) {
viewer.trans.composeScale(1.1, 1.0);
}
}
} else if (ke.getKeyCode() == KeyEvent.VK_UP) {
JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
if (!ke.isShiftDown() && scrollBar.getVisibleAmount() < scrollBar.getMaximum()) {
scrollBar.setValue(scrollBar.getValue() - scrollBar.getBlockIncrement(1));
} else { //centerAndScale
double scale = 1.1 * viewer.trans.getScaleY();
if (scale <= MainViewer.YMAX_SCALE) {
viewer.trans.composeScale(1, 1.1);
}
}
} else if (ke.getKeyCode() == KeyEvent.VK_PAGE_UP) { //centerAndScale
double scale = 1.1 * viewer.trans.getScaleY();
if (scale <= MainViewer.YMAX_SCALE) {
viewer.trans.composeScale(1, 1.1);
}
} else if (ke.getKeyCode() == KeyEvent.VK_DOWN) {
JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
if (!ke.isShiftDown() && scrollBar.getVisibleAmount() < scrollBar.getMaximum()) {
scrollBar.setValue(scrollBar.getValue() + scrollBar.getBlockIncrement(1));
} else { //centerAndScale
double scale = viewer.trans.getScaleY() / 1.1;
if (scale >= MainViewer.YMIN_SCALE) {
viewer.trans.composeScale(1, 1 / 1.1);
}
}
} else if (ke.getKeyCode() == KeyEvent.VK_PAGE_DOWN) { //centerAndScale
double scale = viewer.trans.getScaleY() / 1.1;
if (scale >= MainViewer.YMIN_SCALE) {
viewer.trans.composeScale(1, 1 / 1.1);
}
} else if (ke.getKeyCode() == KeyEvent.VK_DELETE && viewer.getAllowEdit()) {
viewer.delSelectedEdges();
viewer.delSelectedNodes();
} else if (ke.getKeyCode() == KeyEvent.VK_SPACE) {
} else if (ke.getKeyChar() == 'c') {
viewer.centerGraph();
} else if ((ke.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) != 0) {
viewer.setCursor(Cursor.getDefaultCursor());
}
}
/**
* Key released
*
* @param ke KeyEvent
*/
public void keyReleased(KeyEvent ke) {
if ((ke.getModifiersEx() & InputEvent.SHIFT_DOWN_MASK) != 0) {
viewer.resetCursor();
}
}
// ComponentListener methods:
/**
* component hidded
*
* @param ev ComponentEvent
*/
public void componentHidden(ComponentEvent ev) {
}
/**
* component moved
*
* @param ev ComponentEvent
*/
public void componentMoved(ComponentEvent ev) {
}
/**
* component resized
*
* @param ev ComponentEvent
*/
public void componentResized(ComponentEvent ev) {
viewer.setSize(viewer.getSize());
}
/**
* component shown
*
* @param ev ComponentEvent
*/
public void componentShown(ComponentEvent ev) {
}
/**
* react to a mouse wheel event
*
*/
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {
boolean doScaleVertical = !e.isMetaDown() && !e.isAltDown() && !e.isShiftDown();
boolean doScaleHorizontal = !e.isMetaDown() && !e.isControlDown() && !e.isAltDown() && e.isShiftDown();
boolean doScrollVertical = !e.isMetaDown() && e.isAltDown() && !e.isShiftDown();
boolean doScrollHorizontal = !e.isMetaDown() && e.isAltDown() && e.isShiftDown();
boolean useMag = viewer.trans.getMagnifier().isActive();
viewer.trans.getMagnifier().setActive(false);
if (doScrollVertical) { //scroll
viewer.getScrollPane().getVerticalScrollBar().setValue(viewer.getScrollPane().getVerticalScrollBar().getValue() + e.getUnitsToScroll());
} else if (doScaleVertical) { //centerAndScale
ScrollPaneAdjuster spa = new ScrollPaneAdjuster(viewer.getScrollPane(), viewer.trans, e.getPoint());
double toScroll = 1.0 + (e.getUnitsToScroll() / 100.0);
double s = (toScroll > 0 ? 1.0 / toScroll : toScroll);
double scale = s * viewer.trans.getScaleY();
if (scale >= MainViewer.YMIN_SCALE && scale <= MainViewer.YMAX_SCALE) {
viewer.trans.composeScale(1, s);
spa.adjust(false, true);
}
} else if (doScrollHorizontal) {
viewer.getScrollPane().getHorizontalScrollBar().setValue(viewer.getScrollPane().getHorizontalScrollBar().getValue() + e.getUnitsToScroll());
} else if (doScaleHorizontal) { //centerAndScale
ScrollPaneAdjuster spa = new ScrollPaneAdjuster(viewer.getScrollPane(), viewer.trans, e.getPoint());
double units = 1.0 + (e.getUnitsToScroll() / 100.0);
double s = (units > 0 ? 1.0 / units : units);
double scale = s * viewer.trans.getScaleX();
if (scale >= MainViewer.XMIN_SCALE && scale <= MainViewer.XMAX_SCALE) {
viewer.trans.composeScale(s, 1);
spa.adjust(true, false);
}
}
viewer.trans.getMagnifier().setActive(useMag);
}
}
}
// EOF
| 44,062 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
TaxonomicLevels.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/TaxonomicLevels.java | /*
* TaxonomicLevels.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import java.util.*;
/**
* defines names and codes for taxonomic levels
* Daniel Huson, 6.2007
*/
public class TaxonomicLevels {
private final Map<Integer, String> id2name;
private final Map<String, Integer> name2id;
private final List<String> names = new LinkedList<>();
public static final String Domain = "Domain";
public static final String Kingdom = "Kingdom";
public static final String Phylum = "Phylum";
public static final String Class = "Class";
public static final String Order = "Order";
public static final String Family = "Family";
private static final String Varietas = "Varietas";
public static final String Genus = "Genus";
private static final String Species_group = "Species_group";
public static final String Species = "Species";
private static final String Subspecies = "Subspecies";
private final BitSet majorRanks = new BitSet();
private static TaxonomicLevels instance;
/**
* get instance
*
* @return instance
*/
private static TaxonomicLevels getInstance() {
if (instance == null)
instance = new TaxonomicLevels();
return instance;
}
/**
* constructor
*/
private TaxonomicLevels() {
name2id = new HashMap<>();
id2name = new HashMap<>();
// add all defined levels here:
// addLevel((byte)0 ,"No rank");
addLevel(127, Domain);
majorRanks.set(127);
addLevel(1, Kingdom);
majorRanks.set(1); // don't use this because it will cause kingdoms to be filled in
addLevel(2, Phylum);
majorRanks.set(2);
addLevel(3, Class);
majorRanks.set(3);
addLevel(4, Order);
majorRanks.set(4);
addLevel(5, Family);
majorRanks.set(5);
addLevel(90, Varietas);
addLevel(98, Genus);
majorRanks.set(98);
addLevel(99, Species_group);
addLevel(100, Species);
majorRanks.set(100);
addLevel(101, Subspecies);
}
/**
* is this a major KPCOFGS rank?
*
* @return true, if major
*/
public static boolean isMajorRank(int rank) {
return getInstance().majorRanks.get(rank);
}
/**
* get the next major rank
*
* @return next major rank
*/
public static int getNextRank(int rank) {
if (rank == 100)
return 0;
if (rank == 127)
return 1;
int nextRank = getInstance().majorRanks.nextSetBit(rank + 1);
return Math.max(nextRank, 0)
;
}
/**
* get rank from one letter code
*
* @return level
*/
public static int getRankForOneLetterCode(String oneLetterLabel) {
return switch (oneLetterLabel.toLowerCase()) {
case "d" -> getId(Domain);
case "p" -> getId(Phylum);
case "c" -> getId(Class);
case "o" -> getId(Order);
case "f" -> getId(Family);
case "g" -> getId(Genus);
case "s" -> getId(Species);
default -> 0;
};
}
/**
* get one letter code for rank, or null
*
* @return code or null
*/
public static String getOneLetterCodeFromRank(int rank) {
if (isMajorRank(rank)) {
for (String name : getAllMajorRanks()) {
if (getId(name) == rank)
return name.substring(0, 1).toLowerCase();
}
}
return null;
}
/* used to set up table
*/
private void addLevel(Integer level, String name) {
name2id.put(name, level);
id2name.put(level, name);
names.add(name);
}
/**
* given a level name, returns the id
*
* @return level id or null
*/
public static Integer getId(String name) {
Integer value = TaxonomicLevels.getInstance().name2id.get(name);
return value == null ? 0 : value;
}
/**
* given a level id, returns its name
*
* @return name
*/
public static String getName(int id) {
return TaxonomicLevels.getInstance().id2name.get(id);
}
/**
* get all names
*
* @return names
*/
public static List<String> getAllNames() {
return TaxonomicLevels.getInstance().names;
}
/**
* get all names of major ranks
*
* @return names
*/
public static List<String> getAllMajorRanks() {
ArrayList<String> list = new ArrayList<>();
for (String name : TaxonomicLevels.getInstance().names) {
if (isMajorRank(getId(name)))
list.add(name);
}
return list;
}
public static int getSpeciesId() {
return getId(Species);
}
public static int getSubspeciesId() {
return getId(Subspecies);
}
public static int getGenusId() {
return getId(Genus);
}
}
| 5,797 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
TaxonomyData.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/TaxonomyData.java | /*
* TaxonomyData.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer;
import jloda.graph.Edge;
import jloda.graph.Node;
import megan.algorithms.LCAAddressing;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.classification.IdMapper;
import megan.classification.data.ClassificationFullTree;
import megan.classification.data.Name2IdMap;
import java.util.*;
/**
* maintains static access to the taxonomy
* Daniel Huson, 4.2015
*/
public class TaxonomyData {
public static final int ROOT_ID =1;
public static final int BACTERIA_ID = 2;
public static final int VIRUSES_ID = 10239;
private static Classification taxonomyClassification;
/**
* explicitly load the taxonomy classification
*/
public static void load() {
setTaxonomyClassification(ClassificationManager.get(Classification.Taxonomy, true));
}
/**
* set the taxonomy classification
*
*/
public static void setTaxonomyClassification(Classification taxonomyClassification) {
TaxonomyData.taxonomyClassification = taxonomyClassification;
}
/**
* gets the taxonomy names to ids
*
* @return taxonomy names to ids
*/
public static Name2IdMap getName2IdMap() {
return taxonomyClassification.getIdMapper().getName2IdMap();
}
/**
* gets the taxonomy tree
*
* @return tree
*/
public static ClassificationFullTree getTree() {
return taxonomyClassification.getFullTree();
}
/**
* is taxonomy data available?
*
* @return true, if available
*/
public static boolean isAvailable() {
return taxonomyClassification != null;
}
/**
* is this taxon, or one of its ancestors, disabled? Taxa that are disabled are ignored by LCA algorithm
*
* @return true, if disabled
*/
public static boolean isTaxonDisabled(String cName, Integer taxonId) {
return cName.equals(Classification.Taxonomy) && (taxonId == null || (taxonId > 0 && taxonomyClassification.getIdMapper().getDisabledIds().contains(taxonId)));
}
/**
* is this taxon, or one of its ancestors, disabled? Taxa that are disabled are ignored by LCA algorithm
*
* @return true, if disabled
*/
public static boolean isTaxonDisabled(Integer taxonId) {
return taxonId == null || (taxonId > 0 && taxonomyClassification.getIdMapper().getDisabledIds().contains(taxonId));
}
/**
* get all currently disabled taxa. Note that any taxon below a disabled taxon is also considered disabled
*
* @return all disabled taxa
*/
public static Set<Integer> getDisabledTaxa() {
if (taxonomyClassification == null)
load();
return taxonomyClassification.getIdMapper().getDisabledIds();
}
public static int getTaxonomicRank(Integer id) {
return taxonomyClassification.getIdMapper().getName2IdMap().getRank(id);
}
public static void setTaxonomicRank(Integer id, byte rank) {
taxonomyClassification.getIdMapper().getName2IdMap().setRank(id, rank);
}
/**
* gets the closest ancestor that has a major rank
*
* @return rank of this node, if is major, otherwise of closest ancestor
*/
public static int getLowestAncestorWithMajorRank(Integer id) {
if (id <= 0)
return id;
while (true) {
var rank = getTaxonomicRank(id);
if (TaxonomicLevels.isMajorRank(rank))
return id;
var address = getAddress(id);
if (address == null || address.isEmpty())
return 1;
address = address.substring(0, address.length() - 1);
if (address.isEmpty())
return 1;
id = getAddress2Id(address);
if (id <= 0)
return 1;
}
}
/**
* gets the ancestor at the given rank, or 0
*/
public static int getAncestorAtGivenRank(Integer id,int rank) {
while (id>0) {
if(getTaxonomicRank(id)==rank)
return id;
var address = getAddress(id);
if (address == null || address.isEmpty())
return 0;
do {
address = address.substring(0, address.length() - 1);
if (address.isEmpty())
return 0;
id = getAddress2Id(address);
}
while(id==0);
}
return 0;
}
public static String getAddress(Integer id) {
return taxonomyClassification.getFullTree().getAddress(id);
}
public static Integer getAddress2Id(String address) {
return taxonomyClassification.getFullTree().getAddress2Id(address);
}
public static boolean isAncestor(int higherTaxonId, int lowerTaxonId) {
var higherAddress = getAddress(higherTaxonId);
var lowerAddress = getAddress(lowerTaxonId);
return higherAddress != null && (lowerAddress == null || lowerAddress.startsWith(higherAddress));
}
/**
* returns the LCA of a set of taxon ids
*
* @return id
*/
public static int getLCA(Set<Integer> taxonIds, boolean removeAncestors) {
if (taxonIds.isEmpty())
return IdMapper.NOHITS_ID;
var addresses = new HashSet<String>();
var countKnownTaxa = 0;
// compute addresses of all hit taxa:
for (var taxonId : taxonIds) {
if (taxonId > 0 && !isTaxonDisabled(taxonId)) {
var address = getAddress(taxonId);
if (address != null) {
addresses.add(address);
countKnownTaxa++;
}
}
}
// compute LCA using addresses:
if (countKnownTaxa > 0) {
var address = LCAAddressing.getCommonPrefix(addresses, removeAncestors);
return getAddress2Id(address);
}
// although we had some hits, couldn't make an assignment
return IdMapper.UNASSIGNED_ID;
}
/**
* get the path string associated with a taxon
*
* @return path string or null
*/
public static String getPath(int taxId, boolean majorRanksOnly) {
var expectedPath = "DKPCOFGS";
var expectedIndex = 0;
final var v = taxonomyClassification.getFullTree().getANode(taxId);
if (v != null) {
var path = new LinkedList<Node>();
{
var w = v;
while (true) {
if (!majorRanksOnly || TaxonomicLevels.isMajorRank(taxonomyClassification.getId2Rank().get((Integer) w.getInfo())))
path.push(w);
if (w.getInDegree() > 0)
w = w.getFirstInEdge().getSource();
else
break;
}
}
var buf = new StringBuilder();
for (var w : path) {
var id = (Integer) w.getInfo();
if (id != null) {
if (majorRanksOnly) {
var letters = TaxonomicLevels.getName(taxonomyClassification.getId2Rank().get((Integer) w.getInfo()));
var key = Character.toUpperCase(letters.charAt(0));
while (expectedIndex < expectedPath.length() && key != expectedPath.charAt(expectedIndex)) {
var missing = expectedPath.charAt(expectedIndex);
if (missing != 'K') {
if (!buf.isEmpty())
buf.append(" ");
buf.append("[").append(missing == 'D' ? "D" : missing).append("] unknown;");
}
expectedIndex++;
}
expectedIndex++;
letters = letters.substring(0, 1);
if (!buf.isEmpty())
buf.append(" ");
buf.append("[").append(letters).append("] ").append(taxonomyClassification.getName2IdMap().get(id)).append(";");
} else {
if (!buf.isEmpty())
buf.append(" ");
buf.append(taxonomyClassification.getName2IdMap().get(id)).append(";");
}
}
}
return buf.toString();
} else
return null;
}
/**
* gets the path, or id, if path not found
*
* @return path or id
*/
public static String getPathOrId(int taxId, boolean majorRanksOnly) {
var path = getPath(taxId, majorRanksOnly);
return path != null ? path : "" + taxId;
}
/**
* set total set of disabled nodes from a set of disabled nodes. This is used to set all disabled node from
* the representation saved in the preferrences file
*
*/
public static void setDisabledInternalTaxa(Set<Integer> internal) {
var root = taxonomyClassification.getFullTree().getRoot();
if (root != null)
setDisabledInternalTaxaRec(root, internal, internal.contains((Integer) root.getInfo()));
}
/**
* recursively does the work
*
*/
private static void setDisabledInternalTaxaRec(final Node v, final Set<Integer> internalDisabledIds, boolean disable) {
final var id = (int) v.getInfo();
if (!disable && internalDisabledIds.contains(id))
disable = true;
if (disable)
taxonomyClassification.getIdMapper().getDisabledIds().add(id);
else
taxonomyClassification.getIdMapper().getDisabledIds().remove(id);
for(var e:v.outEdges()) {
setDisabledInternalTaxaRec(e.getTarget(), internalDisabledIds, disable);
}
}
/**
* gets the disabled internal nodes. This generates the set that is saved to the preferences file
*
* @return disabled internal nodes
*/
public static Set<Integer> getDisabledInternalTaxa() {
var internalDisabledIds = new TreeSet<Integer>();
var root = getTree().getRoot();
if (root != null)
getDisabledFromInternalTaxaRec(root, internalDisabledIds);
return internalDisabledIds;
}
/**
* recursively does the work
*
*/
private static void getDisabledFromInternalTaxaRec(Node v, Set<Integer> internalDisabledIds) {
var id = (int) v.getInfo();
if (taxonomyClassification.getIdMapper().getDisabledIds().contains(id)) {
internalDisabledIds.add(id);
} else {
for(var e:v.outEdges()) {
getDisabledFromInternalTaxaRec(e.getTarget(), internalDisabledIds);
}
}
}
/**
* ensures that the disabled taxa have been initialized
*/
public static void ensureDisabledTaxaInitialized() {
if (getDisabledTaxa().isEmpty() && !getDisabledInternalTaxa().isEmpty())
TaxonomyData.setDisabledInternalTaxa(getDisabledInternalTaxa());
}
public static Collection<Integer> getNonProkaryotesToCollapse() {
var root = taxonomyClassification.getFullTree().getRoot();
var ids2collapse = new ArrayList<Integer>();
for(var e:root.outEdges()) {
var w = e.getTarget();
var id = (Integer) w.getInfo();
if (id != 131567 && id != 2 && id != 2157)// cellular organisms
ids2collapse.add(id);
}
ids2collapse.add(2759); // eukaryotes
return ids2collapse;
}
public static Collection<Integer> getNonEukaryotesToCollapse() {
var root = taxonomyClassification.getFullTree().getRoot();
var ids2collapse = new ArrayList<Integer>();
for(var e:root.outEdges()) {
var w = e.getTarget();
var id = (Integer) w.getInfo();
if (id != 131567)// cellular organisms
ids2collapse.add(id);
}
ids2collapse.add(2); // bacteria
ids2collapse.add(2157); // archaea
return ids2collapse;
}
public static Collection<Integer> getNonVirusesToCollapse() {
var root = taxonomyClassification.getFullTree().getRoot();
var ids2collapse = new ArrayList<Integer>();
for(var e:root.outEdges()) {
var w = e.getTarget();
var id = (Integer) w.getInfo();
if (id != 10239 && id != 12884)// viruses or viroids
ids2collapse.add(id);
}
return ids2collapse;
}
}
| 13,469 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ColorGradient.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/gui/ColorGradient.java | /*
* ColorGradient.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.gui;
import jloda.swing.util.ColorTable;
import java.awt.*;
/**
* Color gradient
* Daniel Huson, 5.2017
*/
public class ColorGradient {
static private final Color separatorColor = new Color(200, 255, 200);
private final ColorTable colorTable;
private final int maxCount;
private final double inverseLogCount;
private final double inverseSqrtCount;
/**
* constructor
*
*/
public ColorGradient(ColorTable colorTable, int maxCount) {
this.colorTable = colorTable;
this.maxCount = maxCount;
inverseLogCount = 1.0 / Math.log(maxCount + 1);
if (maxCount > 0)
inverseSqrtCount = 1.0 / Math.sqrt(maxCount);
else
inverseSqrtCount = 1;
}
/**
* get color on linear scale
*
* @return color
*/
public Color getColor(int count) {
if (maxCount == 0)
return Color.WHITE;
return colorTable.getColor(count, maxCount);
}
/**
* get sqrt scale color
*
* @return color
*/
public Color getColorSqrtScale(int count) {
if (maxCount == 0)
return Color.WHITE;
return colorTable.getColorSqrtScale(count, inverseSqrtCount);
}
/**
* get color on log scale
*
* @return color
*/
public Color getColorLogScale(int count) {
if (maxCount == 0)
return Color.WHITE;
return colorTable.getColorLogScale(count, inverseLogCount);
}
/**
* gets the max count
*
* @return max count
*/
public int getMaxCount() {
return maxCount;
}
/**
* get border color used to separate different regions
*
* @return separator color
*/
public Color getSeparatorColor() {
return separatorColor;
}
}
| 2,650 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
GreenGradient.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/gui/GreenGradient.java | /*
* GreenGradient.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.gui;
import java.awt.*;
/**
* a green color gradient
* Daniel Huson, 10.2010
*/
public class GreenGradient {
static private final Color separatorColor = new Color(200, 255, 200);
private final int maxCount;
private final double factor;
/**
* setup the green gradient
*
*/
public GreenGradient(int maxCount) {
this.maxCount = maxCount;
factor = maxCount / Math.log(maxCount);
}
/**
* get color on linear scale
*
* @return color
*/
private Color getColor(int count) {
if (maxCount == 0)
return Color.WHITE;
if (count > maxCount)
count = maxCount;
int scaled = Math.min(255, (int) Math.round(255.0 / maxCount * count));
if (count > 0)
scaled = Math.max(1, scaled);
return new Color(255 - scaled, 255, 255 - scaled);
}
/**
* get color on log scale
*
* @return color
*/
public Color getLogColor(int count) {
int value = (int) Math.max(0, (Math.round(factor * Math.log(count))));
if (count > 0)
value = Math.max(1, value);
return getColor(value);
}
/**
* get border color used to separate different regions
*
* @return separator color
*/
public static Color getSeparatorColor() {
return separatorColor;
}
/**
* gets the max count
*
* @return max count
*/
public int getMaxCount() {
return maxCount;
}
/**
* this is used in the node drawer of the main viewer
*
* @return color on a log scale
*/
public static Color getColorLogScale(int count, double inverseLogMaxReads) {
int value = (count <= 0 ? 0 : Math.min(255, Math.max(1, (int) Math.round(255.0 * Math.log(count + 1) * inverseLogMaxReads))));
if (count > 0 && value < 1)
value = 1;
return new Color(255 - value, 255, 255 - value);
}
/**
* this is used in the node drawer of the main viewer
*
* @return color on a log scale
*/
public static Color getColorSqrtScale(int count, double inverseSqrtMaxReads) {
int value = (count <= 0 ? 0 : Math.min(255, Math.max(1, (int) Math.round(255.0 * Math.sqrt(count) * inverseSqrtMaxReads))));
if (count > 0 && value < 1)
value = 1;
return new Color(255 - value, 255, 255 - value);
}
/**
* get color on linear scale
*
* @return color
*/
public static Color getColor(int count, int maxCount) {
int value = (count <= 0 ? 0 : Math.min(255, Math.max(1, (int) Math.round(255.0 * count / (double) maxCount))));
if (count > 0 && value < 1)
value = 1;
return new Color(255 - value, 255, 255 - value);
}
}
| 3,638 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SpiralNode8.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/gui/SpiralNode8.java | /*
* SpiralNode8.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.gui;
import jloda.swing.util.Geometry;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.util.ArrayList;
public class SpiralNode8 extends JPanel {
public void paintComponent(Graphics gc) {
float[] values = {1.0f, 1.0f, 1.0f, 0.8f, 0, 1.0f, 1.0f, 1.0f, 0.8f, 0, 0, 0, 0, 0, 0, 0.7f, 0.7f, 0.6f, 0.6f, 0.3f, 0.1f, 0.01f, 0f, 0.7f, 0.6f, 0.6f, 0.3f, 0f};
ArrayList<Float> sorted = new ArrayList<>();
for (float f : values)
sorted.add(f);
sorted.sort((a, b) -> -a.compareTo(b));
final int nodeHeight = 200;
final int nodeWidth = 200;
final int centerX = (getSize().width - nodeHeight) / 2;
final int centerY = (getSize().height - nodeHeight) / 2;
final int minX = centerX - nodeWidth / 2;
final int minY = centerY - nodeHeight / 2;
gc.setColor(Color.LIGHT_GRAY);
gc.fillArc(minX - 1, minY - 1, nodeWidth + 2, nodeHeight + 2, 0, 360);
{
final int steps = Math.min(36, sorted.size());
final int add = Math.max(1, sorted.size() / steps);
final float max = sorted.get(0);
final double scale = 0.5 * (max > 0 ? 1.0 / max : 1);
GeneralPath.Float gp = new GeneralPath.Float();
gp.moveTo(centerX, minY);
final double radius = 0.5 * nodeHeight;
final double delta = 2 * Math.PI / steps;
for (int i = 0; i < steps; i += add) {
double angle = Math.PI + i * delta;
double dist = radius * (1 - scale * sorted.get(i));
Point2D apt = Geometry.rotate(new Point2D.Double(0, dist), angle);
gp.lineTo(centerX + apt.getX(), centerY + apt.getY());
}
gp.closePath();
gc.setColor(Color.WHITE);
((Graphics2D) gc).fill(gp);
}
gc.setColor(Color.BLACK);
gc.drawArc(minX - 1, minY - 1, nodeWidth + 2, nodeHeight + 2, 0, 360);
}
public static void main(String[] args) {
SpiralNode8 panel = new SpiralNode8();
JFrame application = new JFrame();
application.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(300, 300);
application.setVisible(true);
}
} | 3,204 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
NodeDrawer.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/gui/NodeDrawer.java | /*
* NodeDrawer.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.gui;
import jloda.graph.Node;
import jloda.graph.NodeData;
import jloda.swing.graphview.GraphView;
import jloda.swing.graphview.INodeDrawer;
import jloda.swing.graphview.NodeView;
import jloda.swing.util.ProgramProperties;
import jloda.util.NodeShape;
import jloda.util.Statistics;
import megan.core.Document;
import megan.main.MeganProperties;
import megan.util.ScalingType;
import megan.viewer.MainViewer;
import java.awt.*;
import java.awt.geom.Arc2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* node drawer for multi-sample nodes
* Daniel Huson, 2.2012
*/
public class NodeDrawer implements INodeDrawer {
static public Color pvalueColor = ProgramProperties.get(MeganProperties.PVALUE_COLOR, Color.CYAN);
private static final Font selectionFont = ProgramProperties.get("selectionFont", Font.decode("Helvetica-PLAIN-11"));
public enum Style {
Circle,
PieChart,
BarChart,
HeatMap,
CoxComb
}
public enum ScaleBy {
Summarized,
Assigned,
None
}
private Graphics2D gc;
private final GraphView viewer;
private final Document doc;
private Style style = Style.Circle;
private ScaleBy scaleBy = ScaleBy.Assigned;
private boolean drawLeavesOnly = false;
private int maxNodeHeight = 20;
private double maxTotalCount = 0;
private double maxSingleCount = 0;
private double maxValue = 0;
private ScalingType scalingType = ScalingType.SQRT;
private double linearFactor = 1; // multiple count by this to get radius for linear scaling
private double sqrtFactor = 1; // multiple count by this to get radius for sqrt scaling
private double logFactor = 1; // multiple count by this to get radius for log scaling
private double inverseLogMaxCount = 1;
private double inverseSqrtMaxCount = 1;
/**
* constructor
*
*/
public NodeDrawer(Document doc, GraphView viewer) {
this.viewer = viewer;
this.doc = doc;
}
/**
* setup data
*
*/
public void setup(GraphView graphView, Graphics2D gc) {
this.gc = gc;
}
/**
* get the Node style
*
* @return node style
*/
public Style getStyle() {
return style;
}
/**
* set the node style
*
*/
public void setStyle(Style style) {
this.style = style;
switch (style) {
case PieChart, Circle -> maxValue = maxTotalCount;
case CoxComb, BarChart, HeatMap -> maxValue = maxSingleCount;
}
this.linearFactor = (maxValue > 0 ? maxNodeHeight / maxValue : 0);
this.sqrtFactor = (maxValue > 0 ? maxNodeHeight / Math.sqrt(maxValue) : 0);
this.logFactor = (maxValue > 0 ? maxNodeHeight / Math.log(maxValue) : 0);
inverseLogMaxCount = (maxValue > 0 ? 1.0 / Math.log(maxValue) : 0);
inverseSqrtMaxCount = (maxValue > 0 ? 1.0 / Math.sqrt(maxValue) : 0);
}
public void setStyle(String styleName, Style defaultValue) {
Style style = null;
if (styleName != null) {
for (Style aStyle : Style.values()) {
if (styleName.equalsIgnoreCase(aStyle.toString())) {
style = aStyle;
break;
}
}
}
if (style == null)
setStyle(defaultValue);
else
setStyle(style);
}
public ScalingType getScalingType() {
return scalingType;
}
public void setScalingType(ScalingType scalingType) {
this.scalingType = scalingType;
}
/**
* set the max single account and max total node count
*
*/
public void setCounts(double[] maxSingleCountAndMaxTotalCount) {
this.maxSingleCount = maxSingleCountAndMaxTotalCount[0];
this.maxTotalCount = maxSingleCountAndMaxTotalCount[1];
setStyle(getStyle()); // trigger rescan
}
public double getMaxSingleCount() {
return maxSingleCount;
}
public double getMaxTotalCount() {
return maxTotalCount;
}
public double getMaxValue() {
return maxValue;
}
public int getMaxNodeHeight() {
return maxNodeHeight;
}
public void setMaxNodeHeight(int maxNodeHeight) {
this.maxNodeHeight = maxNodeHeight;
setStyle(getStyle()); // trigger rescan
}
/**
* gets size at which the value should be drawn
*
* @return scaled size
*/
public double getScaledSize(double value) {
if (value > maxValue)
value = maxValue;
return switch (scalingType) {
default /* case LINEAR */ -> value * linearFactor;
case SQRT -> Math.sqrt(value) * sqrtFactor;
case LOG -> Math.log(value) * logFactor;
};
}
/**
* draw the node
*
*/
public void draw(Node v, boolean selected) {
final NodeView nv = viewer.getNV(v);
final NodeData data = (NodeData) v.getData();
if (selected)
hilite(v);
if ((!drawLeavesOnly || v.getOutDegree() == 0) && scaleBy != ScaleBy.None && nv.getNodeShape() != NodeShape.None) {
switch (style) {
case HeatMap -> drawAsHeatMap(v, nv, data);
case BarChart -> drawAsBarChart(v, nv, data);
case PieChart -> {
drawAsCircle(v, nv, data);
drawAsPieChart(v, nv, data);
}
case CoxComb -> drawAsCoxComb(v, nv, data);
case Circle -> drawAsCircle(v, nv, data);
}
} else {
nv.setNodeShape(NodeShape.None);
}
}
/**
* hilite the node
*
*/
private void hilite(Node v) {
NodeView nv = viewer.getNV(v);
if (nv.getLocation() == null)
return;
{
int scaledWidth;
int scaledHeight;
if (nv.getNodeShape() == NodeShape.None) {
scaledWidth = scaledHeight = 2;
} else {
if (nv.getFixedSize()) {
scaledWidth = nv.getWidth();
scaledHeight = nv.getHeight();
} else {
scaledWidth = NodeView.computeScaledWidth(viewer.trans, nv.getWidth());
scaledHeight = NodeView.computeScaledHeight(viewer.trans, nv.getHeight());
}
}
Point apt = viewer.trans.w2d(nv.getLocation());
apt.x -= (scaledWidth / 2);
apt.y -= (scaledHeight / 2);
gc.setColor(ProgramProperties.SELECTION_COLOR);
Shape shape = new Rectangle(apt.x - 2, apt.y - 2, scaledWidth + 4, scaledHeight + 4);
gc.fill(shape);
gc.setColor(ProgramProperties.SELECTION_COLOR_DARKER);
final Stroke oldStroke = gc.getStroke();
gc.setStroke(NodeView.NORMAL_STROKE);
gc.draw(shape);
gc.setStroke(oldStroke);
}
}
/**
* hilite the node label
*
*/
private void hiliteLabel(Node v, NodeData data) {
NodeView nv = viewer.getNV(v);
if (nv.getLocation() == null)
return;
Point apt = nv.getLabelPosition(viewer.trans);
if (apt == null)
return;
gc.setColor(ProgramProperties.SELECTION_COLOR_ADDITIONAL_TEXT);
if (!nv.getLabelVisible() && nv.getLabel() != null) {
gc.setFont(nv.getFont());
gc.drawString(nv.getLabel(), apt.x, apt.y);
}
if ((data.getSummarized().length > 1 || (data.getSummarized().length == 1 && data.getSummarized()[0] > 0))) {
gc.setFont(selectionFont);
StringBuilder buf = new StringBuilder();
if (data.getCountAssigned() > 0) {
buf.append("Assigned=");
if (data.getAssigned().length < 50) {
for (float value : data.getAssigned()) {
buf.append(String.format("%,d ", Math.round(value)));
}
} else {
final Statistics statistics = new Statistics(data.getAssigned());
final int mean = (int) Math.round(statistics.getMean());
if (mean <= 1)
buf.append(String.format(" %,d - %,d", Math.round(statistics.getMin()), Math.round(statistics.getMax())));
else
buf.append(String.format(" %,d - %,d (mean: %,d sd: %,d)", Math.round(statistics.getMin()), Math.round(statistics.getMax()), mean, Math.round(statistics.getStdDev())));
}
gc.drawString(buf.toString(), apt.x, apt.y += 14);
}
buf = new StringBuilder();
buf.append("Summed=");
if (data.getSummarized().length < 50) {
for (float value : data.getSummarized()) {
buf.append(String.format("%,.0f ", value));
}
} else {
final Statistics statistics = new Statistics(data.getSummarized());
final int mean = (int) Math.round(statistics.getMean());
if (mean <= 1)
buf.append(String.format(" %,d - %,d", Math.round(statistics.getMin()), Math.round(statistics.getMax())));
else
buf.append(String.format(" %,d - %,d (mean: %,d sd: %,d)", Math.round(statistics.getMin()), Math.round(statistics.getMax()), mean, Math.round(statistics.getStdDev())));
}
gc.drawString(buf.toString(), apt.x, apt.y += 12);
}
if (data.getUpPValue() != -1) {
gc.drawString("UPv=" + (float) data.getUpPValue(), apt.x, apt.y += 12);
}
if (data.getDownPValue() != -1) {
gc.drawString("DPv=" + (float) data.getDownPValue(), apt.x, apt.y += 12);
}
}
/**
* draw the label of the node
*
*/
public void drawLabel(Node v, boolean selected) {
viewer.getNV(v).drawLabel(gc, viewer.trans, viewer.getFont(), selected);
if (selected)
hiliteLabel(v, (NodeData) v.getData());
}
/**
* draw the node and the label
*
*/
public void drawNodeAndLabel(Node v, boolean selected) {
draw(v, selected);
drawLabel(v, selected);
}
/**
* draw node as a scaled circle
*
*/
private void drawAsCircle(Node v, NodeView nv, NodeData data) {
Point2D location = nv.getLocation();
if (location == null)
return; // no location, don't draw
nv.setNodeShape(NodeShape.Oval);
float num;
if (scaleBy == ScaleBy.Summarized || v.getOutDegree() == 0)
num = data.getCountSummarized();
else
num = data.getCountAssigned();
if (num > 0) {
int radius = (int) Math.max(1.0, getScaledSize(num));
nv.setHeight((2 * radius));
nv.setWidth((2 * radius));
} else {
nv.setWidth(1);
nv.setHeight(1);
}
if (data.getUpPValue() >= 0 || data.getDownPValue() >= 0) {
int width = nv.getWidth();
int height = nv.getHeight();
Point apt = viewer.trans.w2d(location);
apt.x -= (width /2);
apt.y -= (height/2);
if (data.getUpPValue() >= 0) {
gc.setColor(pvalueColor);
Stroke oldStroke = gc.getStroke();
int leftWidth = getWidthForPValue(data.getUpPValue());
gc.setStroke(new BasicStroke(leftWidth));
gc.drawArc(apt.x - (leftWidth /2) - 1, apt.y - (leftWidth / 2) - 1, width + leftWidth + 1, height + leftWidth + 1, 90, 180);
gc.setStroke(oldStroke);
}
if (data.getDownPValue() >= 0) {
gc.setColor(pvalueColor);
Stroke oldStroke = gc.getStroke();
int rightWidth = getWidthForPValue(data.getDownPValue());
gc.setStroke(new BasicStroke(rightWidth));
gc.drawArc(apt.x - (rightWidth / 2) - 1, apt.y - (rightWidth / 2) - 1, width + rightWidth + 1, height + rightWidth + 1, 270, 180);
gc.setStroke(oldStroke);
}
}
nv.draw(gc, viewer.trans);
}
/**
* draw as Cox comb
*
*/
private void drawAsCoxComb(Node v, NodeView nv, NodeData data) {
Point2D location = nv.getLocation();
if (location == null)
return; // no location, don't draw
Point apt = viewer.trans.w2d(location);
nv.setNodeShape(NodeShape.Oval);
final float[] values;
if (scaleBy == ScaleBy.Summarized || v.getOutDegree() == 0) // must be collapsed node
{
values = data.getSummarized();
} else {
values = data.getAssigned();
}
double delta = 360.0 / values.length;
int maxRadius = 0;
for (int i = 0; i < values.length; i++) {
double radius = Math.max(1.0, getScaledSize(values[i]));
// double radius = Math.sqrt((double)assigned[i] / count) *viewer.getMaxNodeRadius(); // we assume here that the largest value is 50% of total reads
maxRadius = Math.max(maxRadius, (int) radius);
Arc2D arc = new Arc2D.Double(apt.x - radius, apt.y - radius, 2 * radius, 2 * radius, i * delta + 45, delta, Arc2D.PIE);
gc.setColor(doc.getColorByIndex(i));
gc.fill(arc);
//gc.drawString(""+array[i],apt.x+30,apt.y+(i+1)*20);
if (values.length < 120)
gc.setColor(Color.GRAY);
gc.draw(arc);
}
if (data.getUpPValue() >= 0) {
gc.setColor(pvalueColor);
Stroke oldStroke = gc.getStroke();
int leftWidth = getWidthForPValue(data.getUpPValue());
gc.setStroke(new BasicStroke(leftWidth));
gc.drawArc(apt.x - maxRadius, apt.y - maxRadius, 2 * maxRadius + 2, 2 * maxRadius + 2, 90, 180);
gc.setStroke(oldStroke);
}
if (data.getDownPValue() >= 0) {
gc.setColor(pvalueColor);
Stroke oldStroke = gc.getStroke();
int rightWidth = getWidthForPValue(data.getDownPValue());
gc.setStroke(new BasicStroke(rightWidth));
gc.drawArc(apt.x - maxRadius, apt.y - maxRadius, 2 * maxRadius + 2, 2 * maxRadius + 2, 270, 180);
gc.setStroke(oldStroke);
}
nv.setWidth(Math.max(1, 2 * maxRadius));
nv.setHeight(Math.max(1, 2 * maxRadius));
}
/**
* draw as a pie chart
*
*/
private void drawAsPieChart(Node v, NodeView nv, NodeData data) {
Point2D location = nv.getLocation();
if (location == null)
return; // no location, don't draw
Point apt = viewer.trans.w2d(location);
int width = nv.getWidth();
int height = nv.getHeight();
apt.x -= (width / 2);
apt.y -= (height / 2);
nv.setNodeShape(NodeShape.Oval);
if (data.getUpPValue() >= 0) {
gc.setColor(pvalueColor);
Stroke oldStroke = gc.getStroke();
int leftWidth = getWidthForPValue(data.getUpPValue());
gc.setStroke(new BasicStroke(leftWidth));
gc.drawArc(apt.x - (leftWidth / 2) - 1, apt.y - (leftWidth / 2) - 1, width + leftWidth + 1, height + leftWidth + 1, 90, 180);
gc.setStroke(oldStroke);
}
if (data.getDownPValue() >= 0) {
gc.setColor(pvalueColor);
Stroke oldStroke = gc.getStroke();
int rightWidth = getWidthForPValue(data.getDownPValue());
gc.setStroke(new BasicStroke(rightWidth));
gc.drawArc(apt.x - (rightWidth / 2) - 1, apt.y - (rightWidth / 2) - 1, width + rightWidth + 1, height + rightWidth + 1, 270, 180);
gc.setStroke(oldStroke);
}
final double count;
final float[] array;
if (scaleBy == ScaleBy.Summarized || v.getOutDegree() == 0) // must be collapsed node
{
count = data.getCountSummarized();
array = data.getSummarized();
} else {
count = data.getCountAssigned();
array = data.getAssigned();
}
if (count > 0) {
//gc.drawString(""+count,apt.x+30,apt.y);
double delta = 360.0 / count;
double oldAngle = 0;
int total = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] > 0) {
total += array[i];
double newAngle = total * delta;
Arc2D arc = new Arc2D.Double(apt.x, apt.y, width, height, oldAngle, newAngle - oldAngle, Arc2D.PIE);
gc.setColor(doc.getColorByIndex(i));
gc.fill(arc);
//gc.drawString(""+array[i],apt.x+30,apt.y+(i+1)*20);
if (array.length < 120)
gc.setColor(Color.GRAY);
gc.draw(arc);
oldAngle = newAngle;
}
}
gc.setColor(Color.GRAY);
gc.drawOval(apt.x, apt.y, width, height);
} else
gc.drawOval(apt.x, apt.y, width, height);
}
/**
* draw as a heat map
*
*/
private void drawAsHeatMap(Node v, NodeView nv, NodeData data) {
final double count;
final float[] array;
if (scaleBy == ScaleBy.Summarized || v.getOutDegree() == 0 && data.getCountSummarized() > data.getCountAssigned()) // must be collapsed node
{
count = data.getCountSummarized();
array = data.getSummarized();
} else {
count = data.getCountAssigned();
array = data.getAssigned();
}
Point2D location = nv.getLocation();
Rectangle box = new Rectangle();
viewer.trans.w2d(new Rectangle(0, 0, MainViewer.XSTEP, MainViewer.YSTEP), box);
int width;
if (array.length <= 1)
width = 30;
else
width = (int) (30.0 / array.length * (Math.sqrt(array.length)));
box.setRect(box.x, box.y, width, Math.min(2 * maxNodeHeight, box.height));
if (location == null)
return; // no location, don't draw
Point apt = viewer.trans.w2d(location);
if (v.getOutDegree() == 0 || count > 0) {
nv.setNodeShape(NodeShape.Rectangle);
nv.setWidth((int) Math.round(data.getAssigned().length * box.getWidth()));
nv.setHeight((int) Math.round(box.getHeight()));
} else {
nv.setNodeShape(NodeShape.Oval);
nv.setWidth(1);
nv.setHeight(1);
}
apt.x -= nv.getWidth() / 2; // offset
apt.y -= box.getHeight() / 2 - 1;
if (data.getUpPValue() >= 0) {
gc.setColor(pvalueColor);
Stroke oldStroke = gc.getStroke();
int leftWidth = getWidthForPValue(data.getUpPValue());
gc.setStroke(new BasicStroke(leftWidth));
gc.drawLine(apt.x - 1, apt.y,
apt.x - 1, apt.y + nv.getHeight());
gc.setStroke(oldStroke);
}
if (data.getDownPValue() >= 0) {
gc.setColor(pvalueColor);
Stroke oldStroke = gc.getStroke();
int rightWidth = getWidthForPValue(data.getDownPValue());
gc.setStroke(new BasicStroke(rightWidth));
gc.drawLine(apt.x + nv.getWidth() + 1, apt.y,
apt.x + nv.getWidth() + 1, apt.y + nv.getHeight());
gc.setStroke(oldStroke);
}
//gc.drawString(""+count,apt.x+30,apt.y);
if (v.getOutDegree() == 0 || count > 0) {
for (int i = 0; i < array.length; i++) {
Color color = switch (scalingType) {
default /* case LINEAR */ -> doc.getChartColorManager().getHeatMapTable().getColor((int) array[i], (int) maxValue);
case SQRT -> doc.getChartColorManager().getHeatMapTable().getColorSqrtScale((int) array[i], inverseSqrtMaxCount);
case LOG -> doc.getChartColorManager().getHeatMapTable().getColorLogScale((int) array[i], inverseLogMaxCount);
};
gc.setColor(color);
// gc.setColor(getLogScaleColor(COLORS[i % COLORS.length], array[i], inverseLogTotalReads));
double aWidth = Math.max(0.2, box.getWidth());
gc.fill(new Rectangle2D.Double(apt.x + i * box.getWidth(), apt.y, aWidth, box.getHeight()));
if (box.getWidth() > 1) {
gc.setColor(Color.DARK_GRAY);
gc.draw(new Rectangle2D.Double(apt.x + i * box.getWidth(), apt.y, box.getWidth(), box.getHeight()));
}
}
if (box.getWidth() <= 1) {
gc.setColor(Color.GRAY);
gc.drawRect(apt.x, apt.y, (int) Math.round(array.length * box.getWidth()), (int) Math.round(box.getHeight()));
}
} else
nv.draw(gc, viewer.trans);
}
/**
* draw as meters
*
*/
private void drawAsBarChart(Node v, NodeView nv, NodeData data) {
final double count;
final float[] array;
if (scaleBy == ScaleBy.Summarized || v.getOutDegree() == 0) // must be collapsed node
{
count = data.getCountSummarized();
array = data.getSummarized();
} else {
count = data.getCountAssigned();
array = data.getAssigned();
}
Point2D location = nv.getLocation();
Rectangle box = new Rectangle();
viewer.trans.w2d(new Rectangle(0, 0, MainViewer.XSTEP, MainViewer.YSTEP), box);
int width;
if (array.length <= 1)
width = 30;
else
width = (int) (30.0 / array.length * (Math.sqrt(array.length)));
box.setRect(box.x, box.y, width, Math.min(2 * maxNodeHeight, box.height));
if (location == null)
return; // no location, don't draw
Point apt = viewer.trans.w2d(location);
if (v.getOutDegree() == 0 || count > 0) {
nv.setNodeShape(NodeShape.Rectangle);
nv.setWidth((int) Math.round((array.length) * box.getWidth()));
nv.setHeight((int) Math.round(box.getHeight()));
} else {
nv.setNodeShape(NodeShape.Oval);
nv.setWidth(1);
nv.setHeight(1);
}
apt.x -= nv.getWidth() / 2; // offset
apt.y -= box.getHeight() / 2;
if (data.getUpPValue() >= 0) {
gc.setColor(pvalueColor);
Stroke oldStroke = gc.getStroke();
int leftWidth = getWidthForPValue(data.getUpPValue());
gc.setStroke(new BasicStroke(leftWidth));
gc.drawLine(apt.x - 1, apt.y, apt.x - 1, apt.y + nv.getHeight());
gc.setStroke(oldStroke);
}
if (data.getDownPValue() >= 0) {
gc.setColor(pvalueColor);
Stroke oldStroke = gc.getStroke();
int rightWidth = getWidthForPValue(data.getDownPValue());
gc.setStroke(new BasicStroke(rightWidth));
gc.drawLine(apt.x + nv.getWidth() + 1, apt.y,
apt.x + nv.getWidth() + 1, apt.y + nv.getHeight());
gc.setStroke(oldStroke);
}
//gc.drawString(""+count,apt.x+30,apt.y);
if (v.getOutDegree() == 0 || count > 0) {
for (int i = 0; i < array.length; i++) {
gc.setColor(Color.WHITE);
gc.fill(new Rectangle2D.Double(apt.x + i * box.getWidth(), apt.y, box.getWidth(), box.getHeight()));
gc.setColor(doc.getColorByIndex(i));
double height = box.getHeight() / (double) getMaxNodeHeight() * getScaledSize(array[i]);
double aWidth = Math.max(0.2, box.getWidth());
gc.fill(new Rectangle2D.Double(apt.x + i * box.getWidth(), apt.y + (box.getHeight() - height), aWidth, height));
// Color color = new Color(Math.max(0, (int) (0.8 * doc.getColorByIndex(i).getRed())), Math.max(0, (int) (0.8 * doc.getColorByIndex(i).getGreen())), Math.max(0, (int) (0.8 * doc.getColorByIndex(i).getBlue())));
// gc.setColor(color);
// gc.drawLine(apt.x + i * box.width, apt.y + (int) (box.height - height), apt.x + (i + 1) * box.width, apt.y + (int) (box.height - height));
if (box.getWidth() > 1) {
gc.setColor(Color.GRAY);
gc.draw(new Rectangle2D.Double(apt.x + i * box.getWidth(), apt.y, box.getWidth(), box.getHeight()));
}
}
if (box.getWidth() <= 1) {
gc.setColor(Color.GRAY);
gc.drawRect(apt.x, apt.y, (int) Math.round(array.length * box.getWidth()), (int) Math.round(box.getHeight()));
}
} else
nv.draw(gc, viewer.trans);
}
/**
* convert a pvalue into a line width
*
* @return line width
*/
private static int getWidthForPValue(double pvalue) {
if (pvalue < 0) return 0;
if (pvalue < Math.pow(10, -37)) return 9;
if (pvalue < Math.pow(10, -32)) return 8;
if (pvalue < Math.pow(10, -27)) return 7;
if (pvalue < Math.pow(10, -22)) return 6;
if (pvalue < Math.pow(10, -17)) return 5;
if (pvalue < Math.pow(10, -12)) return 4;
if (pvalue < Math.pow(10, -7)) return 3;
if (pvalue < Math.pow(10, -2)) return 2;
return 1;
}
public ScaleBy getScaleBy() {
return scaleBy;
}
public void setScaleBy(String scaleByName) {
for (ScaleBy aScaleBy : ScaleBy.values()) {
if (scaleByName.equalsIgnoreCase(aScaleBy.toString())) {
setScaleBy(aScaleBy);
return;
}
}
}
public void setScaleBy(ScaleBy scaleBy) {
this.scaleBy = scaleBy;
}
public boolean isDrawLeavesOnly() {
return drawLeavesOnly;
}
public void setDrawLeavesOnly(boolean drawLeavesOnly) {
this.drawLeavesOnly = drawLeavesOnly;
}
}
| 27,153 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MyJTreeCellRender.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/gui/MyJTreeCellRender.java | /*
* MyJTreeCellRender.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.gui;
import jloda.graph.Node;
import jloda.graph.NodeData;
import jloda.swing.util.ProgramProperties;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.tree.TreeCellRenderer;
import java.awt.*;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
/**
* tree cell Renderer
* Daniel Huson, March 2016
*/
public class MyJTreeCellRender implements TreeCellRenderer {
private final ClassificationViewer classificationViewer;
private final Map<Integer, Set<Node>> id2NodesInInducedTree;
private final JLabel label = new JLabel();
private final LineBorder selectedBorder = (LineBorder) BorderFactory.createLineBorder(ProgramProperties.SELECTION_COLOR_DARKER);
private Function<Integer, ImageIcon> iconProducer = null;
/**
* constructor
*
*/
public MyJTreeCellRender(ClassificationViewer classificationViewer, Map<Integer, Set<Node>> id2NodesInInducedTree) {
this.classificationViewer = classificationViewer;
this.id2NodesInInducedTree = id2NodesInInducedTree;
label.setOpaque(true);
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (value instanceof ViewerJTree.MyJTreeNode) {
final ViewerJTree.MyJTreeNode jNode = (ViewerJTree.MyJTreeNode) value;
final Node v = jNode.getV(); // node in full tree
final Integer classId = (Integer) v.getInfo();
float count = 0;
Set<Node> inducedNodes = id2NodesInInducedTree.get(classId);
if (inducedNodes != null && inducedNodes.size() > 0) {
final NodeData nodeData = (NodeData) inducedNodes.iterator().next().getData();
if (nodeData != null)
count = nodeData.getCountSummarized();
}
final String name = (classificationViewer.getClassification().getName2IdMap().get((Integer) v.getInfo()));
if (count > 0) {
label.setText(String.format("<html>%s<font color=#a0a0a0> (%,.0f)</font>", name, count));
label.setForeground(Color.BLACK);
} else {
label.setForeground(Color.LIGHT_GRAY);
label.setText(name);
}
if(!selected)
selected = classificationViewer.getSelectedNodeIds().contains(v.getId());
if (selected) {
label.setBackground(ProgramProperties.SELECTION_COLOR);
label.setBorder(selectedBorder);
} else if (hasFocus) {
label.setBackground(Color.WHITE);
label.setBorder(selectedBorder);
} else {
label.setBackground(Color.WHITE);
label.setBorder(null);
}
if (iconProducer != null)
label.setIcon(iconProducer.apply(classId));
} else {
label.setText(value.toString());
}
label.setPreferredSize(new Dimension(label.getPreferredSize().width + 100, label.getPreferredSize().height));
label.setMinimumSize(label.getPreferredSize());
label.validate();
label.setToolTipText(label.getText());
return label;
}
public void setIconProducer(Function<Integer, ImageIcon> iconProducer) {
this.iconProducer = iconProducer;
}
}
| 4,310 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CircSpiral.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/gui/CircSpiral.java | /*
* CircSpiral.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.gui;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.GeneralPath;
public class CircSpiral extends JPanel {
public void paintComponent(Graphics gc) {
float[] values = {1.0f, .7f, 0.3f, 0.01f, 0.001f};
//float[] values={1.0f,.7f,0.7f,0.6f,0.3f};
final int nodeHeight = 200;
final int nodeWidth = 200;
final int centerX = (getSize().width - nodeHeight) / 2;
final int centerY = (getSize().height - nodeHeight) / 2;
final int minX = centerX - nodeWidth / 2;
final int maxX = centerX + nodeWidth / 2;
final int minY = centerY - nodeHeight / 2;
final int maxY = centerY + nodeHeight / 2;
gc.setColor(Color.DARK_GRAY);
gc.fillArc(minX - 3, minY - 3, nodeWidth + 6, nodeHeight + 6, 0, 360);
final float factor = 0.7f;
{
float[] x = new float[5];
float[] y = new float[5];
for (int i = 0; i < 5; i++) {
switch (i) {
case 0 -> {
x[i] = centerX;
y[i] = minY + 0.5f * factor * values[i] * nodeHeight;
}
case 1 -> {
x[i] = maxX - 0.5f * factor * values[i] * nodeWidth;
y[i] = centerY;
}
case 2 -> {
x[i] = centerX;
y[i] = maxY - 0.5f * factor * values[i] * nodeHeight;
}
case 3 -> {
x[i] = minX + 0.5f * factor * values[i] * nodeWidth;
y[i] = centerY;
}
case 4 -> {
x[i] = centerX;
y[i] = minY + factor * values[i] * nodeHeight;
}
}
}
GeneralPath.Float gp = new GeneralPath.Float();
gp.moveTo(x[0], y[0]);
gp.quadTo(x[1], y[0], x[1], y[1]);
gp.quadTo(x[1], y[2], x[2], y[2]);
gp.quadTo(x[3], y[2], x[3], y[3]);
gp.quadTo(x[3], y[4], x[4], y[4]);
gp.lineTo(x[0], y[0]);
gp.closePath();
gc.setColor(Color.WHITE);
((Graphics2D) gc).fill(gp);
/*
gc.setColor(Color.BLUE);
((Graphics2D) gc).draw(gp);
*/
}
gc.setColor(Color.BLACK);
gc.drawArc(minX - 3, minY - 3, nodeWidth + 6, nodeHeight + 6, 0, 360);
}
public static void main(String[] args) {
CircSpiral panel = new CircSpiral();
JFrame application = new JFrame();
application.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
application.add(panel);
application.setSize(300, 300);
application.setVisible(true);
}
} | 3,706 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ViewerJTree.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/gui/ViewerJTree.java | /*
* ViewerJTree.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.gui;
import javafx.application.Platform;
import jloda.fx.util.ProgramExecutorService;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.phylo.PhyloTree;
import jloda.swing.util.PopupMenu;
import jloda.swing.window.IPopupMenuModifier;
import megan.viewer.ClassificationViewer;
import megan.viewer.GUIConfiguration;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
/**
* tree viewer for classification
* Created by huson on 2/3/16.
*/
public class ViewerJTree extends JTree {
private final ClassificationViewer classificationViewer;
private final Map<Integer, MyJTreeNode> id2node = new HashMap<>();
private IPopupMenuModifier popupMenuModifier;
private final PhyloTree inducedTree; // need use own copy of induced tree that has no collapsed nodes
private final Map<Integer, Set<Node>> id2NodesInInducedTree;
private final JPopupMenu popupMenu;
boolean inSelection = false; // use this to prevent bouncing when selecting from viewer
/**
* constructor
*
*/
public ViewerJTree(ClassificationViewer classificationViewer) {
this.classificationViewer = classificationViewer;
getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
inducedTree = new PhyloTree();
id2NodesInInducedTree = new HashMap<>();
setCellRenderer(new MyJTreeCellRender(classificationViewer, id2NodesInInducedTree));
addTreeSelectionListener(new MyJTreeSelectionListener(this, classificationViewer));
final MyJTreeListener treeListener = new MyJTreeListener(this, classificationViewer, id2node);
addTreeWillExpandListener(treeListener);
addTreeExpansionListener(treeListener);
addMouseListener(new MyMouseListener());
popupMenu = new PopupMenu(this, GUIConfiguration.getJTreePopupConfiguration(), classificationViewer.getCommandManager());
}
/**
* rescan the jtree
*/
public void update() {
if (classificationViewer.getTree().getNumberOfNodes() > 1) {
removeAll();
id2node.clear();
inducedTree.clear();
id2NodesInInducedTree.clear();
if (classificationViewer.getDocument().getNumberOfReads() > 0)
classificationViewer.computeInduceTreeWithNoCollapsedNodes(inducedTree, id2NodesInInducedTree);
final Node root = classificationViewer.getClassification().getFullTree().getRoot();
final int id = (Integer) root.getInfo();
final MyJTreeNode node = new MyJTreeNode(root);
final DefaultTreeModel model = (DefaultTreeModel) getModel();
model.setRoot(node);
id2node.put(id, node);
setRootVisible(true);
setShowsRootHandles(true);
addChildren(node);
}
}
/**
* add all children of a given node
*
*/
public void addChildren(MyJTreeNode node) {
final Node v = node.getV();
final DefaultTreeModel model = (DefaultTreeModel) getModel();
if (v.getOutDegree() > 0 && node.getChildCount() == 0) {
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
final Node w = e.getTarget();
final MyJTreeNode wNode = new MyJTreeNode(w);
node.add(wNode);
id2node.put((Integer) w.getInfo(), wNode);
model.nodeStructureChanged(wNode);
}
}
model.nodeStructureChanged(node);
}
public boolean isInSelection() {
return inSelection;
}
/**
* select a node by id
*
*/
public void setSelected(int id, boolean select) {
if (!inSelection) {
inSelection = true;
var n = id2node.get(id);
if (n != null) {
var path = new TreePath(n.getPath());
if (select)
addSelectionPath(path);
else
removeSelectionPath(path);
makeVisible(path);
repaint();
}
inSelection = false;
}
}
/**
* select nodes by their ids
*
*/
public void setSelected(Collection<Integer> ids, boolean select) {
if (!inSelection) {
inSelection = true;
var paths = new ArrayList<TreePath>();
for (var id : ids) {
DefaultMutableTreeNode n = id2node.get(id);
if (n != null) {
var path = new TreePath(n.getPath());
paths.add(path);
if (select && paths.size() == 1)
makeVisible(path);
}
}
if (paths.size() > 0) {
if (select)
addSelectionPaths(paths.toArray(new TreePath[0]));
else
removeSelectionPaths(paths.toArray(new TreePath[0]));
SwingUtilities.invokeLater(this::repaint);
}
inSelection = false;
}
}
public void setPopupMenuModifier(IPopupMenuModifier popupMenuModifier) {
this.popupMenuModifier = popupMenuModifier;
}
class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) showPopupMenu(e);
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) showPopupMenu(e);
}
}
private void showPopupMenu(MouseEvent e) {
if (popupMenuModifier != null) {
popupMenuModifier.apply(popupMenu, classificationViewer.getCommandManager());
popupMenuModifier = null;
}
popupMenu.show(ViewerJTree.this, e.getX(), e.getY());
}
/**
* tree node
*/
public static class MyJTreeNode extends DefaultMutableTreeNode {
private final Node v;
MyJTreeNode(Node v) {
this.v = v;
}
public Node getV() {
return v;
}
public String toString() {
return "[" + v.getInfo() + "]";
}
@Override
public boolean isLeaf() {
return v.getOutDegree() == 0;
}
}
}
class MyJTreeListener implements TreeWillExpandListener, TreeExpansionListener {
private final ViewerJTree jTree;
private final ClassificationViewer classificationViewer;
/**
* constructor
*
*/
MyJTreeListener(ViewerJTree jTree, ClassificationViewer classificationViewer, Map<Integer, ViewerJTree.MyJTreeNode> id2node) {
this.jTree = jTree;
this.classificationViewer = classificationViewer;
}
/**
* Invoked whenever a node in the tree is about to be collapsed.
*/
public void treeWillCollapse(TreeExpansionEvent event) {
}
/**
* Called whenever an item in the tree has been collapsed.
*/
public void treeCollapsed(TreeExpansionEvent event) {
}
/**
* Called whenever an item in the tree has been expanded.
*/
public void treeExpanded(TreeExpansionEvent event) {
}
/**
* Invoked whenever a node in the tree is about to be expanded.
*/
public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
if (classificationViewer.isLocked()) {
throw new ExpandVetoException(event);
}
jTree.addChildren((ViewerJTree.MyJTreeNode) event.getPath().getLastPathComponent());
}
}
class MyJTreeSelectionListener implements TreeSelectionListener {
private final ClassificationViewer ClassificationViewer;
private final ViewerJTree jtree;
public MyJTreeSelectionListener(ViewerJTree jtree, ClassificationViewer ClassificationViewer) {
this.jtree = jtree;
this.ClassificationViewer = ClassificationViewer;
}
/**
* Called whenever the value of the selection changes.
*
* @param e the event that characterizes the replace.
*/
public void valueChanged(TreeSelectionEvent e) {
if (!jtree.inSelection) {
jtree.inSelection = true;
Set<Integer> ids2Select = new HashSet<>();
Set<Integer> ids2Deselect = new HashSet<>();
for (TreePath path : e.getPaths()) {
final ViewerJTree.MyJTreeNode node = (ViewerJTree.MyJTreeNode) path.getLastPathComponent();
if (e.isAddedPath(path))
ids2Select.add((Integer) node.getV().getInfo());
else
ids2Deselect.add((Integer) node.getV().getInfo());
}
if (ids2Select.size() > 0 || ids2Deselect.size() > 0) {
if (ids2Deselect.size() > 0)
ClassificationViewer.setSelectedIds(ids2Deselect, false);
if (ids2Select.size() > 0) {
ClassificationViewer.setSelectedIds(ids2Select, true);
Node v = ClassificationViewer.getANode(ids2Select.iterator().next());
if (v != null)
ClassificationViewer.scrollToNode(v);
}
ClassificationViewer.repaint();
}
jtree.inSelection = false;
}
}
} | 10,289 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ViewerJTable.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/gui/ViewerJTable.java | /*
* ViewerJTable.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.gui;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.graph.NodeData;
import jloda.swing.util.PopupMenu;
import jloda.swing.util.ProgramProperties;
import jloda.swing.window.IPopupMenuModifier;
import jloda.util.Basic;
import jloda.util.Pair;
import megan.viewer.ClassificationViewer;
import megan.viewer.GUIConfiguration;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/**
* jtable representation of the data at leaves of tree
* Daniel Huson, 10.2010
*/
public class ViewerJTable extends JTable {
private final ClassificationViewer classificationViewer;
private final DefaultTableModel model;
private final MyCellRender cellRenderer;
private final Map<Integer, Integer> id2row = new HashMap<>();
private final JPopupMenu popupMenu;
private IPopupMenuModifier popupMenuModifier;
private boolean inSelection = false; // use this to prevent bouncing when selecting from viewer
/**
* constructor
*
*/
public ViewerJTable(ClassificationViewer classificationViewer) {
this.classificationViewer = classificationViewer;
model = new DefaultTableModel() {
public Class getColumnClass(int col) {
if (col >= 0 && col < getColumnCount()) {
if (col == 0)
return Pair.class;
else
return Integer.class;
} else
return Object.class;
}
};
setModel(model);
addMouseListener(new MyMouseListener());
getSelectionModel().addListSelectionListener(new MyListSelectionListener());
cellRenderer = new MyCellRender();
getTableHeader().setReorderingAllowed(true);
setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
setShowGrid(false);
setRowSorter(new TableRowSorter<TableModel>(model));
popupMenu = new PopupMenu(this, GUIConfiguration.getJTablePopupConfiguration(), classificationViewer.getCommandManager());
// ToolTipManager.sharedInstance().unregisterComponent(this);
// rescan();
}
/**
* rescan the heatmap
*/
public void update() {
clear();
// setup column names
final String[] columnNames = new String[classificationViewer.getNumberOfDatasets() + 1];
columnNames[0] = classificationViewer.getClassName();
for (int i = 1; i <= classificationViewer.getNumberOfDatasets(); i++) {
columnNames[i] = "Reads [" + i + "]";
}
model.setColumnIdentifiers(columnNames);
// setup cellRenderer:
for (int i = 0; i < getColumnCount(); i++) {
TableColumn col = getColumnModel().getColumn(i);
col.setCellRenderer(cellRenderer);
}
if (classificationViewer.getTree().getRoot() != null) {
buildHeatMapRec(classificationViewer.getTree().getRoot(), new HashSet<>());
}
float[] maxCounts = new float[classificationViewer.getNumberOfDatasets()];
for (Node v = classificationViewer.getTree().getFirstNode(); v != null; v = v.getNext()) {
if (v.getOutDegree() == 0) {
NodeData data = classificationViewer.getNodeData(v);
if (data != null) {
float[] summarized = data.getSummarized();
int top = Math.min(summarized.length, maxCounts.length);
for (int i = 0; i < top; i++) {
maxCounts[i] = Math.max(maxCounts[i], summarized[i]);
}
}
}
}
cellRenderer.setMaxCounts(maxCounts);
}
/**
* recursively build the table
*
*/
private void buildHeatMapRec(Node v, HashSet<Integer> seen) {
if (v.getOutDegree() == 0) {
NodeData data = classificationViewer.getNodeData(v);
if (data != null) {
float[] summarized = data.getSummarized();
Comparable[] rowData = new Comparable[summarized.length + 1];
int id = (Integer) v.getInfo();
if (!seen.contains(id)) {
seen.add(id);
String name = classificationViewer.getClassification().getName2IdMap().get(id);
rowData[0] = new Pair<>(name, id) {
public String toString() {
return getFirst();
}
};
for (int i = 0; i < summarized.length; i++) {
rowData[i + 1] = summarized[i];
}
id2row.put(id, model.getRowCount());
model.addRow(rowData);
}
}
} else {
for (Edge e = v.getFirstOutEdge(); e != null; e = v.getNextOutEdge(e)) {
Node w = e.getTarget();
buildHeatMapRec(w, seen);
}
}
}
/**
* erase the table
*/
private void clear() {
id2row.clear();
clearSelection();
while (model.getRowCount() > 0)
model.removeRow(model.getRowCount() - 1);
model.getDataVector().clear();
}
/**
* don't allow editing of anything
*
* @return false
*/
public boolean isCellEditable(int row, int column) {
return false;
}
public boolean isInSelection() {
return inSelection;
}
/**
* select nodes by their ids
*
*/
public void setSelected(Collection<Integer> ids, boolean select) {
if (!inSelection) {
inSelection = true;
int first = -1;
for (Integer id : ids) {
Integer row = id2row.get(id);
if (row != null) {
row = convertRowIndexToView(row);
if (first == -1)
first = row;
if (select)
addRowSelectionInterval(row, row);
else
removeRowSelectionInterval(row, row);
}
}
if (first != -1) {
final int firstf = first;
final Runnable runnable = () -> scrollRectToVisible(new Rectangle(getCellRect(firstf, 0, true)));
if (SwingUtilities.isEventDispatchThread())
runnable.run();
else
SwingUtilities.invokeLater(runnable);
}
}
inSelection = false;
}
class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
try {
classificationViewer.getDir().executeImmediately("zoom what=full;zoom what=selected;", classificationViewer.getCommandManager());
} catch (Exception e1) {
Basic.caught(e1);
}
}
}
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopupMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopupMenu(e);
}
}
}
private void showPopupMenu(MouseEvent e) {
if (popupMenuModifier != null) {
popupMenuModifier.apply(popupMenu, classificationViewer.getCommandManager());
popupMenuModifier = null;
}
popupMenu.show(ViewerJTable.this, e.getX(), e.getY());
}
/**
* selection listener
*/
class MyListSelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
if (!inSelection) {
inSelection = true;
if (!classificationViewer.isLocked()) {
if (!e.getValueIsAdjusting()) {
boolean originallyEmptySelectionInViewer = classificationViewer.getSelectedNodes().isEmpty();
classificationViewer.selectAllNodes(false);
classificationViewer.selectAllEdges(false);
// selection event
if (getSelectedRowCount() > 0) {
int[] selectedRowIndices = getSelectedRows();
// first deselect all nodes and edges
for (int row : selectedRowIndices) {
row = convertRowIndexToModel(row);
int col = convertColumnIndexToModel(0);
if (row > model.getDataVector().size() - 1) {
return;
}
if (getModel().getValueAt(row, 0) != null) {
int id = ((Pair<String, Integer>) getModel().getValueAt(row, col)).getSecond();
if (classificationViewer.getNodes(id) != null) {
for (Node v : classificationViewer.getNodes(id)) {
classificationViewer.setSelected(v, true);
classificationViewer.repaint();
}
}
}
}
if (originallyEmptySelectionInViewer != classificationViewer.getSelectedNodes().isEmpty())
classificationViewer.getCommandManager().updateEnableState();
}
}
}
inSelection = false;
}
}
}
public IPopupMenuModifier getPopupMenuModifier() {
return popupMenuModifier;
}
public void setPopupMenuModifier(IPopupMenuModifier popupMenuModifier) {
this.popupMenuModifier = popupMenuModifier;
}
}
class MyCellRender implements TableCellRenderer {
private GreenGradient[] greenGradients;
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
// in case of reorder columns:
col = table.convertColumnIndexToModel(col);
if (col == 0) {
Pair<String, Integer> pair = (Pair<String, Integer>) value;
if (pair == null)
return new JLabel("");
JLabel label = new JLabel(pair.getFirst());
if (isSelected)
label.setBorder(BorderFactory.createLineBorder(ProgramProperties.SELECTION_COLOR_DARKER));
else
label.setBorder(null);
label.setPreferredSize(new Dimension(label.getPreferredSize().width + 100, label.getPreferredSize().height));
label.setMinimumSize(label.getPreferredSize());
return label;
} else {
int number;
try {
number = Math.round(Float.parseFloat(String.valueOf(value)));
} catch (NumberFormatException nfe) {
return new JLabel("?");
}
JLabel label = new JLabel(String.valueOf(number));
label.setFont(new Font("SansSerif", Font.PLAIN, 11));
try {
if (greenGradients != null && greenGradients[col - 1] != null) {
Color color = greenGradients[col - 1].getLogColor(number);
label.setBackground(color);
if (color.getRed() + color.getGreen() + color.getBlue() < 250)
label.setForeground(Color.WHITE);
}
} catch (IllegalArgumentException iae) {
// -1 ?
}
label.setOpaque(true);
if (isSelected)
label.setBorder(BorderFactory.createLineBorder(ProgramProperties.SELECTION_COLOR));
else if (hasFocus)
label.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
else
label.setBorder(null);
label.setToolTipText(label.getText());
return label;
}
}
public void setMaxCounts(float[] maxCounts) {
greenGradients = new GreenGradient[maxCounts.length];
for (int i = 0; i < maxCounts.length; i++)
greenGradients[i] = new GreenGradient(Math.round(maxCounts[i]));
}
}
| 13,655 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyImageCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/CopyImageCommand.java | /*
* CopyImageCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.export.TransferableGraphic;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class CopyImageCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
TransferableGraphic tg = new TransferableGraphic(((ClassificationViewer) getViewer()).getPanel(), ((ClassificationViewer) getViewer()).getScrollPane());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(tg, tg);
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Copy Image";
}
public String getDescription() {
return "Copy image to clipboard";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Copy16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
}
| 2,272 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
EditEdgeLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/EditEdgeLabelCommand.java | /*
* EditEdgeLabelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.graph.Edge;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class EditEdgeLabelCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
ClassificationViewer viewer = ((ClassificationViewer) getViewer());
boolean changed = false;
int numToEdit = viewer.getSelectedEdges().size();
for (Edge e : viewer.getSelectedEdges()) {
if (numToEdit > 5) {
int result = JOptionPane.showConfirmDialog(viewer.getFrame(), "There are " + numToEdit +
" more selected labels, edit next?", "Question", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon());
if (result == JOptionPane.NO_OPTION)
break;
}
numToEdit--;
String label = viewer.getLabel(e);
label = JOptionPane.showInputDialog(viewer.getFrame(), "Edit Edge Label:", label);
if (label != null && !label.equals(viewer.getLabel(e))) {
if (label.length() > 0)
viewer.setLabel(e, label);
else
viewer.setLabel(e, null);
changed = true;
}
}
if (changed)
viewer.repaint();
}
public boolean isApplicable() {
return getViewer() != null && ((ClassificationViewer) getViewer()).getSelectedEdges().size() > 0;
}
public String getName() {
return "Edit Edge Label";
}
public String getDescription() {
return "Edit the edge label";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Command16.gif");
}
public boolean isCritical() {
return false;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,217 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectByRankCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/SelectByRankCommand.java | /*
* SelectByRankCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.util.CallBack;
import megan.util.PopupChoice;
import megan.viewer.ClassificationViewer;
import megan.viewer.TaxonomicLevels;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* selection command
* Daniel Huson, 9.2015
*/
public class SelectByRankCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "select rank={" + StringUtils.toString(TaxonomicLevels.getAllNames(), "|") + "}";
}
public void apply(NexusStreamParser np) throws Exception {
final ClassificationViewer viewer = (ClassificationViewer) getViewer();
np.matchIgnoreCase("select rank=");
String rankName = np.getWordMatchesIgnoringCase(StringUtils.toString(TaxonomicLevels.getAllNames(), " "));
int rank = TaxonomicLevels.getId(rankName);
np.matchRespectCase(";");
if (rank == 0)
NotificationsInSwing.showError(getViewer().getFrame(), "Unknown rank: " + rankName);
else {
viewer.setSelectedIds(ClassificationManager.get(viewer.getClassName(), true).getFullTree().getNodeIdsAtGivenRank(rank, false), true);
}
viewer.repaint();
}
public void actionPerformed(ActionEvent event) {
final String[] ranks = TaxonomicLevels.getAllMajorRanks().toArray(new String[0]);
PopupChoice<String> popupChoice = new PopupChoice<>(ranks, null, new CallBack<>() {
@Override
public void call(String choice) {
execute("select rank='" + choice + "';");
}
});
popupChoice.showAtCurrentMouseLocation(getViewer().getFrame());
}
public String getName() {
return "Rank...";
}
public String getAltName() {
return "Select By Rank";
}
public String getDescription() {
return "Select nodes by rank";
}
public ImageIcon getIcon() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ClassificationManager.get(getViewer().getClassName(), false).getId2Rank().size() > 0;
}
}
| 3,516 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowAlignmentViewerCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/ShowAlignmentViewerCommand.java | /*
* ShowAlignmentViewerCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.graph.Node;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.alignment.AlignmentViewer;
import megan.commands.CommandBase;
import megan.core.Director;
import megan.core.Document;
import megan.util.WindowUtilities;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
public class ShowAlignmentViewerCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show window=aligner;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show window=aligner");
np.matchIgnoreCase(";");
final Director dir = getDir();
final Document doc = dir.getDocument();
final ClassificationViewer classificationViewer = (ClassificationViewer) getViewer();
if (classificationViewer.getSelectedNodeIds().size() == 1) {
final int id = classificationViewer.getSelectedNodeIds().iterator().next();
final Node v = classificationViewer.getANode(id);
if (v != null) {
final String name = classificationViewer.getLabel(v);
final Set<Integer> ids = new HashSet<>();
ids.add(id);
if (v.getOutDegree() == 0) {
ids.addAll(classificationViewer.getClassification().getFullTree().getAllDescendants(id));
}
final AlignmentViewer alignerViewer = new AlignmentViewer(dir);
dir.addViewer(alignerViewer);
alignerViewer.getBlast2Alignment().loadData(classificationViewer.getClassName(), ids, name, doc.getProgressListener());
WindowUtilities.toFront(alignerViewer);
}
}
}
public void actionPerformed(ActionEvent event) {
execute("show window=aligner;");
}
public boolean isApplicable() {
final Document doc = getDir().getDocument();
final ClassificationViewer classificationViewer = (ClassificationViewer) getViewer();
return classificationViewer != null && doc.getMeganFile().hasDataConnector() && classificationViewer.getSelectedNodeIds().size() == 1;
// && (doc.getBlastMode().equals(BlastModeUtils.BlastX) || (doc.getBlastMode().equals(BlastModeUtils.BlastN) || (doc.getBlastMode().equals(BlastModeUtils.BlastP))));
}
private final static String NAME = "Show Alignment...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Show alignment of reads to a specified reference sequence";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Alignment16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
}
| 3,999 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectPositiveAssignedCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/SelectPositiveAssignedCommand.java | /*
* SelectPositiveAssignedCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* selection command
* Daniel Huson, 7.2018
*/
public class SelectPositiveAssignedCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("select nodes=positiveAssigned;");
}
public String getName() {
return "Has Assigned";
}
public String getDescription() {
return "Has a positive number of assigned reads";
}
public ImageIcon getIcon() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return ((ClassificationViewer) getViewer()).getNumberOfDatasets() > 0;
}
}
| 2,153 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowVersionInfoCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/ShowVersionInfoCommand.java | /*
* ShowVersionInfoCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.Message;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.Document;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class ShowVersionInfoCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show versionInfo;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final ClassificationViewer classificationViewer = (ClassificationViewer) getViewer();
String version = Document.getVersionInfo().get(classificationViewer.getClassName() + " tree");
if (version != null)
Message.show(getViewer().getFrame(), classificationViewer.getClassName() + " classification:\n" + version);
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return getViewer() != null && getViewer() instanceof ClassificationViewer && Document.getVersionInfo().get(getViewer().getClassName() + " tree") != null;
}
private final static String NAME = "Show Info...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Show version info on this classification";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Help16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,537 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportSegmentationOfReadsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/ExportSegmentationOfReadsCommand.java | /*
* ExportSegmentationOfReadsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.NumberUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.analysis.TaxonomicSegmentation;
import megan.core.Document;
import megan.dialogs.export.analysis.SegmentationOfReadsExporter;
import megan.viewer.MainViewer;
import megan.viewer.TaxonomicLevels;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
/**
* export taxonomic segmentation of reads
* Daniel Huson, 8.2018
*/
public class ExportSegmentationOfReadsCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export segmentedReads file=<filename> [rank={" + StringUtils.toString(TaxonomicLevels.getAllMajorRanks(), "|") + "|next}" +
" [switchPenalty=<number>] [compatibleFactor=<number>] [incompatibleFactor=<number>];";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export segmentedReads file=");
String fileName = np.getAbsoluteFileName();
final String rankName;
if (np.peekMatchIgnoreCase("rank")) {
np.matchIgnoreCase("rank=");
rankName = np.getWordMatchesIgnoringCase(StringUtils.toString(TaxonomicLevels.getAllMajorRanks(), " ") + " next");
} else
rankName = "next";
final int rank = (rankName.equals("next") ? 0 : TaxonomicLevels.getId(rankName));
final TaxonomicSegmentation taxonomicSegmentation = new TaxonomicSegmentation();
if (np.peekMatchIgnoreCase("switchPenalty")) {
np.matchIgnoreCase("switchPenalty=");
taxonomicSegmentation.setSwitchPenalty((float) np.getDouble(0.0, 1000000.0));
}
if (np.peekMatchIgnoreCase("compatibleFactor")) {
np.matchIgnoreCase("compatibleFactor=");
taxonomicSegmentation.setCompatibleFactor((float) np.getDouble(0, 1000.0));
}
if (np.peekMatchIgnoreCase("incompatibleFactor")) {
np.matchIgnoreCase("incompatibleFactor=");
taxonomicSegmentation.setIncompatibleFactor((float) np.getDouble(0, 1000.0));
}
np.matchIgnoreCase(";");
try {
final MainViewer viewer = (MainViewer) getViewer();
final Document doc = viewer.getDocument();
final int count = SegmentationOfReadsExporter.export(doc.getProgressListener(), viewer.getClassification().getName(), viewer.getSelectedNodeIds(), rank, doc.getConnector(), fileName, taxonomicSegmentation);
NotificationsInSwing.showInformation("Exported segmentation of reads: " + count);
} catch (IOException e) {
NotificationsInSwing.showError("Export segmentation of reads failed: " + e.getMessage());
}
}
public void actionPerformed(ActionEvent event) {
if (getViewer() instanceof MainViewer) {
final MainViewer viewer = (MainViewer) getViewer();
final JDialog frame = new JDialog();
frame.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
frame.setLocationRelativeTo(viewer.getFrame());
frame.setSize(280, 180);
final JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
pane.setBorder(new EmptyBorder(2, 5, 2, 3));
frame.getContentPane().add(pane);
pane.add(new JLabel("Setup read-segmentation DP"), BorderLayout.NORTH);
final JPanel center = new JPanel();
center.setLayout(new GridLayout(4, 2));
center.setBorder(new EtchedBorder());
pane.add(center, BorderLayout.CENTER);
center.add(new JLabel("Rank:"));
final JComboBox<String> rankMenu = new JComboBox<>(StringUtils.toArray("next " + " " + StringUtils.toString(TaxonomicLevels.getAllMajorRanks(), " ")));
rankMenu.setSelectedItem(ProgramProperties.get("SegmentationRank", "next"));
rankMenu.setEditable(false);
rankMenu.setToolTipText("Use 'next' to always use the next rank down below rank at which read is assigned");
center.add(rankMenu);
center.add(new JLabel("Switch penalty:"));
final JTextField switchPenaltyField = new JTextField();
switchPenaltyField.setMaximumSize(new Dimension(40, 12));
switchPenaltyField.setText("" + (float) ProgramProperties.get("SegmentationSwitchPenalty", TaxonomicSegmentation.defaultSwitchPenalty));
switchPenaltyField.setToolTipText("Penalty for switching to a different taxon");
center.add(switchPenaltyField);
center.add(new JLabel("Compatible factor:"));
final JTextField compatibleFactorField = new JTextField();
compatibleFactorField.setText("" + (float) ProgramProperties.get("SegmentationCompatibleFactor", TaxonomicSegmentation.defaultCompatibleFactor));
compatibleFactorField.setMaximumSize(new Dimension(40, 12));
compatibleFactorField.setToolTipText("Factor for weighting bitscore of alignment with same or compatible taxon");
center.add(compatibleFactorField);
center.add(new JLabel("Incompatible factor:"));
final JTextField incompatibleFactorField = new JTextField();
incompatibleFactorField.setText("" + (float) ProgramProperties.get("SegmentationIncompatibleFactor", TaxonomicSegmentation.defaultIncompatibleFactor));
incompatibleFactorField.setMaximumSize(new Dimension(40, 12));
incompatibleFactorField.setToolTipText("Factor for weighting bitscore of alignment with incompatible taxon");
center.add(incompatibleFactorField);
// options
final JPanel bottom = new JPanel();
bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
bottom.add(Box.createHorizontalGlue());
bottom.add(new JButton(new AbstractAction("Cancel") {
@Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
}));
bottom.add(new JButton(new AbstractAction("Apply") {
@Override
public void actionPerformed(ActionEvent e) {
final String prevFile = ProgramProperties.get("SegmentationExportFile", viewer.getDocument().getMeganFile().getFileName());
frame.setVisible(false);
final String fileName = FileUtils.replaceFileSuffix(FileUtils.getFilePath(prevFile, FileUtils.getFileNameWithoutPath(viewer.getDocument().getMeganFile().getFileName())), "-%i-%t-segmentation.txt");
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), new File(fileName), new TextFileFilter(), new TextFileFilter(), e, "Save segmentation of reads file", ".txt");
if (file != null) {
if (FileUtils.getFileSuffix(file.getName()) == null)
file = FileUtils.replaceFileSuffix(file, ".fasta");
if (rankMenu.getSelectedItem() != null)
ProgramProperties.put("SegmentationRank", rankMenu.getSelectedItem().toString());
ProgramProperties.put("SegmentationSwitchPenalty", NumberUtils.parseFloat(switchPenaltyField.getText()));
ProgramProperties.put("SegmentationCompatibleFactor", NumberUtils.parseFloat(compatibleFactorField.getText()));
ProgramProperties.put("SegmentationIncompatibleFactor", NumberUtils.parseFloat(incompatibleFactorField.getText()));
ProgramProperties.put("SegmentationExportFile", file.getPath());
execute("export segmentedReads file='" + file.getPath() + "'"
+ " rank=" + rankMenu.getSelectedItem()
+ " switchPenalty=" + NumberUtils.parseFloat(switchPenaltyField.getText()) + " compatibleFactor=" + NumberUtils.parseFloat(compatibleFactorField.getText())
+ " incompatibleFactor=" + NumberUtils.parseFloat(incompatibleFactorField.getText())
+ ";");
}
}
}));
pane.add(bottom, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
public boolean isApplicable() {
if (getViewer() instanceof MainViewer) {
final MainViewer viewer = (MainViewer) getViewer();
return viewer.getSelectedNodes().size() > 0 && viewer.getDocument().getMeganFile().hasDataConnector();
} else
return false;
}
public String getName() {
return "Export Segmentation of Reads...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export segmentation of reads. Occurrences of %f, %t or %i in filename will be replaced by input file name, class name or id, respectively.";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
} | 10,472 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
InspectAssignmentsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/InspectAssignmentsCommand.java | /*
* InspectAssignmentsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.graph.Node;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.Triplet;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.inspector.InspectorWindow;
import megan.util.WindowUtilities;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
public class InspectAssignmentsCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "inspector nodes=selected;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final Director dir = ((ClassificationViewer) getViewer()).getDir();
final ClassificationViewer classificationViewer = ((ClassificationViewer) getViewer());
final InspectorWindow inspectorWindow;
if (dir.getViewerByClass(InspectorWindow.class) != null)
inspectorWindow = (InspectorWindow) dir.getViewerByClass(InspectorWindow.class);
else
inspectorWindow = (InspectorWindow) dir.addViewer(new InspectorWindow(dir));
final LinkedList<Triplet<String, Float, Collection<Integer>>> name2Size2Ids = new LinkedList<>();
for (Integer id : classificationViewer.getSelectedNodeIds()) {
String name = classificationViewer.getClassification().getName2IdMap().get(id);
Node v = classificationViewer.getANode(id);
if (v.getOutDegree() > 0) { // internal node
float size = classificationViewer.getNodeData(v).getCountAssigned();
name2Size2Ids.add(new Triplet<>(name, size, Collections.singletonList(id)));
} else {
float size = classificationViewer.getNodeData(v).getCountSummarized();
final Collection<Integer> ids = classificationViewer.getClassification().getFullTree().getAllDescendants(id);
name2Size2Ids.add(new Triplet<>(name, size, ids));
}
}
WindowUtilities.toFront(inspectorWindow.getFrame());
if (name2Size2Ids.size() > 0) {
SwingUtilities.invokeLater(() -> {
inspectorWindow.addTopLevelNode(name2Size2Ids, classificationViewer.getClassName());
if (false) { // todo: without this, inspector window sometimes opens behind main windows...
final Runnable job = () -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> inspectorWindow.getFrame().toFront());
};
Thread thread = new Thread(job);
thread.setDaemon(true);
thread.start();
}
});
}
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return getViewer() != null && ((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0 &&
((ClassificationViewer) getViewer()).getDocument().getMeganFile().hasDataConnector();
}
private final static String NAME = "Inspect...";
public String getName() {
return NAME;
}
public String getDescription() {
return "Inspect reads and their alignments";
}
public boolean isCritical() {
return true;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Inspector16.gif");
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_I, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 4,854 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
PrintCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/PrintCommand.java | /*
* PrintCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.print.PrinterJob;
public class PrintCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show window=print;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
PrinterJob job = PrinterJob.getPrinterJob();
if (ProgramProperties.getPageFormat() != null)
job.setPrintable(((ClassificationViewer) getViewer()), ProgramProperties.getPageFormat());
else
job.setPrintable(((ClassificationViewer) getViewer()));
// Put up the dialog box
if (job.printDialog()) {
// Print the job if the user didn't cancel printing
try {
job.print();
} catch (Exception ex) {
NotificationsInSwing.showError(getViewer().getFrame(), "Print failed: " + ex.getMessage());
}
}
}
public void actionPerformed(ActionEvent event) {
executeImmediately(getSyntax());
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Print...";
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_P, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK);
}
public String getDescription() {
return "Print the main panel";
}
public boolean isCritical() {
return true;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Print16.gif");
}
}
| 2,873 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
AutoLabelLayoutCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/AutoLabelLayoutCommand.java | /*
* AutoLabelLayoutCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class AutoLabelLayoutCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
return getViewer() != null && ((ClassificationViewer) getViewer()).getAutoLayoutLabels();
}
public String getSyntax() {
return "set autoLayoutLabels={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set autoLayoutLabels=");
((ClassificationViewer) getViewer()).setAutoLayoutLabels(np.getBoolean());
np.matchIgnoreCase(";");
}
public void actionPerformed(ActionEvent event) {
execute("set autoLayoutLabels=" + (!isSelected()) + ";");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Layout Labels";
}
public String getDescription() {
return "Layout labels";
}
public boolean isCritical() {
return true;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,350 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
OpenClassificationViewerWebPageCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/OpenClassificationViewerWebPageCommand.java | /*
* OpenClassificationViewerWebPageCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.BasicSwing;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.Basic;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.net.URL;
public class OpenClassificationViewerWebPageCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "show url=<url>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show url=");
String url = np.getWordRespectCase();
np.matchIgnoreCase(";");
try {
if (url != null)
BasicSwing.openWebPage(new URL(url));
} catch (Exception e1) {
Basic.caught(e1);
NotificationsInSwing.showError(getViewer().getFrame(), "Failed to open URL: " + url);
}
}
public void actionPerformed(ActionEvent event) {
final ClassificationViewer viewer = (ClassificationViewer) getViewer();
java.util.List<String> urls = viewer.getURLsForSelection();
if (urls.size() >= 5 && JOptionPane.showConfirmDialog(getViewer().getFrame(), "Do you really want to open " + urls.size() +
" URLs in your browser?", "Confirmation - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon()) != JOptionPane.YES_OPTION)
return;
for (String url : urls) {
try {
BasicSwing.openWebPage(new URL(url));
} catch (Exception e1) {
Basic.caught(e1);
}
}
}
public boolean isApplicable() {
ClassificationViewer viewer = (ClassificationViewer) getViewer();
return viewer != null && (viewer.hasURLsForSelection());
}
private static final String NAME = "Open Web Page...";
public String getName() {
return NAME;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/WebComponent16.gif");
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_B, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
public String getDescription() {
return "Open web site in browser";
}
public boolean isCritical() {
return true;
}
}
| 3,522 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportFrameShiftCorrectedReadsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/ExportFrameShiftCorrectedReadsCommand.java | /*
* ExportFrameShiftCorrectedReadsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.FastaFileFilter;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.core.Document;
import megan.dialogs.export.analysis.FrameShiftCorrectedReadsExporter;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
public class ExportFrameShiftCorrectedReadsCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export correctedReads file=<filename> [what={all|selected}];";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export correctedReads file=");
String fileName = np.getAbsoluteFileName();
boolean saveAll = true;
if (np.peekMatchIgnoreCase("what")) {
np.matchIgnoreCase("what=");
saveAll = np.getWordMatchesIgnoringCase("selected all").equalsIgnoreCase("all");
}
np.matchIgnoreCase(";");
try {
final int count;
final ClassificationViewer viewer = (ClassificationViewer) getViewer();
final Document doc = viewer.getDocument();
if (saveAll)
count = FrameShiftCorrectedReadsExporter.exportAll(doc.getConnector(), fileName, doc.getProgressListener());
else
count = FrameShiftCorrectedReadsExporter.export(viewer.getClassification().getName(), viewer.getSelectedNodeIds(), doc.getConnector(), fileName, doc.getProgressListener());
NotificationsInSwing.showInformation("Exported corrected reads: " + count);
} catch (IOException e) {
NotificationsInSwing.showError("Export corrected reads failed: " + e.getMessage());
}
}
public void actionPerformed(ActionEvent event) {
if (getViewer() instanceof ClassificationViewer) {
final ClassificationViewer viewer = (ClassificationViewer) getViewer();
final String fileName = FileUtils.replaceFileSuffix(viewer.getDocument().getMeganFile().getFileName(), "-%i-%t-fs_corrected.fasta");
File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), new File(fileName), new FastaFileFilter(), new FastaFileFilter(), event, "Save corrected reads file", ".fasta");
if (file != null) {
if (FileUtils.getFileSuffix(file.getName()) == null)
file = FileUtils.replaceFileSuffix(file, ".fasta");
execute("export correctedReads file='" + file.getPath() + "' what=" + (viewer.hasSelectedNodes() ? "selected" : "all") + ";");
}
}
}
public boolean isApplicable() {
if (getViewer() instanceof ClassificationViewer) {
final ClassificationViewer viewer = (ClassificationViewer) getViewer();
return viewer.getDocument().getMeganFile().hasDataConnector();
} else
return false;
}
public String getName() {
return "Export Frame-Shift Corrected Reads...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export frame-shift corrected reads. Occurrences of %f, %t or %i in filename will be replaced by input file name, class name or id, respectively.";
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 4,510 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
EditNodeLabelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/EditNodeLabelCommand.java | /*
* EditNodeLabelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.graph.Node;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class EditNodeLabelCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
int numToEdit = ((ClassificationViewer) getViewer()).getSelectedNodes().size();
boolean changed = false;
for (Node v : ((ClassificationViewer) getViewer()).getSelectedNodes()) {
if (numToEdit > 5) {
int result = JOptionPane.showConfirmDialog(getViewer().getFrame(), "There are " + numToEdit +
" more selected labels, edit next?", "Question", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, ProgramProperties.getProgramIcon());
if (result == JOptionPane.NO_OPTION)
break;
}
numToEdit--;
String label = ((ClassificationViewer) getViewer()).getLabel(v);
label = JOptionPane.showInputDialog(getViewer().getFrame(), "Edit Node Label:", label);
if (label != null && !label.equals(((ClassificationViewer) getViewer()).getLabel(v))) {
if (label.length() > 0)
((ClassificationViewer) getViewer()).setLabel(v, label);
else
((ClassificationViewer) getViewer()).setLabel(v, null);
changed = true;
}
}
if (changed)
((ClassificationViewer) getViewer()).repaint();
}
public boolean isApplicable() {
return getViewer() != null && ((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0;
}
public String getName() {
return "Edit Node Label";
}
public String getDescription() {
return "Edit the node label";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Command16.gif");
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,360 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DrawComparisonOnLeavesOnlyCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/DrawComparisonOnLeavesOnlyCommand.java | /*
* DrawComparisonOnLeavesOnlyCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class DrawComparisonOnLeavesOnlyCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
return getViewer() != null && ((ClassificationViewer) getViewer()).isDrawLeavesOnly();
}
public String getSyntax() {
return "set drawLeavesOnly={true|false};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set drawLeavesOnly=");
boolean leavesOnly = np.getBoolean();
np.matchIgnoreCase(";");
ClassificationViewer viewer = ((ClassificationViewer) getViewer());
viewer.setDrawLeavesOnly(leavesOnly);
viewer.repaint();
viewer.setMustDrawTwice();
}
public void actionPerformed(ActionEvent event) {
execute("set drawLeavesOnly=" + (!isSelected()) + ";");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Draw Leaves Only";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public String getDescription() {
return "Only draw leaves";
}
public boolean isCritical() {
return true;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,514 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CollapseToTopCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/CollapseToTopCommand.java | /*
* CollapseToTopCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class CollapseToTopCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("collapse nodes=top;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Collapse To Top";
}
public String getDescription() {
return "Collapse nodes at top level";
}
public boolean isCritical() {
return true;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("CollapseTreeLevel16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,086 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
UncollapseAllNodesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/UncollapseAllNodesCommand.java | /*
* UncollapseAllNodesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class UncollapseAllNodesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("uncollapse nodes=all;");
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Uncollapse All";
}
public String getDescription() {
return "Uncollapse all nodes";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("UncollapseTree16.gif");
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_SEMICOLON, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
public boolean isCritical() {
return true;
}
}
| 1,984 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
KeepNonVirusesCollapsedCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/KeepNonVirusesCollapsedCommand.java | /*
* KeepNonVirusesCollapsedCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class KeepNonVirusesCollapsedCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return ProgramProperties.get("KeepOthersCollapsed", "").equals("viruses");
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("set keepOthersCollapsed=" + (isSelected() ? "none" : "viruses") + ";");
}
public boolean isApplicable() {
return getViewer() instanceof MainViewer;
}
public String getName() {
return "Keep Non-Viruses Collapsed";
}
public String getDescription() {
return "Keep all non-viruses collapsed when uncollapsing by rank or level";
}
public ImageIcon getIcon() {
return null;
}
public KeyStroke getAcceleratorKey() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 2,124 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CollapseAllOtherCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/CollapseAllOtherCommand.java | /*
* CollapseAllOtherCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.graph.Edge;
import jloda.graph.Node;
import jloda.swing.commands.ICommand;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public class CollapseAllOtherCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "collapse except={name};";
}
public void apply(NexusStreamParser np) throws Exception {
java.util.List<String> names = np.getWordsRespectCase("collapse except=", ";");
final ClassificationViewer classificationViewer = (ClassificationViewer) getViewer();
Set<Integer> doNotCollapse = new HashSet<>();
for (String name : names) {
Integer id = classificationViewer.getClassification().getName2IdMap().get(name);
SortedSet<Node> set = new TreeSet<>(classificationViewer.getNodes(id));
for (Node v : set) {
while (true) {
doNotCollapse.add((Integer) v.getInfo());
if (v.getInDegree() > 0)
v = v.getFirstInEdge().getSource();
else
break;
}
}
while (set.size() > 0) {
Node w = set.first();
set.remove(w);
doNotCollapse.add((Integer) w.getInfo());
for (Edge e = w.getFirstOutEdge(); e != null; e = w.getNextOutEdge(e))
set.add(e.getTarget());
}
}
boolean changed = false;
{
for (Node v = classificationViewer.getTree().getFirstNode(); v != null; v = v.getNext()) {
Integer id = (Integer) v.getInfo();
if (!doNotCollapse.contains(id)) {
classificationViewer.getCollapsedIds().add(id);
changed = true;
}
}
}
if (changed) {
classificationViewer.updateTree();
getDoc().setDirty(true);
}
}
public void actionPerformed(ActionEvent event) {
java.util.Collection<String> labels = ((ClassificationViewer) getViewer()).getSelectedNodeLabels(false);
if (labels.size() > 0)
execute("collapse except='" + StringUtils.toString(labels, "' '") + "';");
}
public boolean isApplicable() {
return getViewer() != null && ((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0;
}
public String getName() {
return "Collapse All Others";
}
public String getDescription() {
return "Collapse all parts of tree that are not above or below the selected nodes";
}
public boolean isCritical() {
return true;
}
public ImageIcon getIcon() {
return null;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_K, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
}
| 4,115 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
UncollapseSubTreeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/UncollapseSubTreeCommand.java | /*
* UncollapseSubTreeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class UncollapseSubTreeCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
if (((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0)
((ClassificationViewer) getViewer()).setPreviousNodeIdsOfInterest(((ClassificationViewer) getViewer()).getSelectedNodeIds());
execute("uncollapse nodes=subtree;");
}
public boolean isApplicable() {
return getViewer() != null && ((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0;
}
public String getName() {
return "Uncollapse Subtree";
}
public String getDescription() {
return "Uncollapse whole subtree beneath selected nodes";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("UncollapseSubTree16.gif");
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_U, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | java.awt.event.InputEvent.SHIFT_DOWN_MASK);
}
public boolean isCritical() {
return true;
}
}
| 2,401 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
UncollapseSelectedNodesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/UncollapseSelectedNodesCommand.java | /*
* UncollapseSelectedNodesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class UncollapseSelectedNodesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "uncollapse nodes={selected|all|subtree};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("uncollapse nodes=");
String what = np.getWordMatchesIgnoringCase("all selected subtree");
np.matchIgnoreCase(";");
if (what.equalsIgnoreCase("selected"))
((ClassificationViewer) getViewer()).uncollapseSelectedNodes(false);
else if (what.equalsIgnoreCase("subtree"))
((ClassificationViewer) getViewer()).uncollapseSelectedNodes(true);
else if (what.equalsIgnoreCase("all"))
((ClassificationViewer) getViewer()).uncollapseAll();
((ClassificationViewer) getViewer()).getDocument().setDirty(true);
}
public void actionPerformed(ActionEvent event) {
if (((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0)
((ClassificationViewer) getViewer()).setPreviousNodeIdsOfInterest(((ClassificationViewer) getViewer()).getSelectedNodeIds());
execute("uncollapse nodes=selected;");
}
public boolean isApplicable() {
return getViewer() != null && ((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0;
}
public String getName() {
return "Uncollapse";
}
public String getDescription() {
return "Uncollapse selected nodes";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("UncollapseTree16.gif");
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_U, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
public boolean isCritical() {
return true;
}
}
| 3,000 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CollapseAtLevelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/CollapseAtLevelCommand.java | /*
* CollapseAtLevelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.viewer.ClassificationViewer;
import megan.viewer.TaxonomyData;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Set;
public class CollapseAtLevelCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "collapse level=<num>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("collapse level=");
final int level = np.getInt(0, 100);
np.matchIgnoreCase(";");
final ClassificationViewer classificationViewer = (ClassificationViewer) getViewer();
final Set<Integer> ids2collapse = ClassificationManager.get(classificationViewer.getClassName(), true).getFullTree().getAllAtLevel(level);
switch (ProgramProperties.get("KeepOthersCollapsed", " none")) {
case "prokaryotes" -> ids2collapse.addAll(TaxonomyData.getNonProkaryotesToCollapse());
case "eukaryotes" -> ids2collapse.addAll(TaxonomyData.getNonEukaryotesToCollapse());
case "viruses" -> ids2collapse.addAll(TaxonomyData.getNonVirusesToCollapse());
}
classificationViewer.setCollapsedIds(ids2collapse);
getDoc().setDirty(true);
classificationViewer.updateTree();
}
public void actionPerformed(ActionEvent event) {
int level = 2;
String input = JOptionPane.showInputDialog(getViewer().getFrame(), "Enter max level", level);
if (input != null) {
try {
level = Integer.parseInt(input);
} catch (NumberFormatException ex) {
NotificationsInSwing.showError(getViewer().getFrame(), "Failed to parse input: " + input);
}
if (level < 0)
level = 0;
execute("collapse level=" + level + ";");
}
}
public boolean isApplicable() {
return true;
}
public String getName() {
return "Collapse at Level...";
}
public String getDescription() {
return "Collapse all nodes at given depth in tree";
}
public boolean isCritical() {
return true;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("CollapseTreeLevel16.gif");
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,474 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
KeepNonEukaryotesCollapsedCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/KeepNonEukaryotesCollapsedCommand.java | /*
* KeepNonEukaryotesCollapsedCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class KeepNonEukaryotesCollapsedCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return ProgramProperties.get("KeepOthersCollapsed", "none").equals("eukaryotes");
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
execute("set keepOthersCollapsed=" + (isSelected() ? "none" : "eukaryotes") + ";");
}
public boolean isApplicable() {
return getViewer() instanceof MainViewer;
}
public String getName() {
return "Keep Non-Eukaryotes Collapsed";
}
public String getDescription() {
return "Keep all non-eukaryotes collapsed when uncollapsing by rank or level";
}
public ImageIcon getIcon() {
return null;
}
public KeyStroke getAcceleratorKey() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 2,146 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
KeepNonProkaryotesCollapsedCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/KeepNonProkaryotesCollapsedCommand.java | /*
* KeepNonProkaryotesCollapsedCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.MainViewer;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class KeepNonProkaryotesCollapsedCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return ProgramProperties.get("KeepOthersCollapsed", "").equals("prokaryotes");
}
public String getSyntax() {
return "set keepOthersCollapsed={prokaryotes|eukaryotes|viruses|none};";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set keepOthersCollapsed=");
final String what = np.getWordMatchesIgnoringCase("prokaryotes eukaryotes viruses none");
ProgramProperties.put("KeepOthersCollapsed", what);
np.matchIgnoreCase(";");
}
public void actionPerformed(ActionEvent event) {
execute("set keepOthersCollapsed=" + (isSelected() ? "none" : "prokaryotes") + ";");
}
public boolean isApplicable() {
return getViewer() instanceof MainViewer;
}
public String getName() {
return "Keep Non-Prokaryotes Collapsed";
}
public String getDescription() {
return "Keep all certain taxa collapsed when uncollapsing by rank or level";
}
public ImageIcon getIcon() {
return null;
}
public KeyStroke getAcceleratorKey() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 2,469 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CollapseSelectedNodesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/CollapseSelectedNodesCommand.java | /*
* CollapseSelectedNodesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.viewer.ClassificationViewer;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class CollapseSelectedNodesCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "collapse nodes={selected|top};";
}
public void apply(NexusStreamParser np) throws Exception {
if (((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0)
((ClassificationViewer) getViewer()).setPreviousNodeIdsOfInterest(((ClassificationViewer) getViewer()).getSelectedNodeIds());
np.matchIgnoreCase("collapse nodes=");
String what = np.getWordMatchesIgnoringCase("selected top");
if (what.equals("selected"))
((ClassificationViewer) getViewer()).collapseSelectedNodes();
else if (what.equals("top"))
((ClassificationViewer) getViewer()).collapseToTop();
((ClassificationViewer) getViewer()).getDocument().setDirty(true);
}
public void actionPerformed(ActionEvent event) {
execute("collapse nodes=selected;");
}
public boolean isApplicable() {
return getViewer() != null && ((ClassificationViewer) getViewer()).getSelectedNodes().size() > 0;
}
public String getName() {
return "Collapse";
}
public String getDescription() {
return "Collapse nodes";
}
public boolean isCritical() {
return true;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("CollapseTree16.gif");
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_K, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,767 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CollapseByRankCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/viewer/commands/collapse/CollapseByRankCommand.java | /*
* CollapseByRankCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.viewer.commands.collapse;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.ClassificationManager;
import megan.commands.CommandBase;
import megan.util.CallBack;
import megan.util.PopupChoice;
import megan.viewer.ClassificationViewer;
import megan.viewer.MainViewer;
import megan.viewer.TaxonomicLevels;
import megan.viewer.TaxonomyData;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Set;
/**
* collapse rank command
* Daniel Huson, 9.2015
*/
public class CollapseByRankCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "collapse rank={" + StringUtils.toString(TaxonomicLevels.getAllNames(), "|") + "}";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("collapse rank=");
final String rankName = np.getWordMatchesIgnoringCase(StringUtils.toString(TaxonomicLevels.getAllMajorRanks(), " "));
Integer rank = TaxonomicLevels.getId(rankName);
np.matchRespectCase(";");
if (rank == 0)
NotificationsInSwing.showError(getViewer().getFrame(), "Unknown rank: " + rankName);
else {
final ClassificationViewer classificationViewer = (ClassificationViewer) getViewer();
final Set<Integer> toCollapse = ClassificationManager.get(classificationViewer.getClassName(), true).getFullTree().getNodeIdsAtGivenRank(rank, true);
switch (ProgramProperties.get("KeepOthersCollapsed", " none")) {
case "prokaryotes" -> toCollapse.addAll(TaxonomyData.getNonProkaryotesToCollapse());
case "eukaryotes" -> toCollapse.addAll(TaxonomyData.getNonEukaryotesToCollapse());
case "viruses" -> toCollapse.addAll(TaxonomyData.getNonVirusesToCollapse());
}
classificationViewer.setCollapsedIds(toCollapse);
getDoc().setDirty(true);
classificationViewer.updateTree();
}
}
public void actionPerformed(ActionEvent event) {
final String[] ranks = TaxonomicLevels.getAllMajorRanks().toArray(new String[0]);
String choice = null;
if (getViewer() instanceof MainViewer) {
choice = ((MainViewer) getViewer()).getPOWEREDBY();
}
PopupChoice<String> popupChoice = new PopupChoice<>(ranks, choice, new CallBack<>() {
@Override
public void call(String choice) {
execute("collapse rank='" + choice + "';select rank='" + choice + "';");
}
});
popupChoice.showAtCurrentMouseLocation(getViewer().getFrame());
}
public boolean isCritical() {
return true;
}
public boolean isApplicable() {
final ClassificationViewer classificationViewer = (ClassificationViewer) getViewer();
return ClassificationManager.hasTaxonomicRanks(classificationViewer.getClassName());
}
public String getName() {
return "Rank...";
}
public String getDescription() {
return "Collapse tree at specific rank";
}
public ImageIcon getIcon() {
return null;
}
}
| 4,132 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LoaderTask.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/LoaderTask.java | /*
* LoaderTask.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
import jloda.util.progress.ProgressListener;
/**
* a task that can be run by the loader
* Daniel Huson, 9.2009
*/
interface LoaderTask {
void run(ProgressListener progressListener) throws Exception;
}
| 1,041 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
NodeBase.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/NodeBase.java | /*
* NodeBase.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* a node in the inspector2 data tree
* Daniel Huson, 2.2006
*/
public class NodeBase extends DefaultMutableTreeNode implements Comparable<NodeBase> {
private String name;
float rank;
private static long maxId = 0;
private final long id;
private boolean completed = true;
public NodeBase() {
this("Untitled");
}
public NodeBase(String name) {
this.name = name;
rank = 0;
id = (++maxId);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isLeaf() {
return false;
}
public boolean getAllowsChildren() {
return !isLeaf();
}
public String toString() {
return name;
}
public float getRank() {
return rank;
}
public void setRank(float rank) {
this.rank = rank;
}
public long getId() {
return id;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
public boolean isCompleted() {
return completed;
}
public int compareTo(NodeBase v) {
if (rank < v.rank)
return -1;
else if (rank > v.rank)
return 1;
if (name != null && v.name == null)
return -1;
else if (name == null && v.name != null)
return 1;
if (name != null) {
int value = name.compareTo(v.name);
if (value != 0)
return value;
}
return Long.compare(id, v.id);
}
}
| 2,484 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ReadDataHeadLineNode.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/ReadDataHeadLineNode.java | /*
* ReadDataHeadLineNode.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
import jloda.util.StringUtils;
/**
* node representing head line for read
* Daniel Huson, 2.2006
*/
public class ReadDataHeadLineNode extends NodeBase {
private String text;
private String data;
public ReadDataHeadLineNode(String text, int readLength, float complexity, int weight, String data) {
final StringBuilder builder = new StringBuilder();
builder.append(text);
boolean first = true;
if (readLength > 0) {
builder.append("[");
first = false;
builder.append(String.format("length=%,d", readLength));
}
if (weight > 1) {
if (first) {
builder.append("[");
first = false;
} else
builder.append(", ");
builder.append(String.format("weight=%,d", weight));
}
if (complexity > 0) {
if (first) {
builder.append("[");
first = false;
} else
builder.append(", ");
builder.append(String.format("complexity=%1.2f", complexity));
}
if (!first)
builder.append("]");
setText(builder.toString());
this.data = (data != null && data.startsWith(">") ? data : ">" + data);
this.data = StringUtils.foldHard(this.data, 140);
}
private void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
public boolean isLeaf() {
return data == null || data.length() == 0;
}
public String toString() {
return text;
}
public String getData() {
return data;
}
}
| 2,523 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ReadDataTextNode.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/ReadDataTextNode.java | /*
* ReadDataTextNode.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
/**
* node to represent the data (i.e. text) of a read
* Daniel Huson, 2.2006
*/
public class ReadDataTextNode extends NodeBase {
private String text;
public ReadDataTextNode(String text) {
setText(text);
}
private void setText(String text) {
if (text.endsWith("\n"))
this.text = text;
else
this.text = text + "\n";
}
public String getText() {
return text;
}
public boolean isLeaf() {
return true;
}
public String toString() {
return text;
}
}
| 1,406 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MatchHeadLineNode.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/MatchHeadLineNode.java | /*
* MatchHeadLineNode.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
import jloda.swing.util.MultiLineCellRenderer;
/**
* Node representing headline for match
* Daniel Huson, 2.2006
*/
public class MatchHeadLineNode extends NodeBase {
private final boolean ignore;
private final boolean isUsed;
private final long uId;
private final int taxId;
private final String matchText;
/**
* constructor
*
*/
public MatchHeadLineNode(String name, float score, boolean ignore, boolean isUsed, long uId, int taxId, String matchText) {
super(name);
this.rank = -score;
this.ignore = ignore;
this.isUsed = isUsed;
this.uId = uId;
this.taxId = taxId;
this.matchText = matchText;
}
public String toString() {
StringBuilder buf = new StringBuilder();
if (ignore)
buf.append(MultiLineCellRenderer.RED);
else if (!isUsed)
buf.append(MultiLineCellRenderer.GRAY);
buf.append(getName());
if (rank != 0)
buf.append(" score=").append(String.format("%.1f", -rank));
return buf.toString();
}
public boolean getIgnore() {
return ignore;
}
public boolean isUsed() {
return isUsed;
}
public long getUId() {
return uId;
}
public int getTaxId() {
return taxId;
}
public String getMatchText() {
return matchText;
}
}
| 2,238 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
InspectorWindow.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/InspectorWindow.java | /*
* InspectorWindow.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
import jloda.swing.commands.CommandManager;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.director.IViewerWithFindToolBar;
import jloda.swing.director.ProjectManager;
import jloda.swing.find.FindToolBar;
import jloda.swing.find.JTreeSearcher;
import jloda.swing.find.SearchManager;
import jloda.swing.util.MultiLineCellRenderer;
import jloda.swing.util.PopupMenu;
import jloda.swing.util.StatusBar;
import jloda.swing.util.ToolBar;
import jloda.swing.window.MenuBar;
import jloda.util.*;
import megan.algorithms.ActiveMatches;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.core.Director;
import megan.core.Document;
import megan.data.*;
import megan.dialogs.input.InputDialog;
import megan.main.MeganProperties;
import megan.util.IReadsProvider;
import megan.viewer.MainViewer;
import megan.viewer.TaxonomyData;
import javax.swing.*;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.*;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* the inspector window
* Daniel Huson , 3.2006 , rewrote 10.2009
*/
public class InspectorWindow implements IDirectableViewer, IViewerWithFindToolBar, Printable, IReadsProvider {
private boolean uptodate = true;
private final JFrame frame;
private final JPanel mainPanel;
private final JScrollPane scrollPane;
private final StatusBar statusBar;
final Director dir;
final JTree dataTree;
private boolean doClear = false; // if this is set, window will be cleared on next rescan
private boolean isDirty = false;
// by default, the different types of nodes sorted alphabetically, alternative: by rank
private boolean sortReadsAlphabetically = true;
private final CommandManager commandManager;
private final MenuBar menuBar;
private final JPopupMenu popupMenu;
private boolean showFindToolBar = false;
private final SearchManager searchManager;
private final Loader loader;
private boolean isLocked = false;
private final Map<String, NodeBase> classification2RootNode = new HashMap<>();
private final NodeBase rootNode;
/**
* constructor
*
*/
public InspectorWindow(final Director dir) {
this.dir = dir;
this.commandManager = new CommandManager(dir, this, new String[]{"megan.inspector.commands", "megan.commands"}, !ProgramProperties.isUseGUI());
frame = new JFrame();
setTitle();
frame.setIconImages(jloda.swing.util.ProgramProperties.getProgramIconImages());
frame.getContentPane().setLayout(new BorderLayout());
menuBar = new MenuBar(this, GUIConfiguration.getMenuConfiguration(), getCommandManager());
frame.setJMenuBar(menuBar);
MeganProperties.addPropertiesListListener(menuBar.getRecentFilesListener());
MeganProperties.notifyListChange(ProgramProperties.RECENTFILES);
ProjectManager.addAnotherWindowWithWindowMenu(dir, menuBar.getWindowMenu());
popupMenu = new PopupMenu(this, GUIConfiguration.getPopupMenuConfiguration(), getCommandManager());
frame.add(new ToolBar(this, GUIConfiguration.getToolBarConfiguration(), commandManager), BorderLayout.NORTH);
statusBar = new StatusBar();
frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
loader = new Loader(this);
rootNode = new NodeBase(dir.getDocument().getMeganFile().getName());
dataTree = new JTree(rootNode);
//dataTree.setRootVisible(false);
final String[] cNames = dir.getDocument().getActiveViewers().toArray(new String[0]);
NodeBase[] rootNodes = new NodeBase[cNames.length];
for (int i = 0; i < cNames.length; i++) {
String cName = cNames[i];
rootNodes[i] = new NodeBase(cName);
classification2RootNode.put(cName, rootNodes[i]);
}
dataTree.setRowHeight(0); //When row height is 0, each node determines its height from its contents.
dataTree.setShowsRootHandles(true);
{
MyTreeListener treeListener = new MyTreeListener(dir, this);
dataTree.addTreeWillExpandListener(treeListener);
dataTree.addTreeExpansionListener(treeListener);
}
dataTree.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
if (me.isPopupTrigger()) {
popupMenu.show(dataTree, me.getX(), me.getY());
}
}
public void mousePressed(MouseEvent me) {
if (me.isPopupTrigger()) {
popupMenu.show(dataTree, me.getX(), me.getY());
}
}
});
dataTree.addTreeSelectionListener(treeSelectionEvent -> getCommandManager().updateEnableState());
dataTree.setCellRenderer(new MultiLineCellRenderer());
scrollPane = new JScrollPane(dataTree);
mainPanel.add(scrollPane, BorderLayout.CENTER);
searchManager = new SearchManager(dir, this, new JTreeSearcher(dataTree), false, true);
final int[] geometry = ProgramProperties.get(MeganProperties.INSPECTOR_WINDOW_GEOMETRY, new int[]{100, 100, 300, 600});
frame.setLocationRelativeTo(MainViewer.getLastActiveFrame());
frame.setSize(geometry[2], geometry[3]);
frame.addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e) {
componentResized(e);
}
public void componentResized(ComponentEvent event) {
if ((event.getID() == ComponentEvent.COMPONENT_RESIZED || event.getID() == ComponentEvent.COMPONENT_MOVED) &&
(frame.getExtendedState() & JFrame.MAXIMIZED_HORIZ) == 0
&& (frame.getExtendedState() & JFrame.MAXIMIZED_VERT) == 0) {
ProgramProperties.put(MeganProperties.INSPECTOR_WINDOW_GEOMETRY, new int[]
{frame.getLocation().x, frame.getLocation().y, frame.getSize().width,
frame.getSize().height});
}
}
});
frame.addWindowListener(new WindowAdapter() {
public void windowActivated(WindowEvent event) {
final InputDialog inputDialog = InputDialog.getInstance();
if (inputDialog != null)
inputDialog.setViewer(dir, InspectorWindow.this);
}
public void windowClosing(WindowEvent event) {
if (dir.getDocument().getProgressListener() != null)
dir.getDocument().getProgressListener().setUserCancelled(true);
clear();
}
});
}
/**
* erase the tree
*/
public void clear() {
final DefaultTreeModel model = (DefaultTreeModel) dataTree.getModel();
for (NodeBase root : classification2RootNode.values()) {
root.removeAllChildren();
model.nodeStructureChanged(root);
}
}
/**
* add a top-level node.
*
*/
public void addTopLevelNode(final LinkedList<Triplet<String, Float, Collection<Integer>>> name2Count2Ids, final String classificationName) {
final NodeBase classificationRoot = classification2RootNode.get(classificationName);
if (classificationRoot == null)
return;
if (!rootNode.isNodeChild(classificationRoot)) {
try {
rootNode.add(classificationRoot);
((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(rootNode);
} catch (Exception e) {
e.printStackTrace();
}
}
dataTree.expandPath(new TreePath(new Object[]{rootNode, classificationRoot}));
statusBar.setText2("Rows: " + countVisibleNodes());
loader.execute(progressListener -> {
progressListener.setMaximum(name2Count2Ids.size());
progressListener.setProgress(0);
long startTime = System.currentTimeMillis();
long diff = 500;
boolean needsFinalRefresh = false;
try {
for (final Triplet<String, Float, Collection<Integer>> triplet : name2Count2Ids) {
final String name = triplet.getFirst();
boolean isPresent = false;
// first determine whether taxon already present as child of parent:
Enumeration level1Enumeration = classificationRoot.children();
while (!isPresent && level1Enumeration.hasMoreElements()) {
NodeBase level1Node = (NodeBase) level1Enumeration.nextElement();
if (level1Node instanceof TopLevelNode && level1Node.getName().equals(name)) {
isPresent = true;
}
}
if (!isPresent) {
final boolean doRefresh = (System.currentTimeMillis() - startTime > diff);
if (doRefresh) {
diff *= 2;
}
SwingUtilities.invokeAndWait(() -> {
try {
final NodeBase node = new TopLevelNode(name, Math.round(triplet.getSecond()), triplet.getThird(), classificationName);
classificationRoot.add(node);
if (doRefresh) {
((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(classificationRoot);
statusBar.setText2("Rows: " + countVisibleNodes());
}
} catch (Exception ex) {
// Basic.caught(ex);
}
});
needsFinalRefresh = !doRefresh;
}
progressListener.incrementProgress();
}
} finally {
if (needsFinalRefresh) {
SwingUtilities.invokeLater(() -> ((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(classificationRoot));
}
}
});
}
/**
* add a top-level node.
*
*/
public void addTopLevelNode(final String name, final Object key, final String classificationName) {
final NodeBase classificationRoot = classification2RootNode.get(classificationName);
if (classificationRoot == null)
return;
if (!rootNode.isNodeChild(classificationRoot)) {
try {
rootNode.add(classificationRoot);
((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(rootNode);
statusBar.setText2("Rows: " + countVisibleNodes());
} catch (Exception e) {
e.printStackTrace();
}
}
dataTree.expandPath(new TreePath(classificationRoot));
loader.execute(progressListener -> {
progressListener.setMaximum(-1);
boolean isPresent = false;
// first determine whether taxon already present as child of parent:
Enumeration level1Enumeration = classificationRoot.children();
while (!isPresent && level1Enumeration.hasMoreElements()) {
NodeBase level1Node = (NodeBase) level1Enumeration.nextElement();
if (level1Node instanceof TopLevelNode && level1Node.getName().equals(name)) {
isPresent = true;
}
}
if (!isPresent) {
final int classId = (Integer) key;
final int size = dir.getDocument().getConnector().getClassSize(classificationName, classId);
SwingUtilities.invokeAndWait(() -> {
classificationRoot.add(new TopLevelNode(name, size, classId, classificationName));
((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(classificationRoot);
});
}
});
}
/**
* adds a list of reads below the root
*
*/
public void addTopLevelReadNode(final IReadBlock readBlock, String classificationName) {
final NodeBase classificationRoot = classification2RootNode.get(classificationName);
if (classificationRoot == null)
return;
String readName = readBlock.getReadName();
for (int i = 0; i < classificationRoot.getChildCount(); i++) {
NodeBase child = (NodeBase) classificationRoot.getChildAt(i);
if (child.getName().equals(readName))
return;
}
final ReadHeadLineNode node = new ReadHeadLineNode(readBlock);
try {
SwingUtilities.invokeAndWait(() -> {
classificationRoot.add(node);
((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(classificationRoot);
});
} catch (InterruptedException | InvocationTargetException e) {
Basic.caught(e);
}
}
/**
* add all read level nodes below a top-level node
*
*/
public void addChildren(final TopLevelNode parent) {
loader.execute(progressListener -> {
long lastRefreshTime = System.currentTimeMillis();
long diff = 10;
boolean needsFinalRefresh = false;
try {
progressListener.setMaximum((int) parent.getRank());
progressListener.setProgress(0);
IConnector connector = dir.getDocument().getConnector();
try (IReadBlockIterator it = connector.getReadsIteratorForListOfClassIds(parent.getClassificationName(), parent.getClassIds(), 0, 100000, true, true)) {
while (it.hasNext()) {
IReadBlock readBlock = it.next();
if (readBlock != null) {
final ReadHeadLineNode node = new ReadHeadLineNode(readBlock);
final boolean doRefresh = (System.currentTimeMillis() - lastRefreshTime > diff);
if (doRefresh) {
if (diff == 10)
diff = 50;
else
diff *= 2;
}
SwingUtilities.invokeAndWait(() -> {
parent.add(node);
if (doRefresh) {
if (sortReadsAlphabetically)
sortChildrenAlphabetically(parent);
((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(parent);
statusBar.setText2("Rows: " + countVisibleNodes());
}
});
if (doRefresh)
lastRefreshTime = System.currentTimeMillis();
needsFinalRefresh = !doRefresh;
}
progressListener.incrementProgress();
}
}
} catch (CanceledException ex) {
parent.setCompleted(false);
throw ex;
} finally {
if (needsFinalRefresh) {
SwingUtilities.invokeLater(() -> {
if (sortReadsAlphabetically)
sortChildrenAlphabetically(parent);
((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(parent);
statusBar.setText2("Rows: " + countVisibleNodes());
});
}
}
});
}
/**
* add all match level nodes below a read-level node
*
*/
public void addChildren(final ReadHeadLineNode parent, final String classificationName) {
loader.execute(progressListener -> {
boolean needsFinalRefresh = true; // true, because we add data node before entering loop
try {
progressListener.setMaximum((int) parent.getRank());
progressListener.setProgress(0);
IConnector connector = dir.getDocument().getConnector();
long uId = parent.getUId();
IReadBlock readBlock;
try (IReadBlockGetter readBlockGetter = connector.getReadBlockGetter(0, 100000, true, true)) {
readBlock = readBlockGetter.getReadBlock(uId);
}
final String header = readBlock.getReadHeader();
final String sequence = readBlock.getReadSequence();
int length = readBlock.getReadLength();
if (length == 0 && sequence != null)
length = StringUtils.getNumberOfNonSpaceCharacters(sequence);
parent.setCompleted(true);
final ReadDataHeadLineNode readDataHeadLineNode = new ReadDataHeadLineNode("DATA", length, readBlock.getComplexity(), readBlock.getReadWeight(), header + (sequence != null ? "\n" + sequence : ""));
// add data node
SwingUtilities.invokeAndWait(() -> parent.add(readDataHeadLineNode));
long lastRefreshTime = System.currentTimeMillis();
long diff = 10;
final Document doc = dir.getDocument();
final BitSet activeMatches = new BitSet();
ActiveMatches.compute(doc.getMinScore(), doc.isLongReads() ? 100 : doc.getTopPercent(), doc.getMaxExpected(), doc.getMinPercentIdentity(), readBlock, classificationName, activeMatches);
for (int m = 0; m < readBlock.getNumberOfAvailableMatchBlocks(); m++) {
IMatchBlock matchBlock = readBlock.getMatchBlock(m);
final StringBuilder buf = new StringBuilder();
final int taxId = matchBlock.getTaxonId();
{
String taxonName = TaxonomyData.getName2IdMap().get(taxId);
if (taxonName == null) {
if (taxId > 0)
buf.append(String.format("%d;", taxId));
else
buf.append("?;");
} else
buf.append(taxonName).append(";");
}
for (String cName : doc.getActiveViewers()) {
if (!cName.equals(Classification.Taxonomy)) {
final int id = matchBlock.getId(cName);
if (id > 0) {
String label = ClassificationManager.get(cName, true).getName2IdMap().get(id);
if (label != null) {
label = StringUtils.abbreviateDotDotDot(label, 50);
buf.append(" ").append(label).append(";");
}
}
}
}
final MatchHeadLineNode node = new MatchHeadLineNode(buf.toString(), matchBlock.getBitScore(), matchBlock.isIgnore(), activeMatches.get(m), matchBlock.getUId(), taxId, matchBlock.getText());
// add match node
final boolean doRefresh = (System.currentTimeMillis() - lastRefreshTime > diff);
if (doRefresh) {
if (diff == 10)
diff = 50;
else
diff *= 2;
}
SwingUtilities.invokeAndWait(() -> {
parent.add(node);
if (doRefresh) {
((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(parent);
statusBar.setText2("Rows: " + countVisibleNodes());
}
});
if (doRefresh)
lastRefreshTime = System.currentTimeMillis();
needsFinalRefresh = !doRefresh;
progressListener.incrementProgress();
}
} catch (CanceledException ex) {
parent.setCompleted(false);
throw ex;
} finally {
if (needsFinalRefresh) {
SwingUtilities.invokeLater(() -> {
((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(parent);
statusBar.setText2("Rows: " + countVisibleNodes());
});
}
}
});
}
/**
* add children to read level data node
*
*/
public void addChildren(final ReadDataHeadLineNode parent) {
parent.add(new ReadDataTextNode(parent.getData()));
}
/**
* add all read level nodes below a match-level node
*
*/
public void addChildren(final MatchHeadLineNode parent) {
loader.execute(progressListener -> {
progressListener.setMaximum(-1);
final MatchTextNode node = new MatchTextNode(parent.getMatchText() == null ? "Unknown" : parent.getMatchText());
SwingUtilities.invokeAndWait(() -> {
parent.add(node);
((DefaultTreeModel) dataTree.getModel()).nodeStructureChanged(parent);
});
});
}
/**
* sort all children of a node by rank
*
*/
private void sortChildrenByRank(NodeBase node) {
SortedSet<NodeBase> children = new TreeSet<>();
for (int i = 0; i < node.getChildCount(); i++) {
NodeBase child = (NodeBase) node.getChildAt(i);
children.add(child);
}
node.removeAllChildren();
for (NodeBase a : children) {
node.add(a);
}
}
/**
* sort all children of a node by rank
*
*/
private void sortChildrenAlphabetically(NodeBase node) {
SortedSet<NodeBase> children = new TreeSet<>((n1, n2) -> {
int value = n1.getName().compareTo(n2.getName());
if (value == 0)
return String.format("%5d", n1.getId()).compareTo(String.format("%5d", n2.getId()));
else
return value;
});
for (int i = 0; i < node.getChildCount(); i++) {
NodeBase child = (NodeBase) node.getChildAt(i);
children.add(child);
}
node.removeAllChildren();
for (NodeBase a : children) {
node.add(a);
}
}
/**
* return the frame associated with the viewer
*
* @return frame
*/
public JFrame getFrame() {
return frame;
}
/**
* gets the title
*
* @return title
*/
public String getTitle() {
return frame.getTitle();
}
/**
* is viewer uptodate?
*
* @return uptodate
*/
public boolean isUptoDate() {
return uptodate;
}
/**
* ask view to destroy itself
*/
public void destroyView() {
frame.setVisible(false);
MeganProperties.removePropertiesListListener(menuBar.getRecentFilesListener());
dir.removeViewer(this);
searchManager.getFindDialogAsToolBar().close();
// cancel anything that is running:
if (getDir().getDocument().getProgressListener() != null)
getDir().getDocument().getProgressListener().setUserCancelled(true);
frame.dispose();
}
/**
* ask view to prevent user input
*/
public void lockUserInput() {
isLocked = true;
getCommandManager().setEnableCritical(false);
searchManager.getFindDialogAsToolBar().setEnableCritical(false);
frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
statusBar.setText2("Busy...");
menuBar.setEnableRecentFileMenuItems(false);
}
/**
* set uptodate state
*
*/
public void setUptoDate(boolean flag) {
uptodate = flag;
}
/**
* ask view to allow user input
*/
public void unlockUserInput() {
getCommandManager().setEnableCritical(true);
searchManager.getFindDialogAsToolBar().setEnableCritical(true);
frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
statusBar.setText2("");
menuBar.setEnableRecentFileMenuItems(true);
isLocked = false;
}
/**
* ask view to rescan itself. This is method is wrapped into a runnable object
* and put in the swing event queue to avoid concurrent modifications.
*
* @param what what should be updated? Possible values: Director.ALL or Director.TITLE
*/
public void updateView(String what) {
uptodate = false;
if (doClear) {
clear();
doClear = false;
}
commandManager.updateEnableState();
setTitle();
statusBar.setText2("Rows: " + countVisibleNodes());
uptodate = true;
FindToolBar findToolBar = searchManager.getFindDialogAsToolBar();
if (findToolBar.isClosing()) {
showFindToolBar = false;
findToolBar.setClosing(false);
}
if (!findToolBar.isEnabled() && showFindToolBar) {
mainPanel.add(findToolBar, BorderLayout.NORTH);
findToolBar.setEnabled(true);
frame.getContentPane().validate();
getCommandManager().updateEnableState();
} else if (findToolBar.isEnabled() && !showFindToolBar) {
mainPanel.remove(findToolBar);
findToolBar.setEnabled(false);
frame.getContentPane().validate();
getCommandManager().updateEnableState();
}
if (findToolBar.isEnabled())
findToolBar.clearMessage();
}
/**
* count visible nodes
*
* @return number of visible nodes
*/
private int countVisibleNodes() {
int count = 0;
for (NodeBase root : classification2RootNode.values()) {
// todo: fix this
Stack<NodeBase> stack = new Stack<>();
if (root != null) {
stack.push(root);
while (stack.size() > 0) {
NodeBase node = stack.pop();
if (dataTree.isVisible(new TreePath(node.getPath())))
count++;
for (int i = 0; i < node.getChildCount(); i++) {
NodeBase child = (NodeBase) node.getChildAt(i);
stack.add(child);
}
}
}
}
return count;
}
/**
* expand the given node
*
*/
public void expand(NodeBase v) {
if (v != null) {
for (Enumeration descendants = v.breadthFirstEnumeration(); descendants.hasMoreElements(); ) {
v = (NodeBase) descendants.nextElement();
dataTree.expandPath(new TreePath(v.getPath()));
}
}
}
/**
* expand an array of paths
*
*/
public void expand(TreePath[] paths) {
boolean first = true;
for (TreePath path : paths) {
if (!dataTree.isExpanded(path)) {
dataTree.expandPath(path);
if (first) {
dataTree.repaint();
dataTree.scrollRowToVisible(dataTree.getRowForPath(path));
first = false;
}
}
}
}
/**
* collapse the given node or root
*
*/
public void collapse(NodeBase v) {
if (v != null) {
for (Enumeration descendants = v.depthFirstEnumeration(); descendants.hasMoreElements(); ) {
v = (NodeBase) descendants.nextElement();
dataTree.collapsePath(new TreePath(v.getPath()));
}
}
}
/**
* collapse an array of paths
*
*/
public void collapse(TreePath[] paths) {
for (TreePath path : paths) {
collapse((NodeBase) path.getLastPathComponent());
}
}
/**
* set the title of the window
*/
private void setTitle() {
String newTitle = "Inspector - " + dir.getDocument().getTitle();
if (isDirty())
newTitle += "*";
if (dir.getID() == 1)
newTitle += " - " + ProgramProperties.getProgramVersion();
else
newTitle += " - [" + dir.getID() + "] - " + ProgramProperties.getProgramVersion();
if (!frame.getTitle().equals(newTitle)) {
frame.setTitle(newTitle);
ProjectManager.updateWindowMenus();
}
}
/**
* returns the read head node in a path
*
* @return read head node or null
*/
private ReadHeadLineNode getReadHeadLineNodeFromPath(TreePath path) {
Object[] components = path.getPath();
for (Object component : components) {
if (component instanceof ReadHeadLineNode)
return (ReadHeadLineNode) component;
}
return null;
}
/**
* returns the match head node in a path
*
* @return read head node or null
*/
private MatchHeadLineNode getMatchHeadLineNodeFromPath(TreePath path) {
Object[] components = path.getPath();
for (Object component : components) {
if (component instanceof MatchHeadLineNode)
return (MatchHeadLineNode) component;
}
return null;
}
/**
* does window currently have a selected read headline node?
*
* @return true, if some read headline node is selected
*/
public boolean hasSelectedReadHeadLineNodes() {
if (dataTree != null) {
TreePath[] paths = dataTree.getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
if (getReadHeadLineNodeFromPath(path) != null)
return true;
}
}
}
return false;
}
/**
* get all selected read headline nodes
*
* @return all selected read headline nodes
*/
public ArrayList<ReadHeadLineNode> getAllSelectedReadHeadLineNodes() {
ArrayList<ReadHeadLineNode> list = new ArrayList<>();
TreePath[] paths = dataTree.getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
ReadHeadLineNode node = getReadHeadLineNodeFromPath(path);
if (node != null)
list.add(node);
}
}
return list;
}
/**
* does window currently have a selected read headline node?
*
* @return true, if some match headline node is selected
*/
public boolean hasSelectedMatchHeadLineNodes() {
if (dataTree != null) {
TreePath[] paths = dataTree.getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
if (getMatchHeadLineNodeFromPath(path) != null)
return true;
}
}
}
return false;
}
/**
* get all selected read headline nodes
*
* @return all selected read headline nodes
*/
public ArrayList<MatchHeadLineNode> getAllSelectedMatchHeadLineNodes() {
ArrayList<MatchHeadLineNode> list = new ArrayList<>();
TreePath[] paths = dataTree.getSelectionPaths();
if (paths != null) {
for (TreePath path : paths) {
MatchHeadLineNode node = getMatchHeadLineNodeFromPath(path);
if (node != null)
list.add(node);
}
}
return list;
}
private boolean isDirty() {
return isDirty;
}
public void setDirty(boolean dirty) {
if (dirty != isDirty) {
isDirty = dirty;
setTitle();
}
}
public boolean isLocked() {
return isLocked;
}
public boolean hasSelectedNodes() {
return dataTree != null && dataTree.getSelectionCount() > 0;
}
/**
* delete all the selected nodes
*/
public void deleteSelectedNodes() {
DefaultTreeModel model = (DefaultTreeModel) dataTree.getModel();
TreePath[] selectedPaths = dataTree.getSelectionPaths();
if (selectedPaths != null) {
for (TreePath selectedPath : selectedPaths) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
node.removeAllChildren();
model.nodeStructureChanged(node);
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
if (parent != null) {
parent.remove(node);
model.nodeStructureChanged(parent);
}
}
}
}
/**
* gets the associated command manager
*
* @return command manager
*/
public CommandManager getCommandManager() {
return commandManager;
}
public JTree getDataTree() {
return dataTree;
}
/**
* Print the graph associated with this viewer.
*
* @param gc0 the graphics context.
* @param format page format
* @param pagenumber page index
*/
public int print(Graphics gc0, PageFormat format, int pagenumber) {
Component panel = scrollPane.getViewport().getComponent(0);
if (panel != null && pagenumber == 0) {
Graphics2D gc = ((Graphics2D) gc0);
Dimension dim = panel.getPreferredSize();
int image_w = dim.width;
int image_h = dim.height;
double paper_x = format.getImageableX() + 1;
double paper_y = format.getImageableY() + 1;
double paper_w = format.getImageableWidth() - 2;
double paper_h = format.getImageableHeight() - 2;
double scale_x = paper_w / image_w;
double scale_y = paper_h / image_h;
double scale = Math.min(scale_x, scale_y);
double shift_x = paper_x + (paper_w - scale * image_w) / 2.0;
double shift_y = paper_y + (paper_h - scale * image_h) / 2.0;
gc.translate(shift_x, shift_y);
gc.scale(scale, scale);
panel.print(gc0);
return Printable.PAGE_EXISTS;
}
return Printable.NO_SUCH_PAGE;
}
public NodeBase getRoot(String cName) {
return classification2RootNode.get(cName);
}
public boolean isSortReadsAlphabetically() {
return sortReadsAlphabetically;
}
public void setSortReadsAlphabetically(boolean sortReadsAlphabetically) {
this.sortReadsAlphabetically = sortReadsAlphabetically;
}
public boolean isShowFindToolBar() {
return showFindToolBar;
}
public void setShowFindToolBar(boolean showFindToolBar) {
this.showFindToolBar = showFindToolBar;
}
public SearchManager getSearchManager() {
return searchManager;
}
public String getSelection() {
final StringBuilder buf = new StringBuilder();
final TreePath[] selectedPaths = dataTree.getSelectionPaths();
if (selectedPaths != null) {
for (TreePath selectedPath : selectedPaths) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
buf.append(node.toString()).append("\n");
}
}
return buf.toString();
}
/**
* get name for this type of viewer
*
* @return name
*/
public String getClassName() {
return "InspectorWindow";
}
public Map<String, NodeBase> getClassification2RootNode() {
return classification2RootNode;
}
@Override
public boolean isReadsAvailable() {
return getReads(1).size() > 0;
}
@Override
public Collection<Pair<String, String>> getReads(int maxNumber) {
ArrayList<Pair<String, String>> list = new ArrayList<>(Math.min(1000, maxNumber));
if (dataTree != null) {
final TreePath[] selectedPaths = dataTree.getSelectionPaths();
if (selectedPaths != null) {
for (TreePath selectedPath : selectedPaths) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
if (node instanceof ReadHeadLineNode) {
final ReadHeadLineNode readHeadLineNode = (ReadHeadLineNode) node;
if (readHeadLineNode.getReadHeader() != null && readHeadLineNode.getReadSequence() != null) {
list.add(new Pair<>(readHeadLineNode.getReadHeader(), readHeadLineNode.getReadSequence()));
if (list.size() >= maxNumber)
return list;
}
}
}
}
}
return list;
}
private Director getDir() {
return dir;
}
}
class MyTreeListener implements TreeWillExpandListener, TreeExpansionListener {
private final Director dir;
private final InspectorWindow inspectorWindow;
MyTreeListener(Director dir, InspectorWindow inspectorWindow) {
this.dir = dir;
this.inspectorWindow = inspectorWindow;
}
/**
* Invoked whenever a node in the tree is about to be collapsed.
*/
public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
if (inspectorWindow.isLocked()) {
if (dir.getDocument().getProgressListener() != null)
dir.getDocument().getProgressListener().setUserCancelled(true);
throw new ExpandVetoException(event);
}
}
/**
* Called whenever an item in the tree has been collapsed.
*/
public void treeCollapsed(TreeExpansionEvent event) {
final TreePath path = event.getPath();
final NodeBase node = (NodeBase) path.getLastPathComponent();
if (!inspectorWindow.getClassification2RootNode().containsValue(node)) {
//node.removeAllChildren();
DefaultTreeModel model = (DefaultTreeModel) inspectorWindow.dataTree.getModel();
model.nodeStructureChanged(node);
}
inspectorWindow.updateView(Director.ALL);
}
/**
* Called whenever an item in the tree has been expanded.
*/
public void treeExpanded(TreeExpansionEvent event) {
inspectorWindow.updateView(Director.ALL);
}
/**
* Invoked whenever a node in the tree is about to be expanded.
*/
public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
if (inspectorWindow.isLocked()) {
if (dir.getDocument().getProgressListener() != null)
dir.getDocument().getProgressListener().setUserCancelled(true);
throw new ExpandVetoException(event);
}
final TreePath path = event.getPath();
final NodeBase node = (NodeBase) path.getLastPathComponent();
if (node.getChildCount() > 0) { // has already been expanded
if (node.isCompleted())
return;
else {
int result = JOptionPane.showConfirmDialog(inspectorWindow.getFrame(), "List of children incomplete, re-fetch?", "Re-fetch", JOptionPane.YES_NO_CANCEL_OPTION);
if (result == JOptionPane.NO_OPTION)
return;
else if (result == JOptionPane.CANCEL_OPTION)
throw new ExpandVetoException(event);
else // remove all children to trigger re-download
node.removeAllChildren();
}
}
if (node instanceof TopLevelNode) {
inspectorWindow.addChildren((TopLevelNode) node);
} else if (node instanceof ReadHeadLineNode) {
inspectorWindow.addChildren((ReadHeadLineNode) node, path.getPathComponent(1).toString());
}
if (node instanceof ReadDataHeadLineNode) {
inspectorWindow.addChildren((ReadDataHeadLineNode) node);
} else if (node instanceof MatchHeadLineNode) {
inspectorWindow.addChildren((MatchHeadLineNode) node);
}
}
}
| 42,083 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
MatchTextNode.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/MatchTextNode.java | /*
* MatchTextNode.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
/**
* leaf node that represents the text of an alignment
* Daniel Huson, 2.2006
*/
public class MatchTextNode extends NodeBase {
private final String text;
public MatchTextNode(String text) {
if (text == null)
text = "Null";
if (text.endsWith("\n"))
this.text = text;
else
this.text = text + "\n";
}
public boolean isLeaf() {
return true;
}
public String toString() {
return text;
}
public String getText() {
return text;
}
}
| 1,388 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
GUIConfiguration.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/GUIConfiguration.java | /*
* GUIConfiguration.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
import jloda.swing.window.MenuConfiguration;
import megan.classification.data.ClassificationCommandHelper;
/**
* configuration for menu and toolbar
* Daniel Huson, 7.2010
*/
class GUIConfiguration {
/**
* get the menu configuration
*
* @return menu configuration
*/
public static MenuConfiguration getMenuConfiguration() {
MenuConfiguration menuConfig = new MenuConfiguration();
menuConfig.defineMenuBar("File;Edit;Options;Window;Help;");
menuConfig.defineMenu("File", "New...;|;Open...;@Open Recent;|;Open From Server...;|;Compare...;|;Import From BLAST...;@Import;Meganize DAA File...;|;Export Selected Text...;Export Image...;Export Legend...;|;Page Setup...;Print...;|;Close;|;Quit;");
menuConfig.defineMenu("Open Recent", ";");
menuConfig.defineMenu("Import", "Import Text (CSV) Format...;Import BIOM Format...;|;Import Metadata...;");
menuConfig.defineMenu("Edit", "Inspector Cut;Inspector Copy;Inspector Paste;|;Clear;|;Select All;Select None;|;Find...;Find Again;|;Show Taxon...;Show Reads...;");
menuConfig.defineMenu("Options", "BLAST on NCBI...;|;Collapse Inspector;Expand Inspector;|;Disable Taxon For Match;|;Sort Reads Alphabetically;");
menuConfig.defineMenu("Window", "Close All Other Windows...;|;Reset Window Location;Set Window Size...;|;Message Window...;|;" +
"Inspector Window...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;|;");
menuConfig.defineMenu("Help", "About...;How to Cite...;|;Community Website...;Reference Manual...;|;Check For Updates...;");
return menuConfig;
}
/**
* gets the toolbar configuration
*
* @return toolbar configuration
*/
public static String getToolBarConfiguration() {
return "Open...;Print...;Export Image...;|;Find...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "";
}
/**
* gets the toolbar configuration
*
* @return toolbar configuration
*/
public static String getPopupMenuConfiguration() {
return "Inspector Copy;As Text...;|;Disable Taxon For Match;|;Clear;";
}
}
| 3,068 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
TopLevelNode.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/TopLevelNode.java | /*
* TopLevelNode.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* node to represent top-level taxon
* Daniel Huson, 2.2006
*/
public class TopLevelNode extends NodeBase {
private final String classificationName;
private final Set<Integer> classIds = new HashSet<>();
public TopLevelNode(String name, int count, int classId, String classificationName) {
super(name);
this.rank = count;
classIds.add(classId);
this.classificationName = classificationName;
}
public TopLevelNode(String name, int count, Collection<Integer> classIds, String classificationName) {
super(name);
this.rank = count;
this.classIds.addAll(classIds);
this.classificationName = classificationName;
}
public String toString() {
if (rank > -1)
return String.format("%s [%,d]", getName(), (int) rank);
else
return getName();
}
public boolean isLeaf() {
return rank == 0;
}
public String getClassificationName() {
return classificationName;
}
public Set<Integer> getClassIds() {
return classIds;
}
}
| 2,012 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ReadHeadLineNode.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/ReadHeadLineNode.java | /*
* ReadHeadLineNode.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
import megan.data.IReadBlock;
/**
* node to represent the head line for a read
* Daniel Huson, 2.2006
*/
public class ReadHeadLineNode extends NodeBase {
private final String readHeader;
private final String readSequence;
private final long uid;
/**
* constructor
*
*/
public ReadHeadLineNode(IReadBlock readBlock) {
super(readBlock.getReadName());
this.readHeader = readBlock.getReadHeader();
this.readSequence = readBlock.getReadSequence();
this.uid = readBlock.getUId();
this.rank = readBlock.getNumberOfMatches();
}
public boolean isLeaf() {
return readHeader == null; // never leaf, because at least data node is contained below
}
public String toString() {
if (getReadLength() <= 0) {
if (rank <= 0)
return getName();
else
return String.format("%s [matches=%,d]", getName(), (int) rank);
} else // readLength>0
{
if (rank <= 0)
return String.format("%s [length=%,d]", getName(), getReadLength());
else
return String.format("%s [length=%,d, matches=%,d]", getName(), getReadLength(), (int) rank);
}
}
public long getUId() {
return uid;
}
private int getReadLength() {
return readSequence != null ? readSequence.length() : 0;
}
public String getReadHeader() {
return readHeader;
}
public String getReadSequence() {
return readSequence;
}
}
| 2,401 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Loader.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/Loader.java | /*
* Loader.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector;
import jloda.fx.util.ProgramExecutorService;
import jloda.swing.util.ProgressDialog;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.Basic;
import jloda.util.CanceledException;
import megan.core.Director;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Future;
/**
* load data into node and then a node into the inspector
* Daniel Huson, 9.2009
*/
public class Loader {
private final InspectorWindow inspectorWindow;
private Future future;
private final Queue<LoaderTask> tasks = new LinkedList<>();
/**
* constructor
*
*/
public Loader(InspectorWindow inspectorWindow) {
this.inspectorWindow = inspectorWindow;
}
/**
* execute a loader task. Either immediately, if nothing is running, or later
*
*/
public void execute(final LoaderTask task) {
tasks.add(task);
processQueue();
}
/**
* runs all loader tasks in queue
*/
private void processQueue() {
final Director dir = inspectorWindow.dir;
if (!dir.isLocked() && (future == null || future.isDone())) {
future = ProgramExecutorService.getInstance().submit(() -> {
ProgressDialog progressDialog = new ProgressDialog("", "", inspectorWindow.getFrame());
dir.getDocument().setProgressListener(progressDialog);
try {
dir.notifyLockInput();
progressDialog.setTasks("Loading data from file", inspectorWindow.dir.getDocument().getMeganFile().getName());
progressDialog.setDebug(Basic.getDebugMode());
while (tasks.size() > 0) {
final LoaderTask task = tasks.remove();
// System.err.println("Task: " + task);
try {
task.run(progressDialog);
} catch (CanceledException ex) {
// System.err.println("USER CANCELED EXECUTE");
} catch (Exception ex) {
Basic.caught(ex);
NotificationsInSwing.showError(inspectorWindow.getFrame(), "Load data failed: " + ex.getMessage());
}
}
} finally {
dir.getDocument().getProgressListener().close();
dir.notifyUnlockInput();
inspectorWindow.updateView(Director.ALL);
}
});
}
}
}
| 3,390 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExpandNodesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/ExpandNodesCommand.java | /*
* ExpandNodesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.inspector.InspectorWindow;
import megan.inspector.NodeBase;
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class ExpandNodesCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
final InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
final TreePath[] paths = inspectorWindow.getDataTree().getSelectionPaths();
if (paths != null) {
inspectorWindow.expand(paths);
} else {
for (NodeBase root : inspectorWindow.getClassification2RootNode().values()) {
inspectorWindow.expand(root);
}
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "expand;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
executeImmediately(getSyntax());
}
public String getName() {
return "Expand";
}
private static final String ALTNAME = "Expand Inspector";
public String getAltName() {
return ALTNAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Expand the selected nodes, or all, if none selected";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_J, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow != null && inspectorWindow.getDataTree() != null && inspectorWindow.getDataTree().getModel() != null && inspectorWindow.getDataTree().getModel().getRoot() != null
&& inspectorWindow.getDataTree().getModel().getChildCount(inspectorWindow.getDataTree().getModel().getRoot()) > 0;
}
}
| 3,855 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
DisableTaxonCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/DisableTaxonCommand.java | /*
* DisableTaxonCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.ICommand;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.commands.clipboard.ClipboardBase;
import megan.inspector.InspectorWindow;
import megan.inspector.MatchHeadLineNode;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Set;
import java.util.TreeSet;
/**
* disable taxon associated with selected match
* Daniel Huson, Nov 2017
*/
public class DisableTaxonCommand extends ClipboardBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
final Set<Integer> set = new TreeSet<>();
final InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
for (MatchHeadLineNode node : inspectorWindow.getAllSelectedMatchHeadLineNodes()) {
if (node.getTaxId() > 0)
set.add(node.getTaxId());
}
if (set.size() > 10 && JOptionPane.showConfirmDialog(getViewer().getFrame(), "Do you really want to disable " + set.size() +
" taxa?", "Confirmation - MEGAN", JOptionPane.YES_NO_CANCEL_OPTION) != JOptionPane.YES_OPTION)
return;
if (set.size() > 0)
execute("disable taxa=" + StringUtils.toString(set, " ") + ";");
}
public boolean isApplicable() {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow != null && inspectorWindow.hasSelectedMatchHeadLineNodes();
}
private static final String NAME = "Disable Taxon";
public String getName() {
return NAME;
}
public String getAltName() {
return "Disable Taxon For Match";
}
public String getDescription() {
return "Disable the taxon associated with this match";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
}
| 2,837 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowReadsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/ShowReadsCommand.java | /*
* ShowReadsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.util.CanceledException;
import jloda.util.Single;
import jloda.util.parse.NexusStreamParser;
import jloda.util.progress.ProgressListener;
import megan.classification.Classification;
import megan.core.Director;
import megan.data.FindSelection;
import megan.inspector.InspectorWindow;
import megan.main.MeganProperties;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* find reads and display in inspector window
* Daniel Huson, 11.2010
*/
public class ShowReadsCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show read=");
String regExpression = np.getWordRespectCase();
np.matchIgnoreCase(";");
final var inspectorWindow = (InspectorWindow) getViewer();
ProgramProperties.put(MeganProperties.FINDREAD, regExpression);
final var doc = ((Director) getDir()).getDocument();
final var findSelection = new FindSelection();
findSelection.useReadName = true;
final ProgressListener progress = doc.getProgressListener();
progress.setTasks("Searching for reads", "");
progress.setProgress(0);
final var canceled = new Single<>(false);
final var matchesFound = new Single<>(0);
try (var it = doc.getConnector().getFindAllReadsIterator(regExpression, findSelection, canceled)) {
progress.setMaximum(it.getMaximumProgress());
final ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(() -> {
try {
while (!canceled.get()) {
progress.setProgress(it.getProgress());
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CanceledException ex) {
System.err.println("USER CANCELED EXECUTE");
} finally {
canceled.set(true);
executor.shutdownNow();
}
});
try {
while (it.hasNext()) {
inspectorWindow.addTopLevelReadNode(it.next(), Classification.Taxonomy);
matchesFound.set(matchesFound.get() + 1);
progress.setSubtask(matchesFound.get() + " found");
}
} finally {
canceled.set(true);
}
}
System.err.println("Found: " + matchesFound.get());
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "show read=<regex>;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
var inspectorWindow = (InspectorWindow) getViewer();
var regularExpression = ProgramProperties.get(MeganProperties.FINDREAD, "");
regularExpression = JOptionPane.showInputDialog(inspectorWindow.getFrame(), "Enter regular expression for read names:", regularExpression);
if (regularExpression != null && regularExpression.trim().length() != 0) {
regularExpression = regularExpression.trim();
ProgramProperties.put(MeganProperties.FINDREAD, regularExpression);
execute("show read='" + regularExpression + "';");
}
}
private static final String NAME = "Show Reads...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show all reads whose names match the given regular expression";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
var inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow != null;
}
}
| 5,902 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
PasteCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/PasteCommand.java | /*
* PasteCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.clipboard.ClipboardBase;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class PasteCommand extends ClipboardBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
}
public boolean isApplicable() {
return false;
}
private static final String ALT_NAME = "Inspector Paste";
public String getAltName() {
return ALT_NAME;
}
public String getName() {
return "Paste";
}
public String getDescription() {
return "Paste";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Paste16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,010 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SortReadsAlphabeticallyCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/SortReadsAlphabeticallyCommand.java | /*
* SortReadsAlphabeticallyCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.inspector.InspectorWindow;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class SortReadsAlphabeticallyCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow.isSortReadsAlphabetically();
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set sortreads=");
String which = np.getWordMatchesIgnoringCase("alphabetically no");
np.matchIgnoreCase(";");
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
inspectorWindow.setSortReadsAlphabetically(which.equalsIgnoreCase("alphabetically"));
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "set sortreads={alphabetically|no};";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
executeImmediately("set sortreads=" + (isSelected() ? "no" : "alphabetically") + ";");
}
public String getName() {
return "Sort Reads Alphabetically";
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Sort reads alphabetically";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow != null;
}
}
| 3,395 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectNoneCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/SelectNoneCommand.java | /*
* SelectNoneCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.inspector.InspectorWindow;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectNoneCommand extends CommandBase implements ICommand {
public String getSyntax() {
return null;
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
executeImmediately("select items=none;");
}
public boolean isApplicable() {
return getViewer() instanceof InspectorWindow && ((InspectorWindow) getViewer()).getDataTree() != null &&
((InspectorWindow) getViewer()).getDataTree().getSelectionCount() > 0;
}
public String getName() {
return "Select None";
}
public String getDescription() {
return "Select none";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() | InputEvent.SHIFT_DOWN_MASK);
}
}
| 2,359 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ListAsTextCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/ListAsTextCommand.java | /*
* ListAsTextCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.clipboard.ClipboardBase;
import megan.core.Director;
import megan.inspector.InspectorWindow;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.event.ActionEvent;
public class ListAsTextCommand extends ClipboardBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
JTree dataTree = inspectorWindow.getDataTree();
StringBuilder builder = new StringBuilder();
TreePath[] selectedPaths = dataTree.getSelectionPaths();
if (selectedPaths != null) {
for (TreePath selectedPath : selectedPaths) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectedPath.getLastPathComponent();
builder.append(node.toString()).append("\n");
}
}
if (builder.toString().length() > 0) {
Director.showMessageWindow();
System.out.println("\n" + builder);
}
}
public boolean isApplicable() {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow != null && inspectorWindow.hasSelectedNodes();
}
private static final String NAME = "As Text...";
public String getName() {
return NAME;
}
public String getDescription() {
return "List as text";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/History16.gif");
}
public boolean isCritical() {
return true;
}
}
| 2,705 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CollapseNodesCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/CollapseNodesCommand.java | /*
* CollapseNodesCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.inspector.InspectorWindow;
import megan.inspector.NodeBase;
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class CollapseNodesCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
TreePath[] paths = inspectorWindow.getDataTree().getSelectionPaths();
if (paths != null)
inspectorWindow.collapse(paths);
else {
for (NodeBase root : inspectorWindow.getClassification2RootNode().values()) {
inspectorWindow.collapse(root);
}
}
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "collapse;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
executeImmediately(getSyntax());
}
public String getName() {
return "Collapse";
}
private static final String ALTNAME = "Collapse Inspector";
public String getAltName() {
return ALTNAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Collapse the selected nodes, or all, if none selected";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_K, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow != null && inspectorWindow.getDataTree() != null && inspectorWindow.getDataTree().getModel().getRoot() != null
&& inspectorWindow.getDataTree().getModel().getChildCount(inspectorWindow.getDataTree().getModel().getRoot()) > 0;
}
}
| 3,803 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CopyCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/CopyCommand.java | /*
* CopyCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.clipboard.ClipboardBase;
import megan.inspector.InspectorWindow;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class CopyCommand extends ClipboardBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
final String selected = ((InspectorWindow) getViewer()).getSelection();
if (selected.length() > 0) {
StringSelection selection = new StringSelection(selected);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
}
}
public boolean isApplicable() {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow != null && inspectorWindow.hasSelectedNodes();
}
private static final String ALT_NAME = "Inspector Copy";
public String getAltName() {
return ALT_NAME;
}
public String getName() {
return "Copy";
}
public String getDescription() {
return "Copy";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Copy16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,508 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ShowTaxonCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/ShowTaxonCommand.java | /*
* ShowTaxonCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ProgramProperties;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.NumberUtils;
import jloda.util.parse.NexusStreamParser;
import megan.classification.Classification;
import megan.inspector.InspectorWindow;
import megan.main.MeganProperties;
import megan.viewer.TaxonomyData;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class ShowTaxonCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("show taxon=");
String name = np.getWordRespectCase();
np.matchIgnoreCase(";");
if (getViewer() instanceof InspectorWindow) {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
int taxId;
if (NumberUtils.isInteger(name))
taxId = Integer.parseInt(name);
else
taxId = TaxonomyData.getName2IdMap().get(name);
if (taxId == 0) {
NotificationsInSwing.showWarning(inspectorWindow.getFrame(), "Unknown taxon: " + name);
} else
inspectorWindow.addTopLevelNode(name, taxId, Classification.Taxonomy);
} else
NotificationsInSwing.showError(getViewer().getFrame(), "Command in invalid context");
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "show taxon=<name|id>;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
String name = ProgramProperties.get(MeganProperties.FINDTAXON, "");
name = JOptionPane.showInputDialog(inspectorWindow.getFrame(), "Enter taxon name or Id", name);
if (name != null && name.trim().length() > 0) {
name = name.trim();
ProgramProperties.put(MeganProperties.FINDTAXON, name);
executeImmediately("show taxon='" + name + "';"); // do not use execute() here because locked dir will prevent node from showing
}
}
private static final String NAME = "Show Taxon...";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Show the named taxon and all reads assigned to it";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_T, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow != null;
}
}
| 4,488 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SelectAllCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/SelectAllCommand.java | /*
* SelectAllCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.inspector.InspectorWindow;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* * selection command
* * Daniel Huson, 11.2010
*/
public class SelectAllCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "select items={all|none}";
}
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("select items=");
String what = np.getWordMatchesIgnoringCase("all none");
np.matchRespectCase(";");
final InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
switch (what) {
case "all" -> inspectorWindow.getDataTree().setSelectionInterval(0, inspectorWindow.getDataTree().getRowCount());
case "none" -> inspectorWindow.getDataTree().clearSelection();
}
}
public void actionPerformed(ActionEvent event) {
executeImmediately("select items=all;");
}
public boolean isApplicable() {
return getViewer() instanceof InspectorWindow;
}
public String getName() {
return "Select All";
}
public String getDescription() {
return "Select nodes";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("Empty16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,645 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ClearCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/ClearCommand.java | /*
* ClearCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.inspector.InspectorWindow;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* command
* Daniel Huson, 11.2010
*/
public class ClearCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase(getSyntax());
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
if (inspectorWindow.getDataTree().getSelectionCount() == 0)
inspectorWindow.clear();
else
inspectorWindow.deleteSelectedNodes();
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return "clear;";
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent ev) {
executeImmediately(getSyntax());
}
private static final String NAME = "Clear";
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Clear the selected nodes, or all, if none selected";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow != null && inspectorWindow.getDataTree() != null && inspectorWindow.getDataTree().getModel().getRoot() != null
&& inspectorWindow.getDataTree().getModel().getChildCount(inspectorWindow.getDataTree().getModel().getRoot()) > 0;
}
}
| 3,331 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ExportSelectionCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/ExportSelectionCommand.java | /*
* ExportSelectionCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.CommandBase;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.core.Director;
import megan.inspector.InspectorWindow;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class ExportSelectionCommand extends CommandBase implements ICommand {
public String getSyntax() {
return "export what=selection file=<filename>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("export what=selection");
np.matchIgnoreCase("file=");
String outputFile = np.getAbsoluteFileName();
np.matchIgnoreCase(";");
final String selection = ((InspectorWindow) getViewer()).getSelection();
if (selection.length() > 0) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(FileUtils.getOutputStreamPossiblyZIPorGZIP(outputFile)))) {
writer.write(selection);
}
}
NotificationsInSwing.showInformation(getViewer().getFrame(), "Wrote " + StringUtils.countOccurrences(selection, '\n') + " lines to file: " + outputFile);
}
public boolean isApplicable() {
return getViewer() instanceof InspectorWindow && ((InspectorWindow) getViewer()).hasSelectedNodes();
}
public boolean isCritical() {
return true;
}
public void actionPerformed(ActionEvent event) {
final Director dir = (Director) getDir();
if (getViewer() instanceof InspectorWindow) {
String name = FileUtils.replaceFileSuffix(dir.getDocument().getTitle(), "-inspector.txt");
File lastOpenFile = new File(name);
final File file = ChooseFileDialog.chooseFileToSave(getViewer().getFrame(), lastOpenFile, new TextFileFilter(), new TextFileFilter(), event, "Save selected text to file", ".txt");
if (file != null) {
execute("export what=selection file='" + file.getPath() + "';");
}
}
}
public String getName() {
return "Export Selected Text...";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Export16.gif");
}
public String getDescription() {
return "Export selection to a text file";
}
@Override
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 3,534 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CutCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/inspector/commands/CutCommand.java | /*
* CutCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.inspector.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.commands.clipboard.ClipboardBase;
import megan.inspector.InspectorWindow;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class CutCommand extends ClipboardBase implements ICommand {
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
final String selected = ((InspectorWindow) getViewer()).getSelection();
if (selected.length() > 0) {
StringSelection selection = new StringSelection(selected);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, null);
((InspectorWindow) getViewer()).deleteSelectedNodes();
}
}
public boolean isApplicable() {
InspectorWindow inspectorWindow = (InspectorWindow) getViewer();
return inspectorWindow != null && inspectorWindow.hasSelectedNodes();
}
private static final String ALT_NAME = "Inspector Cut";
public String getAltName() {
return ALT_NAME;
}
public String getName() {
return "Cut";
}
public String getDescription() {
return "Cut from inspector";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Cut16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
}
}
| 2,584 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FilesPanel.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/FilesPanel.java | /*
* FilesPanel.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast;
import jloda.swing.commands.CommandManager;
import jloda.swing.util.ProgramProperties;
import megan.importblast.commands.*;
import megan.parsers.blast.BlastFileFormat;
import megan.parsers.blast.BlastModeUtils;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
/**
* the files panel
* Daniel Huson, 12.2012
*/
public class FilesPanel extends JPanel {
/**
* make the files panel
*
*/
public FilesPanel(final ImportBlastDialog dialog) {
final CommandManager commandManager = dialog.getCommandManager();
setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
topPanel.add(Box.createHorizontalGlue());
topPanel.add(new JLabel("Specify input and output files"));
topPanel.add(Box.createHorizontalGlue());
add(topPanel, BorderLayout.NORTH);
JPanel innerPanel = new JPanel();
innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS));
innerPanel.setMaximumSize(new Dimension(400, 400));
{
dialog.getBlastFileNameField().setToolTipText("Add BLAST (or DAA or SAM or RDP or Silva) file(s) to import");
JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.setBorder(BorderFactory.createTitledBorder("1. Specify the BLAST (or DAA or MAF or SAM or RDP or Silva) file(s) to import"));
JPanel line1 = new JPanel();
line1.setLayout(new BoxLayout(line1, BoxLayout.X_AXIS));
// line1.add(Box.createHorizontalGlue());
line1.add(new JScrollPane(dialog.getBlastFileNameField()));
line1.setMaximumSize(new Dimension(1000, 80));
line1.setMinimumSize(new Dimension(100, 80));
line1.add(commandManager.getButton(ChooseBlastFileCommand.ALTNAME));
panel1.add(line1, BorderLayout.CENTER);
JPanel oneLine = new JPanel();
oneLine.setLayout(new BoxLayout(oneLine, BoxLayout.X_AXIS));
oneLine.add(Box.createHorizontalGlue());
JLabel formatLabel = new JLabel("Format:");
formatLabel.setForeground(Color.GRAY);
oneLine.add(formatLabel);
oneLine.add(dialog.getFormatCBox());
oneLine.add(Box.createHorizontalGlue());
JLabel modeLabel = new JLabel("Mode:");
modeLabel.setForeground(Color.GRAY);
oneLine.add(modeLabel);
oneLine.add(dialog.getAlignmentModeCBox());
oneLine.add(Box.createHorizontalGlue());
JPanel twoLines = new JPanel();
twoLines.setLayout(new BoxLayout(twoLines, BoxLayout.Y_AXIS));
twoLines.add(oneLine);
twoLines.add(Box.createVerticalStrut(12));
panel1.add(twoLines, BorderLayout.SOUTH);
innerPanel.add(panel1);
}
final JPanel readsFilePanel = new JPanel();
final JTextArea readFileNameField = dialog.getReadFileNameField();
final AbstractButton longReadsCBox;
{
readFileNameField.setToolTipText("Add reads files (FastA or FastQ format) to import, not neccessary for DAA files");
readsFilePanel.setLayout(new BorderLayout());
readsFilePanel.setBorder(BorderFactory.createTitledBorder("2. Specify the READs file(s) (FastA/Q format) to import (if available)"));
JPanel line2 = new JPanel();
line2.setLayout(new BoxLayout(line2, BoxLayout.X_AXIS));
// line2.add(Box.createHorizontalGlue());
line2.setMaximumSize(new Dimension(1000, 80));
line2.setMinimumSize(new Dimension(100, 80));
line2.add(new JScrollPane(readFileNameField));
readFileNameField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent event) {
dialog.setReadFileName(readFileNameField.getText());
commandManager.updateEnableState();
}
public void removeUpdate(DocumentEvent event) {
insertUpdate(event);
}
public void changedUpdate(DocumentEvent event) {
insertUpdate(event);
}
});
line2.add(commandManager.getButton(ChooseReadsFileCommand.ALTNAME));
readsFilePanel.add(line2, BorderLayout.CENTER);
JPanel oneLine = new JPanel();
oneLine.setLayout(new BoxLayout(oneLine, BoxLayout.X_AXIS));
oneLine.add(Box.createHorizontalGlue());
oneLine.add(commandManager.getButton(SetPairedReadsCommand.NAME));
oneLine.add(Box.createHorizontalGlue());
longReadsCBox = commandManager.getButton(SetLongReadsCommand.NAME);
oneLine.add(longReadsCBox);
oneLine.add(Box.createHorizontalGlue());
JPanel twoLines = new JPanel();
twoLines.setLayout(new BoxLayout(twoLines, BoxLayout.Y_AXIS));
twoLines.add(oneLine);
twoLines.add(Box.createVerticalStrut(12));
readsFilePanel.add(twoLines, BorderLayout.SOUTH);
innerPanel.add(readsFilePanel);
}
dialog.getBlastFileNameField().getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent event) {
String blastFileName = dialog.getBlastFileNameField().getText().trim();
dialog.setBlastFileName(blastFileName);
int endOfLine = blastFileName.indexOf("\n");
if (endOfLine != -1)
blastFileName = blastFileName.substring(0, endOfLine).trim();
try {
String format = BlastFileFormat.detectFormat(dialog, blastFileName, false).toString();
dialog.getFormatCBox().setSelectedFormat(format);
String mode = BlastModeUtils.detectMode(dialog, blastFileName, false).toString();
dialog.getAlignmentModeCBox().setSelectedMode(mode);
boolean isDAA = format.equalsIgnoreCase("daa");
readsFilePanel.setEnabled(!isDAA);
readFileNameField.setEnabled(!isDAA);
if (isDAA)
readFileNameField.setText("");
} catch (Exception e) {
dialog.getFormatCBox().setSelectedFormat("Unknown");
}
commandManager.updateEnableState();
}
public void removeUpdate(DocumentEvent event) {
insertUpdate(event);
}
public void changedUpdate(DocumentEvent event) {
insertUpdate(event);
}
});
{
final JPanel panel3 = new JPanel();
panel3.setLayout(new BorderLayout());
panel3.setBorder(BorderFactory.createTitledBorder("3. Specify a new MEGAN file"));
final JPanel line3 = new JPanel();
line3.setLayout(new BoxLayout(line3, BoxLayout.X_AXIS));
final JTextField meganFileNameField = dialog.getMeganFileNameField();
meganFileNameField.setToolTipText("Name MEGAN file to create");
meganFileNameField.setBorder(BorderFactory.createEmptyBorder());
line3.add(new JScrollPane(meganFileNameField));
meganFileNameField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent event) {
dialog.setMeganFileName(meganFileNameField.getText());
commandManager.updateEnableState();
}
public void removeUpdate(DocumentEvent event) {
insertUpdate(event);
}
public void changedUpdate(DocumentEvent event) {
insertUpdate(event);
}
});
line3.add(commandManager.getButton(ChooseMeganFileCommand.ALTNAME));
panel3.add(line3, BorderLayout.CENTER);
final JPanel below3 = new JPanel();
below3.setLayout(new BoxLayout(below3, BoxLayout.LINE_AXIS));
below3.add(dialog.getMaxNumberOfMatchesPerReadLabel());
dialog.getMaxNumberOfMatchesPerReadField().setMinimumSize(new Dimension(70, 30));
dialog.getMaxNumberOfMatchesPerReadField().setMaximumSize(new Dimension(400, 30));
dialog.getMaxNumberOfMatchesPerReadField().setText("" + ProgramProperties.get("MaxNumberMatchesPerRead", 100));
dialog.getMaxNumberOfMatchesPerReadField().setToolTipText("Specify the maximum number of matches to save per read." +
" A small value reduces the size of the MEGAN file, but may exclude some important matches.");
below3.add(dialog.getMaxNumberOfMatchesPerReadField());
longReadsCBox.addActionListener(e -> dialog.getMaxNumberOfMatchesPerReadField().setEnabled(!longReadsCBox.isSelected()));
below3.add(Box.createHorizontalGlue());
dialog.getUseCompressionCBox().setText("Use Compression");
dialog.getUseCompressionCBox().setToolTipText("Compress reads and matches in RMA file. Files are much smaller, but take slightly longer to generate.");
dialog.getUseCompressionCBox().setSelected(ProgramProperties.get("UseCompressInRMAFiles", true));
below3.add(dialog.getUseCompressionCBox());
below3.add(Box.createHorizontalStrut(50));
JPanel twoLines = new JPanel();
twoLines.setLayout(new BoxLayout(twoLines, BoxLayout.Y_AXIS));
twoLines.add(below3);
twoLines.add(Box.createVerticalStrut(12));
panel3.add(twoLines, BorderLayout.SOUTH);
innerPanel.add(panel3);
}
{
final JPanel panel4 = new JPanel();
panel4.setLayout(new BorderLayout());
panel4.setBorder(BorderFactory.createTitledBorder("4. Short description of sample"));
JPanel line4 = new JPanel();
line4.setLayout(new BoxLayout(line4, BoxLayout.X_AXIS));
dialog.getShortDescriptionField().setToolTipText("Provide short description of sample");
dialog.getShortDescriptionField().setMaximumSize(new Dimension(100000, 30));
dialog.getShortDescriptionField().getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent event) {
String description = dialog.getShortDescriptionField().getText().trim();
dialog.setShortDescription(description);
commandManager.updateEnableState();
commandManager.updateEnableState();
}
public void removeUpdate(DocumentEvent event) {
insertUpdate(event);
}
public void changedUpdate(DocumentEvent event) {
insertUpdate(event);
}
});
line4.add(dialog.getShortDescriptionField());
panel4.add(line4, BorderLayout.CENTER);
innerPanel.add(panel4);
}
innerPanel.add(Box.createVerticalGlue());
innerPanel.add(Box.createVerticalStrut(10));
add(innerPanel, BorderLayout.CENTER);
}
}
| 12,375 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
FormatCBox.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/FormatCBox.java | /*
* FormatCBox.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast;
import megan.parsers.blast.BlastFileFormat;
import javax.swing.*;
import java.awt.*;
import java.util.Objects;
/**
* combo box for choosing blast format
* Daniel Huson, 6.2013
*/
public class FormatCBox extends JComboBox<String> {
/**
* constructor
*/
public FormatCBox() {
setEditable(false);
for (BlastFileFormat value : BlastFileFormat.values()) {
addItem(value.toString());
}
setMaximumSize(new Dimension(150, 20));
setPreferredSize(new Dimension(150, 20));
setToolTipText("Select format of input files");
}
/**
* get the selected format
*
* @return selected format
*/
public String getSelectedFormat() {
return Objects.requireNonNull(getSelectedItem()).toString();
}
/**
* set the selected format
*
*/
public void setSelectedFormat(String name) {
for (int i = 0; i < getItemCount(); i++) {
final String item = getItemAt(i);
if (item.equalsIgnoreCase(name)) {
setSelectedIndex(i);
break;
}
}
}
}
| 1,972 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
LCAParametersPanel.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/LCAParametersPanel.java | /*
* LCAParametersPanel.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast;
import jloda.swing.commands.CommandManager;
import jloda.swing.util.ProgramProperties;
import megan.core.Document;
import megan.importblast.commands.SetUseIdentityFilterCommand;
import javax.swing.*;
import java.awt.*;
/**
* panel for setting LCA parameters
* Daniel Huson, 12.2012
*/
public class LCAParametersPanel extends JPanel {
/**
* construct the parameters panel
*/
public LCAParametersPanel(final ImportBlastDialog dialog) {
final CommandManager commandManager = dialog.getCommandManager();
setLayout(new BorderLayout());
JPanel outerPanel = new JPanel();
outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(18, 2));
centerPanel.add(new JLabel("Min Score:"));
centerPanel.add(dialog.getMinScoreField());
dialog.getMinScoreField().setToolTipText("Minimal bitscore that a match must attain");
centerPanel.add(new JLabel("Max Expected:"));
centerPanel.add(dialog.getMaxExpectedField());
dialog.getMaxExpectedField().setToolTipText("Ignore all matches whose expected values lie above this threshold");
centerPanel.add(new JLabel("Min Percent Identity:"));
centerPanel.add(dialog.getMinPercentIdentityField());
dialog.getMaxExpectedField().setToolTipText("Ignore all matches whose min percent identity lie above this threshold");
centerPanel.add(new JLabel(" "));
centerPanel.add(new JLabel(" "));
centerPanel.add(new JLabel("Top Percent:"));
centerPanel.add(dialog.getTopPercentField());
dialog.getTopPercentField().setToolTipText("Match must lie within this percentage of the best score attained for a read");
centerPanel.add(new JLabel(" "));
centerPanel.add(new JLabel(" "));
centerPanel.add(new JLabel("Min Support Percent:"));
centerPanel.add(dialog.getMinSupportPercentField());
dialog.getMinSupportPercentField().setToolTipText("Minimum number of reads that a taxon must obtain as a percentage of total reads assigned");
centerPanel.add(new JLabel("Min Support:"));
centerPanel.add(dialog.getMinSupportField());
dialog.getMinSupportField().setToolTipText("Minimum number of reads that a taxon must obtain");
centerPanel.add(new JLabel("Min Read Length:"));
centerPanel.add(dialog.getMinReadLengthField());
dialog.getMinReadLengthField().setToolTipText("Minimum read length");
{
centerPanel.add(new JLabel("LCA Algorithm:"));
final JComboBox<String> lcaAlgorithmComboBox = dialog.getLcaAlgorithmComboBox();
lcaAlgorithmComboBox.setEditable(false);
for (Document.LCAAlgorithm algorithm : Document.LCAAlgorithm.values()) {
lcaAlgorithmComboBox.addItem(algorithm.toString());
}
lcaAlgorithmComboBox.addActionListener(e -> {
if (lcaAlgorithmComboBox.getSelectedItem() != null) {
switch (Document.LCAAlgorithm.valueOfIgnoreCase(lcaAlgorithmComboBox.getSelectedItem().toString())) {
case naive -> {
dialog.getLcaCoveragePercentField().setText("" + Document.DEFAULT_LCA_COVERAGE_PERCENT_SHORT_READS);
lcaAlgorithmComboBox.setToolTipText("Naive LCA for taxonomic binning: fast algorithm applicable to short reads");
}
case weighted -> {
dialog.getLcaCoveragePercentField().setText("" + Document.DEFAULT_LCA_COVERAGE_PERCENT_WEIGHTED_LCA);
lcaAlgorithmComboBox.setToolTipText("Weighted LCA for taxonomic binning: slower algorithm applicable to short reads, slightly more specific than naive LCA");
}
case longReads -> {
dialog.getLcaCoveragePercentField().setText("" + Document.DEFAULT_LCA_COVERAGE_PERCENT_LONG_READS);
lcaAlgorithmComboBox.setToolTipText("Long Reads LCA for taxonomic and functional binning of long reads and contigs");
}
default -> lcaAlgorithmComboBox.setToolTipText("Select LCA algorithm");
}
}
if (lcaAlgorithmComboBox.getSelectedItem() != null) {
final Document.LCAAlgorithm algorithm = Document.LCAAlgorithm.valueOfIgnoreCase((String) lcaAlgorithmComboBox.getSelectedItem());
dialog.setLcaAlgorithm(algorithm != null ? algorithm : Document.DEFAULT_LCA_ALGORITHM_SHORT_READS);
} else
dialog.setLcaAlgorithm(Document.DEFAULT_LCA_ALGORITHM_SHORT_READS);
ProgramProperties.put("SelectedLCAAlgorithm" + (dialog.isLongReads() ? "LongReads" : "ShortReads"), dialog.getLcaAlgorithm().toString());
});
lcaAlgorithmComboBox.setSelectedItem(0);
lcaAlgorithmComboBox.setToolTipText("Set LCA algorithm for taxonomic binning");
centerPanel.add(lcaAlgorithmComboBox);
centerPanel.add(new JLabel("Percent to cover:"));
dialog.getLcaCoveragePercentField().setToolTipText("Percent of weight to cover by weighted LCA");
centerPanel.add(dialog.getLcaCoveragePercentField());
dialog.getLcaCoveragePercentField().setToolTipText("Percent of weight to cover by weighted LCA or long read LCA");
}
{
centerPanel.add(new JLabel("Read Assignment mode:"));
final JComboBox<String> readAssignmentModeComboBox = dialog.getReadAssignmentModeComboBox();
readAssignmentModeComboBox.setEditable(false);
for (Document.ReadAssignmentMode readAssignmentMode : Document.ReadAssignmentMode.values()) {
readAssignmentModeComboBox.addItem(readAssignmentMode.toString());
}
centerPanel.add(readAssignmentModeComboBox);
readAssignmentModeComboBox.setToolTipText("Read assignment mode: determines what is shown as number of assigned reads in taxonomy analysis");
readAssignmentModeComboBox.addActionListener(e -> {
if (readAssignmentModeComboBox.getSelectedItem() != null) {
ProgramProperties.put("ReadAssignmentModeComboBox", readAssignmentModeComboBox.toString());
}
switch (Document.ReadAssignmentMode.valueOfIgnoreCase(readAssignmentModeComboBox.getSelectedItem().toString())) {
case readCount -> readAssignmentModeComboBox.setToolTipText("Display read counts as 'assigned reads' in taxonomy viewer");
case readLength -> readAssignmentModeComboBox.setToolTipText("Display sum of read lengths as 'assigned reads' in taxonomy viewer");
case alignedBases -> readAssignmentModeComboBox.setToolTipText("Display number of aligned bases as 'assigned reads' in taxonomy viewer");
case readMagnitude -> readAssignmentModeComboBox.setToolTipText("Display sum of read magnitudes as 'assigned reads' in taxonomy viewer");
default -> readAssignmentModeComboBox.setToolTipText("Select what to display as 'assigned reads' in taxonomy viewer");
}
});
centerPanel.add(new JLabel(" "));
centerPanel.add(new JLabel(" "));
}
{
centerPanel.add(commandManager.getButton(SetUseIdentityFilterCommand.NAME));
centerPanel.add(new JLabel(" "));
}
{
centerPanel.add(new JLabel("Min Percent Read To Cover:"));
centerPanel.add(dialog.getMinPercentReadToCoverField());
dialog.getMinSupportPercentField().setToolTipText("Minimum percent of read that has to be covered by alignments for read to be binned");
}
{
centerPanel.add(new JLabel("Min Percent Reference To Cover:"));
centerPanel.add(dialog.getMinPercentReferenceToCoverField());
dialog.getMinSupportPercentField().setToolTipText("Minimum percent of reference that has to be covered by alignments for reference to be considered");
}
JPanel three = new JPanel();
three.setLayout(new BoxLayout(three, BoxLayout.X_AXIS));
outerPanel.setBorder(BorderFactory.createTitledBorder("LCA and analysis parameters"));
three.add(Box.createHorizontalGlue());
three.add(centerPanel);
three.add(Box.createHorizontalGlue());
outerPanel.add(three);
add(outerPanel, BorderLayout.CENTER);
}
}
| 9,588 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ImportBlastDialog.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/ImportBlastDialog.java | /*
* ImportBlastDialog.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast;
import jloda.seq.BlastMode;
import jloda.swing.commands.CommandManager;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.director.IDirectableViewer;
import jloda.swing.util.StatusBar;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.*;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.classification.commandtemplates.SetAnalyse4ViewerCommand;
import megan.classification.data.ClassificationCommandHelper;
import megan.core.Director;
import megan.core.Document;
import megan.importblast.commands.*;
import megan.main.MeganProperties;
import megan.parsers.blast.BlastFileFormat;
import megan.parsers.blast.BlastModeUtils;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
/**
* load data from a blast file
* Daniel Huson, 8.2008
*/
public class ImportBlastDialog extends JDialog implements IDirectableViewer {
private final Director dir;
private boolean isLocked = false;
private boolean isUpToDate = true;
private final JTextField minScoreField = new JTextField(8);
private final JTextField maxExpectedField = new JTextField(8);
private final JTextField minPercentIdentityField = new JTextField(8);
private final JTextField topPercentField = new JTextField(8);
private final JTextField minSupportField = new JTextField(8);
private final JTextField minSupportPercentField = new JTextField(8);
private final JComboBox<String> lcaAlgorithmComboBox = new JComboBox<>();
private final JComboBox<String> readAssignmentModeComboBox = new JComboBox<>();
private final JTextField lcaCoveragePercentField = new JTextField(8);
private final JTextField minReadLengthField = new JTextField(8);
private final JTextField minPercentReadCoveredField = new JTextField(8);
private final JTextField minPercentReferenceCoveredField = new JTextField(8);
private boolean usePairedReads = false;
private String pairedReadSuffix1 = ProgramProperties.get(MeganProperties.PAIRED_READ_SUFFIX1, "");
private String pairedReadSuffix2 = ProgramProperties.get(MeganProperties.PAIRED_READ_SUFFIX2, "");
private boolean longReads = false;
private final boolean useReadMagnitudes = false;
private boolean parseTaxonNames = ProgramProperties.get(MeganProperties.PARSE_TAXON_NAMES, true);
private boolean usePercentIdentityFilter = false;
private String contaminantsFileName = ProgramProperties.get(MeganProperties.CONTAMINANT_FILE, "");
private boolean useContaminantsFilter = false;
private final JTextArea blastFileNameField = new JTextArea();
private final FormatCBox formatCBox = new FormatCBox();
private final ModeCBox alignmentModeCBox = new ModeCBox();
private final JTextField shortDescriptionField = new JTextField(8);
private final JTextArea readFileNameField = new JTextArea();
private final JTextField meganFileNameField = new JTextField();
private final JTextField maxNumberOfMatchesPerReadField = new JTextField(8);
private final JLabel maxNumberOfMatchesPerReadLabel = new JLabel("Max number of matches per read:");
private final JCheckBox useCompressionCBox = new JCheckBox();
private final JTabbedPane tabbedPane = new JTabbedPane();
private String result = null;
private final ArrayList<String> cNames = new ArrayList<>();
private final CommandManager commandManager;
/**
* constructor
*
*/
public ImportBlastDialog(Component parent, Director dir, final String title) {
this(parent, dir, ClassificationManager.getAllSupportedClassifications(), title);
}
/**
* constructor
*
*/
public ImportBlastDialog(Component parent, Director dir, Collection<String> cNames0, final String title) {
this.dir = dir;
final boolean showTaxonomyPane;
this.cNames.addAll(cNames0);
if (this.cNames.contains(Classification.Taxonomy)) {
showTaxonomyPane = true;
this.cNames.remove(Classification.Taxonomy);
} else
showTaxonomyPane = false;
dir.addViewer(this);
setIconImages(jloda.swing.util.ProgramProperties.getProgramIconImages());
commandManager = new CommandManager(dir, this, new String[]{"megan.commands", "megan.importblast.commands"}, !ProgramProperties.isUseGUI());
commandManager.addCommands(this, ClassificationCommandHelper.getImportBlastCommands(cNames0), true);
setMinScore(Document.DEFAULT_MINSCORE);
setTopPercent(Document.DEFAULT_TOPPERCENT);
setMaxExpected(Document.DEFAULT_MAXEXPECTED);
setMinPercentIdentity(Document.DEFAULT_MIN_PERCENT_IDENTITY);
setMinSupportPercent(0);
setMinSupport(Document.DEFAULT_MINSUPPORT);
setMinPercentReadToCover(Document.DEFAULT_MIN_PERCENT_READ_TO_COVER);
setMinPercentReferenceToCover(Document.DEFAULT_MIN_PERCENT_REFERENCE_TO_COVER);
setMinReadLength(Document.DEFAULT_MIN_READ_LENGTH);
final Document doc = dir.getDocument();
final String parameters = ProgramProperties.get(MeganProperties.DEFAULT_PROPERTIES, "");
doc.parseParameterString(parameters);
setMinScore(doc.getMinScore());
setTopPercent(doc.getTopPercent());
setMaxExpected(doc.getMaxExpected());
setMinPercentIdentity(doc.getMinPercentIdentity());
setMinSupportPercent(doc.getMinSupportPercent());
setMinSupport(doc.getMinSupport());
setMinPercentReadToCover(doc.getMinPercentReadToCover());
setMinPercentReferenceToCover(doc.getMinPercentReferenceToCover());
setMinReadLength(doc.getMinReadLength());
setUsePercentIdentityFilter(doc.isUseIdentityFilter());
setLCACoveragePercent(doc.getLcaCoveragePercent());
setLcaAlgorithm(doc.getLcaAlgorithm());
// set opposite then call command to toggle; this is to setup LCA for long reads
if (doc.isLongReads()) {
setLongReads(!doc.isLongReads());
commandManager.getCommand(SetLongReadsCommand.NAME).actionPerformed(null);
} else
setLongReads(false);
ArrayList<String> toDelete = new ArrayList<>();
for (String cName : doc.getActiveViewers()) { // turn of classifications for which mappers have not been loaded
if (!cName.equals(Classification.Taxonomy) && !ClassificationManager.get(cName, true).getIdMapper().hasActiveAndLoaded())
toDelete.add(cName);
}
toDelete.forEach(doc.getActiveViewers()::remove);
setLocationRelativeTo(parent);
setTitle(title);
setModal(true);
setSize(900, 700);
getContentPane().setLayout(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(tabbedPane, BorderLayout.CENTER);
addFilesTab(tabbedPane);
if (showTaxonomyPane)
addViewTab(Classification.Taxonomy, new ViewerPanel(commandManager, Classification.Taxonomy));
for (String fName : cNames) {
addViewTab(fName, new ViewerPanel(commandManager, fName));
}
addLCATab(tabbedPane);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.add(Box.createHorizontalStrut(20));
final JLabel tabNumber = new JLabel("Tab 1 of " + tabbedPane.getTabCount());
tabNumber.setForeground(Color.DARK_GRAY);
buttonPanel.add(tabNumber);
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(commandManager.getButton(PreviousTabCommand.ALTNAME));
buttonPanel.add(commandManager.getButton(NextTabCommand.ALTNAME));
JButton cancelButton = (JButton) commandManager.getButton(CancelCommand.ALTNAME);
buttonPanel.add(cancelButton);
JButton applyButton = (JButton) commandManager.getButton(ApplyCommand.ALTNAME);
buttonPanel.add(applyButton);
getRootPane().setDefaultButton(applyButton);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
getContentPane().add(mainPanel, BorderLayout.CENTER);
getContentPane().add(new StatusBar(false), BorderLayout.SOUTH);
tabbedPane.addChangeListener(event -> tabNumber.setText("Tab " + (tabbedPane.getSelectedIndex() + 1) + " of " + tabbedPane.getTabCount()));
getCommandManager().updateEnableState();
}
protected void addFilesTab(JTabbedPane tabbedPane) {
tabbedPane.addTab("Files", new FilesPanel(this));
}
protected void addLCATab(JTabbedPane tabbedPane) {
tabbedPane.addTab("LCA Params", new LCAParametersPanel(this));
}
protected void addViewTab(String title, JPanel jpanel) {
tabbedPane.addTab(title, jpanel);
}
/**
* show the dialog and return the entered command string, or null
*
* @return command string or null
*/
public String showAndGetCommand() {
setVisible(true);
return result;
}
protected double getMinScore() {
double value = Document.DEFAULT_MINSCORE;
try {
value = Double.parseDouble(minScoreField.getText());
} catch (NumberFormatException e) {
Basic.caught(e);
}
return value;
}
private void setMinScore(double value) {
minScoreField.setText("" + (float) value);
}
protected double getTopPercent() {
double value = Document.DEFAULT_TOPPERCENT;
try {
value = Double.parseDouble(topPercentField.getText());
} catch (NumberFormatException e) {
Basic.caught(e);
}
return value;
}
private void setTopPercent(double value) {
topPercentField.setText("" + (float) value);
}
protected double getMaxExpected() {
double value = Document.DEFAULT_MAXEXPECTED;
try {
value = Double.parseDouble(maxExpectedField.getText());
} catch (NumberFormatException e) {
Basic.caught(e);
}
return value;
}
private void setMaxExpected(double value) {
maxExpectedField.setText("" + (float) value);
}
protected double getMinPercentIdentity() {
double value = Document.DEFAULT_MIN_PERCENT_IDENTITY;
try {
value = Double.parseDouble(minPercentIdentityField.getText());
} catch (NumberFormatException e) {
Basic.caught(e);
}
return value;
}
private void setMinPercentIdentity(double value) {
minPercentIdentityField.setText("" + (float) value);
}
protected int getMinSupport() {
int value = Document.DEFAULT_MINSUPPORT;
try {
value = Integer.parseInt(minSupportField.getText());
} catch (NumberFormatException e) {
Basic.caught(e);
}
return Math.max(1, value);
}
private void setMinSupport(int value) {
minSupportField.setText("" + Math.max(0, value));
}
protected float getMinSupportPercent() {
float value = 0;
try {
value = NumberUtils.parseFloat(minSupportPercentField.getText());
} catch (NumberFormatException e) {
Basic.caught(e);
}
return Math.max(0f, value);
}
private void setMinSupportPercent(float value) {
minSupportPercentField.setText("" + Math.max(0f, value) + (value <= 0 ? " (off)" : ""));
}
public int getMinReadLength() {
int value = Document.DEFAULT_MIN_READ_LENGTH;
try {
value = NumberUtils.parseInt(minReadLengthField.getText());
} catch (NumberFormatException e) {
Basic.caught(e);
}
return value;
}
public void setMinReadLength(int value) {
minReadLengthField.setText(String.valueOf(value));
}
private String shortDescription = "";
protected String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
private String blastFileName = "";
public void setBlastFileName(String name) {
blastFileName = name;
}
public String getBlastFileName() {
return blastFileName;
}
private String readFileName = "";
public void setReadFileName(final String name) {
readFileName = name;
}
public void addReadFileName(String name) {
if (readFileName == null || readFileName.length() == 0)
readFileName = name;
else
readFileName += "\n" + name;
}
public String getReadFileName() {
return readFileName;
}
private String meganFileName = "";
public void setMeganFileName(String name) {
meganFileName = name;
}
private String getMeganFileName() {
return meganFileName;
}
public boolean isUsePairedReads() {
return usePairedReads;
}
public void setUsePairedReads(boolean usePairedReads) {
this.usePairedReads = usePairedReads;
}
public boolean isParseTaxonNames() {
return parseTaxonNames;
}
public void setParseTaxonNames(boolean parseTaxonNames) {
this.parseTaxonNames = parseTaxonNames;
ProgramProperties.put(MeganProperties.PARSE_TAXON_NAMES, parseTaxonNames);
}
public String getContaminantsFileName() {
return contaminantsFileName;
}
public void setContaminantsFileName(String contaminantsFileName) {
this.contaminantsFileName = contaminantsFileName;
}
public boolean isUseContaminantsFilter() {
return contaminantsFileName != null && useContaminantsFilter;
}
public void setUseContaminantsFilter(boolean useContaminantsFilter) {
this.useContaminantsFilter = useContaminantsFilter;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public JTabbedPane getTabbedPane() {
return tabbedPane;
}
public boolean isUsePercentIdentityFilter() {
return usePercentIdentityFilter;
}
public void setUsePercentIdentityFilter(boolean usePercentIdentityFilter) {
this.usePercentIdentityFilter = usePercentIdentityFilter;
}
public Document.LCAAlgorithm getLcaAlgorithm() {
return Document.LCAAlgorithm.valueOfIgnoreCase((String) lcaAlgorithmComboBox.getSelectedItem());
}
public void setReadAssignmentMode(Document.ReadAssignmentMode readAssignmentMode) {
readAssignmentModeComboBox.setSelectedItem(readAssignmentMode.toString());
}
protected Document.ReadAssignmentMode getReadAssignmentMode() {
return Document.ReadAssignmentMode.valueOfIgnoreCase((String) readAssignmentModeComboBox.getSelectedItem());
}
public void setLcaAlgorithm(Document.LCAAlgorithm lcaAlgorithm) {
lcaAlgorithmComboBox.setSelectedItem(lcaAlgorithm.toString());
}
protected double getLCACoveragePercent() {
double value = Document.DEFAULT_LCA_COVERAGE_PERCENT_SHORT_READS;
try {
value = NumberUtils.parseDouble(lcaCoveragePercentField.getText());
} catch (NumberFormatException e) {
Basic.caught(e);
}
return value;
}
private void setLCACoveragePercent(double value) {
lcaCoveragePercentField.setText("" + (float) Math.max(0, Math.min(100, value)));
}
public JTextField getLcaCoveragePercentField() {
return lcaCoveragePercentField;
}
public JTextField getMinPercentReadToCoverField() {
return minPercentReadCoveredField;
}
protected double getMinPercentReadToCover() {
double value = Document.DEFAULT_MIN_PERCENT_READ_TO_COVER;
try {
value = NumberUtils.parseDouble(minPercentReadCoveredField.getText());
} catch (NumberFormatException e) {
Basic.caught(e);
}
return value;
}
private void setMinPercentReadToCover(double value) {
minPercentReadCoveredField.setText("" + (float) Math.max(0, Math.min(100, value)));
}
public JTextField getMinPercentReferenceToCoverField() {
return minPercentReferenceCoveredField;
}
protected double getMinPercentReferenceToCover() {
double value = Document.DEFAULT_MIN_PERCENT_REFERENCE_TO_COVER;
try {
value = NumberUtils.parseDouble(minPercentReferenceCoveredField.getText());
} catch (NumberFormatException e) {
Basic.caught(e);
}
return value;
}
private void setMinPercentReferenceToCover(double value) {
minPercentReferenceCoveredField.setText("" + (float) Math.max(0, Math.min(100, value)));
}
public JTextField getMaxNumberOfMatchesPerReadField() {
return maxNumberOfMatchesPerReadField;
}
public JLabel getMaxNumberOfMatchesPerReadLabel() {
return maxNumberOfMatchesPerReadLabel;
}
public CommandManager getCommandManager() {
return commandManager;
}
public ModeCBox getAlignmentModeCBox() {
return alignmentModeCBox;
}
public JTextArea getBlastFileNameField() {
return blastFileNameField;
}
public JTextField getShortDescriptionField() {
return shortDescriptionField;
}
public JTextArea getReadFileNameField() {
return readFileNameField;
}
public JTextField getMeganFileNameField() {
return meganFileNameField;
}
public FormatCBox getFormatCBox() {
return formatCBox;
}
public JTextField getMinScoreField() {
return minScoreField;
}
public JTextField getTopPercentField() {
return topPercentField;
}
public JTextField getMaxExpectedField() {
return maxExpectedField;
}
public JTextField getMinPercentIdentityField() {
return minPercentIdentityField;
}
public JTextField getMinSupportField() {
return minSupportField;
}
public JTextField getMinSupportPercentField() {
return minSupportPercentField;
}
public JTextField getMinReadLengthField() {
return minReadLengthField;
}
public JCheckBox getUseCompressionCBox() {
return useCompressionCBox;
}
public JComboBox<String> getLcaAlgorithmComboBox() {
return lcaAlgorithmComboBox;
}
public JComboBox<String> getReadAssignmentModeComboBox() {
return readAssignmentModeComboBox;
}
/**
* is viewer uptodate?
*
* @return uptodate
*/
public boolean isUptoDate() {
return isUpToDate;
}
/**
* return the frame associated with the viewer
*
* @return frame
*/
public JFrame getFrame() {
return new JFrame("Import Blast Dialog");
}
/**
* ask view to rescan itself. This is method is wrapped into a runnable object
* and put in the swing event queue to avoid concurrent modifications.
*
* @param what what should be updated? Possible values: Director.ALL or Director.TITLE
*/
public void updateView(String what) {
isUpToDate = false;
commandManager.updateEnableState();
isUpToDate = true;
}
/**
* ask view to prevent user input
*/
public void lockUserInput() {
isLocked = true;
getTabbedPane().setEnabled(false);
if (commandManager != null)
commandManager.setEnableCritical(false);
setCursor(new Cursor(Cursor.WAIT_CURSOR));
}
/**
* ask view to allow user input
*/
public void unlockUserInput() {
isLocked = false;
if (commandManager != null)
commandManager.setEnableCritical(true);
getTabbedPane().setEnabled(true);
setCursor(Cursor.getDefaultCursor());
}
/**
* is viewer currently locked?
*
* @return true, if locked
*/
public boolean isLocked() {
return isLocked;
}
/**
* ask view to destroy itself
*/
public void destroyView() {
dir.removeViewer(this);
setVisible(false);
}
/**
* set uptodate state
*
*/
public void setUptoDate(boolean flag) {
isUpToDate = flag;
}
/**
* gets the list of selected cNames
*
* @return all selected fnames
*/
protected Collection<String> getSelectedFNames() {
final ArrayList<String> result = new ArrayList<>();
for (String cName : cNames) {
final ICheckBoxCommand command = (ICheckBoxCommand) commandManager.getCommand(SetAnalyse4ViewerCommand.getName(cName));
if (command.isSelected())
result.add(cName);
}
return result;
}
/**
* get the name of the class
*
* @return class name
*/
@Override
public String getClassName() {
return "ImportBlastDialog";
}
public void setPairedReadSuffix1(String pairedReadSuffix1) {
this.pairedReadSuffix1 = pairedReadSuffix1;
ProgramProperties.put(MeganProperties.PAIRED_READ_SUFFIX1, pairedReadSuffix1);
}
protected String getPairedReadSuffix1() {
return pairedReadSuffix1;
}
public void setPairedReadSuffix2(String pairedReadSuffix2) {
this.pairedReadSuffix2 = pairedReadSuffix2;
ProgramProperties.put(MeganProperties.PAIRED_READ_SUFFIX2, pairedReadSuffix2);
}
public String getPairedReadSuffix2() {
return pairedReadSuffix2;
}
public boolean isLongReads() {
return longReads;
}
public void setLongReads(boolean longReads) {
this.longReads = longReads;
}
/**
* apply import from blast
*/
public void apply() throws CanceledException, IOException {
ClassificationManager.get(Classification.Taxonomy, true).getIdMapper().setUseTextParsing(isParseTaxonNames());
final String blastFileName = getBlastFileName();
ProgramProperties.put(MeganProperties.BLASTFILE, new File(StringUtils.getLinesFromString(blastFileName).get(0)));
final String readFileName = getReadFileName();
String meganFileName = getMeganFileName();
if (!meganFileName.startsWith("MS:::") && !(meganFileName.toLowerCase().endsWith(".rma")
|| meganFileName.toLowerCase().endsWith(".rma1") || meganFileName.toLowerCase().endsWith(".rma2")
|| meganFileName.toLowerCase().endsWith(".rma3") || meganFileName.toLowerCase().endsWith(".rma6")))
meganFileName += ".rma";
ProgramProperties.put(MeganProperties.MEGANFILE, new File(meganFileName));
String blastFormat = getFormatCBox().getSelectedFormat();
String blastMode = getAlignmentModeCBox().getSelectedMode();
StringBuilder buf = new StringBuilder();
buf.append("import blastFile=");
if (blastFileName.length() > 0) {
{
java.util.List<String> fileNames = StringUtils.getLinesFromString(blastFileName);
boolean first = true;
for (String name : fileNames) {
File file = new File(name);
if (!(file.exists() && file.canRead())) {
NotificationsInSwing.showError(this, "Failed to open BLAST file for reading: " + name);
return;
}
if (first)
first = false;
else
buf.append(", ");
buf.append("'").append(name).append("'");
}
}
final String fileName = StringUtils.getFirstLine(blastFileName);
if (blastFormat.equals(BlastFileFormat.Unknown.toString())) {
String formatName = BlastFileFormat.detectFormat(this, fileName, true).toString();
if (formatName != null)
blastFormat = BlastFileFormat.valueOf(formatName).toString();
else
throw new IOException("Failed to detect BLAST format for file: " + fileName);
}
if (blastMode.equals(BlastMode.Unknown.toString())) {
BlastMode mode = BlastModeUtils.detectMode(this, fileName, true);
if (mode == null) // user canceled
throw new CanceledException();
else if (mode == BlastMode.Unknown)
throw new IOException("Failed to detect BLAST mode for file: " + fileName);
else
blastMode = mode.toString();
}
if (readFileName.length() > 0) {
buf.append(" fastaFile=");
java.util.List<String> fileNames = StringUtils.getLinesFromString(readFileName);
boolean first = true;
for (String name : fileNames) {
File file = new File(name);
if (!(file.exists() && file.canRead())) {
NotificationsInSwing.showError(this, "Failed to open READs file for reading: " + name);
return;
}
if (first)
first = false;
else
buf.append(", ");
buf.append("'").append(name).append("'");
}
}
}
buf.append(" meganFile='").append(meganFileName).append("'");
buf.append(" useCompression=").append(getUseCompressionCBox().isSelected());
ProgramProperties.put("UseCompressInRMAFiles", getUseCompressionCBox().isSelected());
buf.append(" format=").append(blastFormat);
buf.append(" mode=").append(blastMode);
int maxNumberOfMatchesPerRead;
if (!isLongReads()) {
try {
maxNumberOfMatchesPerRead = Integer.parseInt(getMaxNumberOfMatchesPerReadField().getText());
ProgramProperties.put("MaxNumberMatchesPerRead", maxNumberOfMatchesPerRead);
} catch (NumberFormatException ex) {
maxNumberOfMatchesPerRead = ProgramProperties.get("MaxNumberMatchesPerRead", 50);
}
buf.append(" maxMatches=").append(maxNumberOfMatchesPerRead);
}
buf.append(" minScore=").append(getMinScore());
buf.append(" maxExpected=").append(getMaxExpected());
buf.append(" minPercentIdentity=").append(getMinPercentIdentity());
buf.append(" topPercent=").append(getTopPercent());
if (getMinSupportPercent() > 0)
buf.append(" minSupportPercent=").append(getMinSupportPercent());
else
buf.append(" minSupport=").append(getMinSupport());
buf.append(" lcaAlgorithm=").append(getLcaAlgorithm().toString());
if (getLcaAlgorithm() == Document.LCAAlgorithm.weighted || getLcaAlgorithm() == Document.LCAAlgorithm.longReads)
buf.append(" lcaCoveragePercent=").append(getLCACoveragePercent());
buf.append(" minPercentReadToCover=").append(getMinPercentReadToCover());
buf.append(" minPercentReferenceToCover=").append(getMinPercentReferenceToCover());
buf.append(" minReadLength=").append(getMinReadLength());
buf.append(" useIdentityFilter=").append(isUsePercentIdentityFilter());
buf.append(" readAssignmentMode=").append(getReadAssignmentMode());
buf.append(" fNames=").append(StringUtils.toString(getSelectedFNames(), " "));
if (isLongReads())
buf.append(" longReads=").append(isLongReads());
if (isUsePairedReads())
buf.append(" paired=").append(isUsePairedReads());
if (isUsePairedReads()) {
String pattern1 = getPairedReadSuffix1();
//String pattern2 = ProgramProperties.get(MeganProperties.PAIRED_READ_SUFFIX2, "");
buf.append(" pairSuffixLength=").append(pattern1.length());
}
if (isUseContaminantsFilter() && StringUtils.notBlank(getContaminantsFileName()))
buf.append(" contaminantsFile='").append(getContaminantsFileName()).append("'");
if (StringUtils.notBlank(getShortDescription()))
buf.append(" description='").append(getShortDescription()).append("'");
buf.append(";");
// delete existing files before we start the computation:
File file = new File(meganFileName);
if (file.exists()) {
System.err.println("Removing file " + file.getPath() + ": " + file.delete());
File rmazFile = new File(FileUtils.getFileSuffix(file.getPath()) + ".rmaz");
if (rmazFile.exists())
System.err.println("Removing file " + rmazFile.getPath() + ": " + rmazFile.delete());
rmazFile = new File(file.getPath() + "z");
if (rmazFile.exists())
System.err.println("Removing file " + rmazFile.getPath() + ": " + rmazFile.delete());
}
setResult(buf.toString());
}
public boolean isAppliable() {
return getBlastFileName().trim().length() > 0 && getMeganFileName().trim().length() > 0;
}
}
| 30,132 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ModeCBox.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/ModeCBox.java | /*
* ModeCBox.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast;
import jloda.seq.BlastMode;
import javax.swing.*;
import java.awt.*;
import java.util.Objects;
/**
* combo box for choosing blast format
* Daniel Huson, 6.2013
*/
public class ModeCBox extends JComboBox<String> {
/**
* constructor
*/
public ModeCBox() {
setEditable(false);
for (BlastMode value : BlastMode.values()) {
addItem(value.toString());
}
setMaximumSize(new Dimension(150, 20));
setPreferredSize(new Dimension(150, 20));
setToolTipText("Select alignment mode");
}
/**
* get the selected format
*
* @return selected format
*/
public String getSelectedMode() {
return Objects.requireNonNull(getSelectedItem()).toString();
}
/**
* set the selected format
*
*/
public void setSelectedMode(String name) {
for (int i = 0; i < getItemCount(); i++) {
final String item = getItemAt(i);
if (item.equalsIgnoreCase(name)) {
setSelectedIndex(i);
break;
}
}
}
}
| 1,927 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ReadPairingDialog.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/ReadPairingDialog.java | /*
* ReadPairingDialog.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import megan.main.MeganProperties;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* dialog requesting setup of regular expressions for matching reads
* Daniel Huson, 10.2009
*/
public class ReadPairingDialog {
private final ImportBlastDialog importBlastDialog;
private final JDialog dialog = new JDialog();
private final JCheckBox noSufficesCBox = new JCheckBox();
private final JTextField field1 = new JTextField(10);
private final JTextField field2 = new JTextField(10);
private boolean canceled = false;
private String pairedReadSuffix1;
private String pairedReadSuffix2;
/**
* constructor
*
*/
public ReadPairingDialog(ImportBlastDialog parent, String readsFile) {
this.importBlastDialog = parent;
dialog.setModal(true);
String[] suffixes = guessPairedSuffixes(readsFile);
this.pairedReadSuffix1 = suffixes[0];
this.pairedReadSuffix2 = suffixes[1];
field1.setText(pairedReadSuffix1);
field1.setToolTipText("Suffix of first read name");
field2.setText(pairedReadSuffix2);
field2.setToolTipText("Suffix of second read name");
dialog.setTitle("Paired reads - " + ProgramProperties.getProgramName());
dialog.setSize(300, 200);
dialog.setLocationRelativeTo(parent);
Container container = dialog.getContentPane();
container.setLayout(new BorderLayout());
final JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout());
final JPanel midPanel = new JPanel();
midPanel.setLayout(new BorderLayout());
midPanel.setBorder(BorderFactory.createTitledBorder("Specify read pair suffixes:"));
final JPanel innerPanel = new JPanel();
innerPanel.setLayout(new GridLayout(2, 3));
innerPanel.add(new JLabel("Suffix 1"));
innerPanel.add(new JLabel(""));
innerPanel.add(new JLabel("Suffix 2"));
innerPanel.add(field1);
field1.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
if (noSufficesCBox.isSelected())
noSufficesCBox.setSelected(false);
}
public void removeUpdate(DocumentEvent e) {
if (noSufficesCBox.isSelected())
noSufficesCBox.setSelected(false);
}
public void changedUpdate(DocumentEvent e) {
if (noSufficesCBox.isSelected())
noSufficesCBox.setSelected(false);
}
});
innerPanel.add(new JLabel("paired with"));
innerPanel.add(field2);
field2.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
if (noSufficesCBox.isSelected())
noSufficesCBox.setSelected(false);
}
public void removeUpdate(DocumentEvent e) {
if (noSufficesCBox.isSelected())
noSufficesCBox.setSelected(false);
}
public void changedUpdate(DocumentEvent e) {
if (noSufficesCBox.isSelected())
noSufficesCBox.setSelected(false);
}
});
midPanel.add(innerPanel, BorderLayout.CENTER);
centerPanel.add(midPanel, BorderLayout.CENTER);
JPanel nextPanel = new JPanel();
nextPanel.setLayout(new BoxLayout(nextPanel, BoxLayout.LINE_AXIS));
nextPanel.add(new JLabel("Read pairs not distinguished by suffix:"));
nextPanel.add(noSufficesCBox);
noSufficesCBox.setAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
for (Component component : innerPanel.getComponents()) {
component.setEnabled(!noSufficesCBox.isSelected());
}
}
});
centerPanel.add(nextPanel, BorderLayout.SOUTH);
container.add(centerPanel, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
bottomPanel.setBorder(BorderFactory.createEtchedBorder());
bottomPanel.add(new JButton(getCancelAction()));
bottomPanel.add(Box.createHorizontalGlue());
bottomPanel.add(new JButton(getApplyAction()));
container.add(bottomPanel, BorderLayout.SOUTH);
if (this.pairedReadSuffix1.length() == 0)
noSufficesCBox.setSelected(true);
}
/**
* show the dialog
*
* @return true, if not canceled
*/
public boolean showDialog() {
dialog.setVisible(true);
return !canceled;
}
private AbstractAction cancelAction;
private AbstractAction getCancelAction() {
AbstractAction action = cancelAction;
if (action != null)
return action;
action = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
canceled = true;
dialog.setVisible(false);
}
};
action.putValue(Action.NAME, "Cancel");
action.putValue(Action.SHORT_DESCRIPTION, "Cancel this dialog");
return cancelAction = action;
}
private AbstractAction applyAction;
private AbstractAction getApplyAction() {
AbstractAction action = applyAction;
if (action != null)
return action;
action = new AbstractAction() {
public void actionPerformed(ActionEvent actionEvent) {
if (noSufficesCBox.isSelected()) {
importBlastDialog.setPairedReadSuffix1("");
importBlastDialog.setPairedReadSuffix2("");
} else {
pairedReadSuffix1 = field1.getText();
pairedReadSuffix2 = field2.getText();
if (pairedReadSuffix1.equals("?") || pairedReadSuffix2.equals("?")) {
NotificationsInSwing.showError("Must specify suffix for both reads");
return;
}
if (pairedReadSuffix1.length() != pairedReadSuffix2.length()) {
NotificationsInSwing.showError(dialog, "Suffixes must have sample length");
return;
}
importBlastDialog.setPairedReadSuffix1(pairedReadSuffix1);
importBlastDialog.setPairedReadSuffix2(pairedReadSuffix2);
}
dialog.setVisible(false);
}
};
action.putValue(Action.NAME, "Apply");
action.putValue(Action.SHORT_DESCRIPTION, "Use the specified suffixes to pair reads");
return applyAction = action;
}
/**
* try to guess the appropriate patterns
*
* @return patterns
*/
private String[] guessPairedSuffixes(String readsFile) {
String pattern1 = ProgramProperties.get(MeganProperties.PAIRED_READ_SUFFIX1, "?");
String pattern2 = ProgramProperties.get(MeganProperties.PAIRED_READ_SUFFIX2, "?");
if (readsFile != null && readsFile.length() > 0) {
BufferedReader r = null;
try {
r = new BufferedReader(new InputStreamReader(ResourceManager.getFileAsStream(readsFile)));
if (r.ready()) {
String[] words = r.readLine().split(" ");
String name;
if (words.length >= 2) {
if (words[0].equals(">"))
name = words[1];
else
name = words[0];
} else
name = null;
if (name != null) {
if (name.endsWith("_1") || name.endsWith("_2")) {
pattern1 = "_1";
pattern2 = "_2";
} else if (name.endsWith(".1") || name.endsWith(".2")) {
pattern1 = ".1";
pattern2 = ".2";
} else if (name.endsWith("_F3") || name.endsWith("_R3")) {
pattern1 = "_F3";
pattern2 = "_R3";
} else if (name.endsWith("_1,") || name.endsWith("_2,")) {
pattern1 = "_1,";
pattern2 = "_2,";
} else if (name.endsWith(".1,") || name.endsWith(".2,")) {
pattern1 = ".1,";
pattern2 = ".2,";
} else if (name.endsWith("_F3,") || name.endsWith("_R3,")) {
pattern1 = "_F3,";
pattern2 = "_R3,";
} else if (name.endsWith("/1") || name.endsWith("/2")) {
pattern1 = "/1";
pattern2 = "/2";
} else if (name.endsWith(".x") || name.endsWith(".y")) {
pattern1 = ".x";
pattern2 = ".y";
} else if (name.endsWith(".a") || name.endsWith(".b")) {
pattern1 = ".a";
pattern2 = ".b";
}
}
}
} catch (Exception ignored) {
} finally {
if (r != null)
try {
r.close();
} catch (IOException ignored) {
}
}
}
return new String[]{pattern1, pattern2};
}
public String getPairedReadSuffix1() {
return pairedReadSuffix1;
}
public String getPairedReadSuffix2() {
return pairedReadSuffix2;
}
}
| 11,121 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ViewerPanel.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/ViewerPanel.java | /*
* ViewerPanel.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast;
import jloda.swing.commands.CommandManager;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.commands.ICommand;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.classification.IdMapper;
import megan.classification.commandtemplates.*;
import megan.importblast.commands.*;
import javax.swing.*;
import java.awt.*;
/**
* panel for setting functional-viewer related stuff
* Daniel Huson, 12.2012, 4.2015
*/
public class ViewerPanel extends JPanel {
/**
* construct the panel
*
*/
public ViewerPanel(CommandManager commandManager, String cName) {
setLayout(new BorderLayout());
final JPanel centerPanel = new JPanel();
centerPanel.setBorder(BorderFactory.createTitledBorder(cName + " analysis settings"));
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.Y_AXIS));
{
final JPanel aPanel = new JPanel();
JCheckBox checkBox = (JCheckBox) commandManager.getButton(SetAnalyse4ViewerCommand.getName(cName));
if (checkBox.isSelected() && !ClassificationManager.get(cName, true).getIdMapper().hasActiveAndLoaded())
checkBox.setSelected(false);
aPanel.add(checkBox);
centerPanel.add(aPanel);
}
final JPanel panel1 = new JPanel();
panel1.setBorder(BorderFactory.createTitledBorder("How MEGAN identifies " + cName + " classes"));
panel1.setLayout(new BorderLayout());
final JPanel aPanel = new JPanel(new GridLayout(6, 1));
{
final ICommand useFastMode = commandManager.getCommand(SetFastModeCommand.NAME);
final AbstractButton useFastModeButton = commandManager.getButton(useFastMode);
aPanel.add(useFastModeButton);
final ICommand useExtendedMode = commandManager.getCommand(SetExtendedModeCommand.NAME);
final AbstractButton usedExtendedModeButton = commandManager.getButton(useExtendedMode);
aPanel.add(usedExtendedModeButton);
}
final ICommand useMapDBCommand = commandManager.getCommand(SetUseMapType4ViewerCommand.getAltName(cName, IdMapper.MapType.MeganMapDB));
final AbstractButton useMapDBButton = commandManager.getButton(useMapDBCommand);
if (useMapDBCommand instanceof ICheckBoxCommand)
useMapDBButton.setSelected(((ICheckBoxCommand) useMapDBCommand).isSelected());
useMapDBButton.setEnabled(useMapDBCommand.isApplicable());
aPanel.add(useMapDBButton);
{
final JPanel butPanel = new JPanel();
butPanel.setLayout(new BoxLayout(butPanel, BoxLayout.X_AXIS));
butPanel.add(commandManager.getButton(LoadMappingFile4ViewerCommand.getAltName(cName, IdMapper.MapType.MeganMapDB)));
butPanel.add(new JLabel(" " + LoadMappingFile4ViewerCommand.getName(cName, IdMapper.MapType.MeganMapDB)));
butPanel.add(Box.createHorizontalGlue());
aPanel.add(butPanel);
}
final ICommand useAccessionLookupCommand = commandManager.getCommand(SetUseMapType4ViewerCommand.getAltName(cName, IdMapper.MapType.Accession));
final AbstractButton ueseAccessionButton = commandManager.getButton(useAccessionLookupCommand);
if (useAccessionLookupCommand instanceof ICheckBoxCommand)
ueseAccessionButton.setSelected(((ICheckBoxCommand) useAccessionLookupCommand).isSelected());
ueseAccessionButton.setEnabled(useAccessionLookupCommand.isApplicable());
aPanel.add(ueseAccessionButton);
{
final JPanel butPanel = new JPanel();
butPanel.setLayout(new BoxLayout(butPanel, BoxLayout.X_AXIS));
butPanel.add(commandManager.getButton(LoadMappingFile4ViewerCommand.getAltName(cName, IdMapper.MapType.Accession)));
butPanel.add(new JLabel(" " + LoadMappingFile4ViewerCommand.getName(cName, IdMapper.MapType.Accession)));
butPanel.add(Box.createHorizontalGlue());
aPanel.add(butPanel);
}
final ICommand useSynonymsCommand = commandManager.getCommand(SetUseMapType4ViewerCommand.getAltName(cName, IdMapper.MapType.Synonyms));
final AbstractButton useSynomymsButton = commandManager.getButton(useSynonymsCommand);
if (useSynonymsCommand instanceof ICheckBoxCommand)
useSynomymsButton.setSelected(((ICheckBoxCommand) useSynonymsCommand).isSelected());
useSynomymsButton.setEnabled(useSynonymsCommand.isApplicable());
aPanel.add(useSynomymsButton);
{
final JPanel butPanel = new JPanel();
butPanel.setLayout(new BoxLayout(butPanel, BoxLayout.X_AXIS));
butPanel.add(commandManager.getButton(LoadMappingFile4ViewerCommand.getAltName(cName, IdMapper.MapType.Synonyms)));
butPanel.add(new JLabel(" " + LoadMappingFile4ViewerCommand.getName(cName, IdMapper.MapType.Synonyms)));
butPanel.add(Box.createHorizontalGlue());
aPanel.add(butPanel);
}
final ICommand useIDParsingCommand = commandManager.getCommand(SetUseIdParsing4ViewerCommand.getAltName(cName));
final AbstractButton useIdParsingButton = commandManager.getButton(useIDParsingCommand);
if (useIdParsingButton instanceof ICheckBoxCommand)
useIdParsingButton.setSelected(((ICheckBoxCommand) useIDParsingCommand).isSelected());
useIdParsingButton.setEnabled(useIDParsingCommand.isApplicable());
aPanel.add(useIdParsingButton);
if (cName.equals(Classification.Taxonomy)) {
AbstractButton useParseTextButton = commandManager.getButton(SetUseTextTaxonomyCommand.NAME);
aPanel.add(useParseTextButton);
{
aPanel.add(commandManager.getButton(UseContaminantsFilterCommand.NAME));
final JPanel butPanel = new JPanel();
butPanel.setLayout(new BoxLayout(butPanel, BoxLayout.X_AXIS));
butPanel.add(commandManager.getButton(ChooseContaminantsFileCommand.NAME));
butPanel.add(new JLabel(" " + ChooseContaminantsFileCommand.NAME));
butPanel.add(commandManager.getButton(ListContaminantsCommand.NAME));
butPanel.add(Box.createHorizontalGlue());
aPanel.add(butPanel);
}
}
if (!ClassificationManager.getDefaultClassificationsList().contains(cName) && ClassificationManager.getAllSupportedClassifications().contains(cName)) {
final ICommand useLCACommand = commandManager.getCommand(SetUseLCA4ViewerCommand.getAltName(cName));
final AbstractButton useLCAButton = commandManager.getButton(useLCACommand);
if (useLCAButton instanceof ICheckBoxCommand)
useLCAButton.setSelected(((ICheckBoxCommand) useLCACommand).isSelected());
useLCAButton.setEnabled(useLCACommand.isApplicable());
aPanel.add(useLCAButton);
}
panel1.add(aPanel, BorderLayout.CENTER);
centerPanel.add(panel1);
add(centerPanel, BorderLayout.CENTER);
}
}
| 7,992 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ChooseReadsFileCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/ChooseReadsFileCommand.java | /*
* ChooseReadsFileCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.FastaFileFilter;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.importblast.ImportBlastDialog;
import megan.main.MeganProperties;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
/**
* choose reads file
* Daniel Huson, 11.2010
*/
public class ChooseReadsFileCommand extends CommandBase implements ICommand {
public void apply(NexusStreamParser np) {
}
public String getSyntax() {
return null;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent event) {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
File lastOpenFile = ProgramProperties.getFile(MeganProperties.READSFILE);
if (lastOpenFile != null) {
lastOpenFile = new File(lastOpenFile.getParentFile(),
FileUtils.replaceFileSuffix(lastOpenFile.getName(), ".fna"));
}
final FastaFileFilter fastAFileFilter = new FastaFileFilter();
fastAFileFilter.add("fastq");
fastAFileFilter.add("fnq");
fastAFileFilter.add("faq");
fastAFileFilter.setAllowGZipped(true);
fastAFileFilter.setAllowZipped(true);
List<File> files = ChooseFileDialog.chooseFilesToOpen(importBlastDialog, lastOpenFile, fastAFileFilter, fastAFileFilter, event, "Open reads file(s)");
if (files.size() > 0) {
ProgramProperties.put(MeganProperties.READSFILE, files.get(0).getPath());
try {
for (File file : files) {
if (!file.exists())
throw new IOException("No such file: " + file);
if (!file.canRead())
throw new IOException("Cannot read file: " + file);
}
importBlastDialog.setReadFileName(StringUtils.toString(files, "\n"));
importBlastDialog.getReadFileNameField().setText(StringUtils.toString(files, "\n"));
} catch (IOException ex) {
NotificationsInSwing.showError(getViewer().getFrame(), "Failed to load file: " + ex.getMessage());
}
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Browse...";
}
final public static String ALTNAME = "Browse Reads File...";
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getAltName() {
return ALTNAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Choose READS file(s) (in FastA format)";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Open16.gif");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return !Objects.requireNonNull(importBlastDialog.getFormatCBox().getSelectedItem()).toString().equalsIgnoreCase("daa");
}
}
| 4,622 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetPairedReadsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/SetPairedReadsCommand.java | /*
* SetPairedReadsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.importblast.ImportBlastDialog;
import megan.importblast.ReadPairingDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetPairedReadsCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return importBlastDialog != null && importBlastDialog.isUsePairedReads();
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
final ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
if (isSelected())
importBlastDialog.setUsePairedReads(false);
else {
String readsFileName = importBlastDialog.getReadFileName();
if (readsFileName.contains("\n"))
readsFileName = readsFileName.substring(0, readsFileName.indexOf("\n"));
ReadPairingDialog readPairingDialog = new ReadPairingDialog(importBlastDialog, readsFileName);
importBlastDialog.setUsePairedReads(readPairingDialog.showDialog());
}
}
public boolean isApplicable() {
return true;
}
public static final String NAME = "Paired Reads";
public String getName() {
return NAME;
}
public String getDescription() {
return "Paired-read data. Identify paired reads and assign to intersection of the matched taxa";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,746 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CommandBase.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/CommandBase.java | /*
* CommandBase.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import megan.core.Director;
import megan.core.Document;
import megan.importblast.ImportBlastDialog;
import javax.swing.*;
/**
* base class
* Daniel Huson, 11.2010
*/
public abstract class CommandBase extends jloda.swing.commands.CommandBase {
public Director getDir() {
return (Director) super.getDir();
}
public ImportBlastDialog getImportBlastDialog() {
return (ImportBlastDialog) getDir().getViewerByClass(ImportBlastDialog.class);
}
public Document getDoc() {
return getDir().getDocument();
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 1,469 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ChooseMeganFileCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/ChooseMeganFileCommand.java | /*
* ChooseMeganFileCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.util.FileUtils;
import jloda.util.parse.NexusStreamParser;
import megan.importblast.ImportBlastDialog;
import megan.main.MeganProperties;
import megan.util.RMAFileFilter;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
/**
* choose MEGAN file
* Daniel Huson, 11.2010
*/
public class ChooseMeganFileCommand extends CommandBase implements ICommand {
public void apply(NexusStreamParser np) {
}
public String getSyntax() {
return null;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent event) {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
File lastOpenFile;
String name = importBlastDialog.getBlastFileName();
if (name.length() > 0)
lastOpenFile = new File(FileUtils.replaceFileSuffix(name, ".rma6"));
else
lastOpenFile = new File(ProgramProperties.getFile(MeganProperties.SAVEFILE), "Untitled.rma6");
File file = ChooseFileDialog.chooseFileToSave(importBlastDialog, lastOpenFile, new RMAFileFilter(), new RMAFileFilter(), event, "Save MEGAN file", ".rma6");
if (file != null) {
ProgramProperties.put(MeganProperties.SAVEFILE, file);
importBlastDialog.setMeganFileName(file.getPath());
importBlastDialog.getMeganFileNameField().setText(file.getPath());
}
}
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return "Browse...";
}
final public static String ALTNAME = "Browse MEGAN File...";
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getAltName() {
return ALTNAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Choose location to save MEGAN file";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/SaveAs16.gif");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 3,642 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetAnalyseTaxonomyCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/SetAnalyseTaxonomyCommand.java | /*
* SetAnalyseTaxonomyCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetAnalyseTaxonomyCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
return true;
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
}
public boolean isApplicable() {
return false;
}
private final static String NAME = "Analyse taxonomic content";
public String getName() {
return NAME;
}
public String getDescription() {
return "Analyse the taxonomic content of the sample";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 1,910 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ListContaminantsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/ListContaminantsCommand.java | /*
* ListContaminantsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.core.ContaminantManager;
import megan.dialogs.parameters.ParametersDialog;
import megan.importblast.ImportBlastDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
/**
* list contaminants
* Daniel Huson, 11.2017
*/
public class ListContaminantsCommand extends CommandBase implements ICommand {
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* parses and applies the command
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
if (getViewer() instanceof ImportBlastDialog) {
ContaminantManager contaminantManager = new ContaminantManager();
try {
contaminantManager.read(((ImportBlastDialog) getViewer()).getContaminantsFileName());
} catch (IOException e) {
NotificationsInSwing.showError("Failed to parse file: " + ((ImportBlastDialog) getViewer()).getContaminantsFileName()
+ ":\n" + e.getMessage());
}
executeImmediately("show window=message;list taxa=" + contaminantManager.getTaxonIdsString() + " title='Contaminants';");
}
}
final public static String NAME = "List Contaminants";
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return NAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "File provides list of contaminant taxa (ids or names)";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/About16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getParent() instanceof ParametersDialog;
}
}
| 3,686 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
NextTabCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/NextTabCommand.java | /*
* NextTabCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.importblast.ImportBlastDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* next tab
* Daniel Huson, 8.2013
*/
public class NextTabCommand extends CommandBase implements ICommand {
public void apply(NexusStreamParser np) {
}
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
importBlastDialog.getTabbedPane().setSelectedIndex(importBlastDialog.getTabbedPane().getSelectedIndex() + 1);
importBlastDialog.getCommandManager().updateEnableState();
}
public String getName() {
return "Next";
}
final public static String ALTNAME = "Next Tab Command";
public String getAltName() {
return ALTNAME;
}
public String getDescription() {
return "Go to next tab";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
public boolean isApplicable() {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return importBlastDialog.getTabbedPane().getSelectedIndex() < importBlastDialog.getTabbedPane().getTabCount() - 1;
}
}
| 2,219 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
UseContaminantsFilterCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/UseContaminantsFilterCommand.java | /*
* UseContaminantsFilterCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.parse.NexusStreamParser;
import megan.importblast.ImportBlastDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
public class UseContaminantsFilterCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
final ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return importBlastDialog != null && importBlastDialog.isUseContaminantsFilter();
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
final ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
if (isSelected() || importBlastDialog.getContaminantsFileName() != null)
importBlastDialog.setUseContaminantsFilter(!isSelected());
getCommandManager().updateEnableState(ListContaminantsCommand.NAME);
if (isSelected())
NotificationsInSwing.showInformation("Contaminants file: " + importBlastDialog.getContaminantsFileName());
}
public boolean isApplicable() {
final ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return importBlastDialog.getContaminantsFileName() != null && (new File(importBlastDialog.getContaminantsFileName())).exists();
}
public final static String NAME = "Use Contaminants Filter";
public String getName() {
return NAME;
}
private final static String DESCRIPTION = "Filter reads that align to any of the provided contaminants";
public String getDescription() {
return DESCRIPTION;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,914 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetFastModeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/SetFastModeCommand.java | /*
* SetFastModeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.classification.ClassificationManager;
import megan.classification.IdMapper;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* set the fast mapping mode
* daniel Huson, 9.2019
*/
public class SetFastModeCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return ClassificationManager.isUseFastAccessionMappingMode();
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set accessionMapMode=");
final boolean fast = np.getWordMatchesIgnoringCase("fast extended").equalsIgnoreCase("fast");
np.matchIgnoreCase(";");
ClassificationManager.setUseFastAccessionMappingMode(fast);
if (fast) {
for (String cName : ClassificationManager.getAllSupportedClassifications()) {
executeImmediately("use mapType=" + IdMapper.MapType.Accession + " cName=" + cName + " state=false;");
executeImmediately("use mapType=" + IdMapper.MapType.Synonyms + " cName=" + cName + " state=false;");
executeImmediately("set idParsing=false cName=" + cName + ";");
}
executeImmediately("set useParseTextTaxonomy=false;");
}
executeImmediately("update;");
}
public String getSyntax() {
return "set accessionMapMode={extended|fast};";
}
public void actionPerformed(ActionEvent event) {
execute("set accessionMapMode=fast;");
}
public static final String NAME = "Fast Mode";
public String getName() {
return NAME;
}
public String getDescription() {
return "Use fast accession mapping mode, only bulk mapping of the first word in each reference header.\nUse MEGAN mapping db file, no other mapping files or options.";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
public boolean isApplicable() {
return ClassificationManager.getMeganMapDBFile() != null;
}
}
| 3,012 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetUseIdentityFilterCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/SetUseIdentityFilterCommand.java | /*
* SetUseIdentityFilterCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.importblast.ImportBlastDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetUseIdentityFilterCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return importBlastDialog != null && importBlastDialog.isUsePercentIdentityFilter();
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
importBlastDialog.setUsePercentIdentityFilter(!isSelected());
}
public boolean isApplicable() {
return true;
}
public final static String NAME = "Use 16S Percent Identity Filter";
public String getName() {
return NAME;
}
public final static String DESCRIPTION = "For analysis of 16S rRNA reads only.\nAdjust assignment based on best percent identity of matches, using the following minimum requirements:\n" +
"Species 99%, Genus 97%, Family 95%, Order 90%, Class 85%, Phylum 80%";
public String getDescription() {
return DESCRIPTION;
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,505 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetUseTextTaxonomyCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/SetUseTextTaxonomyCommand.java | /*
* SetUseTextTaxonomyCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.classification.ClassificationManager;
import megan.importblast.ImportBlastDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetUseTextTaxonomyCommand extends jloda.swing.commands.CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return importBlastDialog.isParseTaxonNames();
}
public String getSyntax() {
return "set useParseTextTaxonomy=<bool>;";
}
public void apply(NexusStreamParser np) throws Exception {
np.matchIgnoreCase("set useParseTextTaxonomy=");
boolean bool = np.getBoolean();
np.matchIgnoreCase(";");
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
importBlastDialog.setParseTaxonNames(bool);
}
public void actionPerformed(ActionEvent event) {
executeImmediately("set useParseTextTaxonomy=" + (!isSelected()) + ";");
}
public boolean isApplicable() {
return !ClassificationManager.isUseFastAccessionMappingMode();
}
final public static String NAME = "Parse Taxon Names";
public String getName() {
return NAME;
}
public String getDescription() {
return "Parse taxon names embedded in BLAST file to identify taxa";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public boolean isCritical() {
return true;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,581 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetExtendedModeCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/SetExtendedModeCommand.java | /*
* SetExtendedModeCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.util.parse.NexusStreamParser;
import megan.classification.ClassificationManager;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* set the slow mapping mode
* daniel Huson, 9.2019
*/
public class SetExtendedModeCommand extends CommandBase implements ICheckBoxCommand {
@Override
public boolean isSelected() {
return !ClassificationManager.isUseFastAccessionMappingMode();
}
public void apply(NexusStreamParser np) {
}
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
execute("set accessionMapMode=extended;");
}
public static final String NAME = "Extended Mode";
public String getName() {
return NAME;
}
public String getDescription() {
return "Use extended accession mapping mode, attempting to mapping all accessions in reference headers.\nCan be used with MEGAN mapping db file and all other mapping options.";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
public boolean isApplicable() {
return true;
}
}
| 2,090 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
PreviousTabCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/PreviousTabCommand.java | /*
* PreviousTabCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.importblast.ImportBlastDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* previous tab
* Daniel Huson, 8.2013
*/
public class PreviousTabCommand extends CommandBase implements ICommand {
public void apply(NexusStreamParser np) {
}
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
importBlastDialog.getTabbedPane().setSelectedIndex(importBlastDialog.getTabbedPane().getSelectedIndex() - 1);
importBlastDialog.getCommandManager().updateEnableState();
}
public String getName() {
return "Previous";
}
final public static String ALTNAME = "Previous Tab Command";
public String getAltName() {
return ALTNAME;
}
public String getDescription() {
return "Go to previous tab";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
public boolean isApplicable() {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return importBlastDialog.getTabbedPane().getSelectedIndex() > 0;
}
}
| 2,192 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
SetLongReadsCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/SetLongReadsCommand.java | /*
* SetLongReadsCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICheckBoxCommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.core.Document;
import megan.importblast.ImportBlastDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class SetLongReadsCommand extends CommandBase implements ICheckBoxCommand {
public boolean isSelected() {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return importBlastDialog != null && importBlastDialog.isLongReads();
}
public String getSyntax() {
return null;
}
public void apply(NexusStreamParser np) {
}
public void actionPerformed(ActionEvent event) {
ImportBlastDialog dialog = (ImportBlastDialog) getParent();
dialog.setLongReads(!isSelected());
if (dialog.isLongReads()) {
dialog.setLcaAlgorithm(Document.DEFAULT_LCA_ALGORITHM_LONG_READS);
dialog.getMaxNumberOfMatchesPerReadField().setEnabled(false);
dialog.getMaxNumberOfMatchesPerReadLabel().setEnabled(false);
dialog.setReadAssignmentMode(Document.DEFAULT_READ_ASSIGNMENT_MODE_LONG_READS);
} else {
dialog.setLcaAlgorithm(Document.DEFAULT_LCA_ALGORITHM_SHORT_READS);
dialog.getMaxNumberOfMatchesPerReadField().setEnabled(true);
dialog.getMaxNumberOfMatchesPerReadLabel().setEnabled(true);
dialog.setReadAssignmentMode(Document.DEFAULT_READ_ASSIGNMENT_MODE_SHORT_READS);
}
}
public boolean isApplicable() {
return true;
}
public static final String NAME = "Long Reads";
public String getName() {
return NAME;
}
public String getDescription() {
return "Parse and bin long reads and contigs using MEGAN-LR features";
}
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Preferences16.gif");
}
public boolean isCritical() {
return false;
}
public KeyStroke getAcceleratorKey() {
return null;
}
}
| 2,920 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CancelCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/CancelCommand.java | /*
* CancelCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICommand;
import jloda.util.parse.NexusStreamParser;
import megan.importblast.ImportBlastDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* apply
* Daniel Huson, 11.2010
*/
public class CancelCommand extends CommandBase implements ICommand {
public void apply(NexusStreamParser np) {
}
public String getSyntax() {
return null;
}
public void actionPerformed(ActionEvent event) {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
importBlastDialog.setResult(null);
importBlastDialog.destroyView();
}
public String getName() {
return "Cancel";
}
final public static String ALTNAME = "Cancel Import Blast";
public String getAltName() {
return ALTNAME;
}
public String getDescription() {
return "Cancel this dialog";
}
public ImageIcon getIcon() {
return null;
}
public boolean isCritical() {
return true;
}
public boolean isApplicable() {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return importBlastDialog != null;
}
}
| 2,041 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ChooseContaminantsFileCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/ChooseContaminantsFileCommand.java | /*
* ChooseContaminantsFileCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.ChooseFileDialog;
import jloda.swing.util.ProgramProperties;
import jloda.swing.util.ResourceManager;
import jloda.swing.util.TextFileFilter;
import jloda.util.parse.NexusStreamParser;
import megan.commands.CommandBase;
import megan.importblast.ImportBlastDialog;
import megan.main.MeganProperties;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
/**
* choose command
* Daniel Huson, 11.2017
*/
public class ChooseContaminantsFileCommand extends CommandBase implements ICommand {
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* parses and applies the command
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* action to be performed
*
*/
public void actionPerformed(ActionEvent ev) {
if (getViewer() instanceof ImportBlastDialog) {
File lastOpenFile = ProgramProperties.getFile(MeganProperties.CONTAMINANT_FILE);
getDir().notifyLockInput();
final File file = ChooseFileDialog.chooseFileToOpen(getViewer().getFrame(), lastOpenFile, new TextFileFilter(), new TextFileFilter(), ev, "Open Contaminants File");
getDir().notifyUnlockInput();
if (file != null && file.exists() && file.canRead()) {
ProgramProperties.put(MeganProperties.CONTAMINANT_FILE, file.getAbsolutePath());
((ImportBlastDialog) getViewer()).setContaminantsFileName(file.getPath());
((ImportBlastDialog) getViewer()).setUseContaminantsFilter(true);
getCommandManager().updateEnableState(UseContaminantsFilterCommand.NAME);
getCommandManager().updateEnableState(ListContaminantsCommand.NAME);
}
}
}
final public static String NAME = "Load Contaminants File...";
/**
* get the name to be used as a menu label
*
* @return name
*/
public String getName() {
return NAME;
}
final public static String DESCRIPTION = "Loads a list of contaminant taxon names or Ids from a file (one per line)";
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return DESCRIPTION;
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Open16.gif");
}
/**
* gets the accelerator key to be used in menu
*
* @return accelerator key
*/
public KeyStroke getAcceleratorKey() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return getViewer() instanceof ImportBlastDialog;
}
}
| 4,108 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ChooseBlastFileCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/ChooseBlastFileCommand.java | /*
* ChooseBlastFileCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICommand;
import jloda.swing.util.*;
import jloda.util.FileUtils;
import jloda.util.StringUtils;
import jloda.util.parse.NexusStreamParser;
import megan.importblast.ImportBlastDialog;
import megan.main.MeganProperties;
import megan.util.LastMAFFileFilter;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
/**
* choose blast file
* Daniel Huson, 11.2010
*/
public class ChooseBlastFileCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent event) {
final ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
final File lastOpenFile = ProgramProperties.getFile(MeganProperties.BLASTFILE);
BlastFileFilter blastFileFilter = new BlastFileFilter();
blastFileFilter.add("rdp");
blastFileFilter.add("out");
blastFileFilter.add("sam");
blastFileFilter.add("log");
blastFileFilter.add("aln");
blastFileFilter.add("m8");
blastFileFilter.add("daa");
blastFileFilter.add(LastMAFFileFilter.getInstance());
blastFileFilter.setAllowGZipped(true);
blastFileFilter.setAllowZipped(true);
java.util.List<File> files = ChooseFileDialog.chooseFilesToOpen(importBlastDialog, lastOpenFile, blastFileFilter, blastFileFilter, event, "Open BLAST (RDP, Silva or SAM) file(s)");
if (files.size() > 0) {
importBlastDialog.setBlastFileName(StringUtils.toString(files, "\n"));
importBlastDialog.getBlastFileNameField().setText(StringUtils.toString(files, "\n"));
final FastaFileFilter fastaFileFilter = new FastaFileFilter();
fastaFileFilter.add(".fastq");
fastaFileFilter.add(".fnq");
fastaFileFilter.add(".fq");
importBlastDialog.setReadFileName("");
for (File aFile : files) {
String fileName = FileUtils.getAnExistingFileWithGivenExtension(aFile.getPath(), fastaFileFilter.getFileExtensions());
if (fileName == null)
fileName = FileUtils.getAnExistingFileWithGivenExtension(FileUtils.getFilePath(ProgramProperties.get(MeganProperties.READSFILE, ""), aFile.getName()), fastaFileFilter.getFileExtensions());
if (fileName != null)
importBlastDialog.addReadFileName(fileName);
}
importBlastDialog.getReadFileNameField().setText(importBlastDialog.getReadFileName());
final String fileName = (files.size() > 1 ? StringUtils.getCommonPrefix(files.toArray(new File[0]), "out") : files.get(0).getName());
final File meganFile = makeNewRMAFile(files.get(0).getParentFile(), fileName);
importBlastDialog.setMeganFileName(meganFile.getPath());
importBlastDialog.getMeganFileNameField().setText(meganFile.getPath());
ProgramProperties.put(MeganProperties.BLASTFILE, files.get(0));
}
}
/**
* make a new MEGAN file name
*
*/
private File makeNewRMAFile(File directory, String fileName) {
int count = 0;
while (true) {
File meganFile = new File(directory, FileUtils.replaceFileSuffix(FileUtils.getFileNameWithoutZipOrGZipSuffix(fileName), (count > 0 ? "-" + count : "") + ".rma6"));
if (!meganFile.exists())
return meganFile;
count++;
}
}
public String getName() {
return "Browse...";
}
final public static String ALTNAME = "Browse BLAST File...";
public String getAltName() {
return ALTNAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Choose input file(s)";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return ResourceManager.getIcon("sun/Open16.gif");
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return false;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
return true;
}
}
| 5,495 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
ApplyCommand.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/importblast/commands/ApplyCommand.java | /*
* ApplyCommand.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.importblast.commands;
import jloda.swing.commands.ICommand;
import jloda.util.Basic;
import jloda.util.CanceledException;
import jloda.util.parse.NexusStreamParser;
import megan.importblast.ImportBlastDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
/**
* apply
* Daniel Huson, 11.2010, 3.2105
*/
public class ApplyCommand extends CommandBase implements ICommand {
/**
* parses the given command and executes it
*/
@Override
public void apply(NexusStreamParser np) {
}
/**
* get command-line usage description
*
* @return usage
*/
@Override
public String getSyntax() {
return null;
}
/**
* action to be performed
*
*/
@Override
public void actionPerformed(ActionEvent event) {
final ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
try {
importBlastDialog.apply();
} catch (CanceledException ex) {
System.err.println("USER CANCELED");
} catch (IOException ex) {
Basic.caught(ex);
} finally {
if (importBlastDialog != null)
importBlastDialog.destroyView();
}
}
public String getName() {
return "Apply";
}
final public static String ALTNAME = "Apply Import BLAST";
public String getAltName() {
return ALTNAME;
}
/**
* get description to be used as a tooltip
*
* @return description
*/
public String getDescription() {
return "Process the named BLAST (or other comparison) and READ files and produce a new MEGAN file";
}
/**
* get icon to be used in menu or button
*
* @return icon
*/
public ImageIcon getIcon() {
return null;
}
/**
* is this a critical command that can only be executed when no other command is running?
*
* @return true, if critical
*/
public boolean isCritical() {
return true;
}
/**
* is the command currently applicable? Used to set enable state of command
*
* @return true, if command can be applied
*/
public boolean isApplicable() {
ImportBlastDialog importBlastDialog = (ImportBlastDialog) getParent();
return importBlastDialog.isAppliable();
}
}
| 3,189 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
GUIConfiguration.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/treeviewer/GUIConfiguration.java | /*
* GUIConfiguration.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.treeviewer;
import jloda.swing.window.MenuConfiguration;
import megan.classification.data.ClassificationCommandHelper;
/**
* configuration for menu and toolbar
* Daniel Huson, 7.2010
*/
public class GUIConfiguration {
/**
* get the menu configuration
*
* @return menu configuration
*/
public static MenuConfiguration getMenuConfiguration() {
MenuConfiguration menuConfig = new MenuConfiguration();
menuConfig.defineMenuBar("File;Edit;Layout;Window;Help;");
menuConfig.defineMenu("File", "New...;|;Open...;@Open Recent;|;Open From Server...;|;Compare...;|;Import From BLAST...;@Import;Meganize DAA File...;|;Save As...;|;"
+ "Export Image...;Export Legend...;@Export;|;Page Setup...;Print...;|;Properties...;|;Close;|;Quit;");
menuConfig.defineMenu("Server", "Set Server Credentials...;;|;Add User...;Add Metadata...;");
menuConfig.defineMenu("Open Recent", ";");
menuConfig.defineMenu("Export", "Text (CSV) Format...;BIOM1 Format...;STAMP Format...;|;Metadata...;|;Reads...;Matches...;Alignments...;|;MEGAN Summary File...;");
menuConfig.defineMenu("Import", "Import Text (CSV) Format...;Import BIOM Format...;|;Import Metadata...;");
menuConfig.defineMenu("Edit", "Tree Viewer Cut;Tree Viewer Copy;Samples TRee Paste;|;Select All;Select None;Select Similar;From Previous Window;|;Find...;Find Again;");
menuConfig.defineMenu("Window", "Close All Other Windows...;|;Reset Window Location;Set Window Size...;|;Message Window...;|;" +
"Inspector Window...;|;Main Viewer...;" + ClassificationCommandHelper.getOpenViewerMenuString() + "|;Samples Viewer...;Groups Viewer...;|;");
menuConfig.defineMenu("Help", "About...;How to Cite...;|;Community Website...;Reference Manual...;|;Check For Updates...;");
return menuConfig;
}
/**
* gets the toolbar configuration
*
* @return toolbar configuration
*/
public static String getToolBarConfiguration() {
return "Open...;|;Find...;|;Group Nodes;Ungroup All;|;Main Viewer...;"
+ ClassificationCommandHelper.getOpenViewerMenuString();
}
}
| 3,023 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
CSVReadsHitsParser.java | /FileExtraction/Java_unseen/husonlab_megan-ce/src/megan/parsers/CSVReadsHitsParser.java | /*
* CSVReadsHitsParser.java Copyright (C) 2024 Daniel H. Huson
*
* (Some files contain contributions from other authors, who are then mentioned separately.)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package megan.parsers;
import jloda.seq.BlastMode;
import jloda.swing.window.NotificationsInSwing;
import jloda.util.*;
import jloda.util.progress.ProgressListener;
import jloda.util.progress.ProgressPercentage;
import megan.algorithms.MinSupportFilter;
import megan.classification.Classification;
import megan.classification.ClassificationManager;
import megan.classification.IdMapper;
import megan.classification.IdParser;
import megan.core.ClassificationType;
import megan.core.DataTable;
import megan.core.Document;
import megan.viewer.MainViewer;
import megan.viewer.TaxonomyData;
import java.io.File;
import java.io.IOException;
import java.util.*;
/**
* parses a CVS file containing a list of reads and hits
* Daniel Huson, 9.2010
*/
public class CSVReadsHitsParser {
/**
* apply the importer parser to the named file.
* Format should be: readname,taxon,score
*
*/
static public void apply(String fileName, Document doc, String[] cNames, boolean tabSeparator) throws IOException, CanceledException {
final char separator = (tabSeparator ? '\t' : ',');
System.err.println("Importing list of read to CLASS-id hits from CSV file");
System.err.println("Line format: readname,CLASS-id,score - for one of the following classifications: " + StringUtils.toString(cNames, " name,"));
System.err.println("Using topPercent=" + doc.getTopPercent() + " minScore=" + doc.getMinScore() +
(doc.getMinSupportPercent() > 0 ? " minSupportPercent=" + doc.getMinSupportPercent() : "") +
" minSupport=" + doc.getMinSupport());
final DataTable table = doc.getDataTable();
table.clear();
table.setCreator(ProgramProperties.getProgramName());
table.setCreationDate((new Date()).toString());
table.setAlgorithm(ClassificationType.Taxonomy.toString(), "Summary");
doc.getActiveViewers().clear();
doc.getActiveViewers().addAll(Arrays.asList(cNames));
final IdParser[] parsers = new IdParser[cNames.length];
int taxonomyIndex = -1;
for (int i = 0; i < cNames.length; i++) {
final String cName = cNames[i];
parsers[i] = ClassificationManager.get(cName, true).getIdMapper().createIdParser();
ClassificationManager.ensureTreeIsLoaded(cName);
if (!cName.equals(Classification.Taxonomy)) {
doc.getActiveViewers().add(cName);
} else {
taxonomyIndex = i;
}
parsers[i].setUseTextParsing(true);
}
final Map<String, List<Pair<Integer, Float>>>[] readName2IdAndScore = new HashMap[cNames.length];
Arrays.fill(readName2IdAndScore, new HashMap<>());
final int[] count = new int[parsers.length];
int numberOfErrors = 0;
int numberOfLines = 0;
final ProgressListener progress = doc.getProgressListener();
progress.setTasks("Importing CSV file", "Reading " + fileName);
int countInputReadNames = 0;
int countOutputReadNames = 0;
int countClassNames = 0;
int countUnrecognizedClassNames = 0;
try (FileLineIterator it = new FileLineIterator(fileName)) {
progress.setMaximum(it.getMaximumProgress());
progress.setProgress(0);
boolean warnedNoScoreGiven = false;
String prevName = "";
while (it.hasNext()) {
numberOfLines++;
final String aLine = it.next().trim();
if (aLine.length() == 0 || aLine.startsWith("#"))
continue;
try {
final String[] tokens = StringUtils.split(aLine, separator);
if (tokens.length < 2 || tokens.length > 3)
throw new IOException("Line " + numberOfLines + ": incorrect number of columns, expected 2 or 3, got: " + tokens.length);
final String readName = tokens[0].trim();
boolean found = false;
for (int i = 0; !found && i < parsers.length; i++) {
final int id = (parsers.length == 1 && NumberUtils.isInteger(tokens[1]) ? NumberUtils.parseInt(tokens[1]) : parsers[i].getIdFromHeaderLine(tokens[1]));
if (id != 0) {
float score;
if (tokens.length < 3) {
score = 50;
if (!warnedNoScoreGiven) {
System.err.println("Setting score=50 for lines that only contained two tokens, such as line " + numberOfLines + ": '" + aLine + "'");
warnedNoScoreGiven = true;
}
} else
score = Float.parseFloat(tokens[2].trim());
final List<Pair<Integer, Float>> taxonIdAndScore = readName2IdAndScore[i].computeIfAbsent(readName, k -> new LinkedList<>());
taxonIdAndScore.add(new Pair<>(id, score));
if (!readName.equals(prevName))
count[i]++;
found = true;
}
}
countClassNames++;
if (!found) {
System.err.println("Unrecognized name: " + tokens[1]);
countUnrecognizedClassNames++;
}
if (!readName.equals(prevName)) {
countInputReadNames++;
if (found)
countOutputReadNames++;
}
prevName = readName;
} catch (Exception ex) {
System.err.println("Error: " + ex + ", skipping");
numberOfErrors++;
}
progress.setProgress(it.getProgress());
}
}
if (progress instanceof ProgressPercentage)
progress.reportTaskCompleted();
final int totalReads = NumberUtils.max(count);
if (taxonomyIndex >= 0) {
progress.setSubtask("Running LCA");
progress.setProgress(0);
progress.setMaximum(readName2IdAndScore[taxonomyIndex].size());
// run LCA algorithm to get assignment of reads
Map<Integer, float[]> class2counts = new HashMap<>();
Map<Integer, Float> class2count = new HashMap<>();
for (String readName : readName2IdAndScore[taxonomyIndex].keySet()) {
List<Pair<Integer, Float>> taxonIdAndScore = readName2IdAndScore[taxonomyIndex].get(readName);
final int taxId = computeTaxonId(doc, taxonIdAndScore);
if (taxId != 0) {
float[] counts = class2counts.computeIfAbsent(taxId, k -> new float[]{0});
counts[0]++;
if (class2count.get(taxId) == null)
class2count.put(taxId, 1f);
else
class2count.put(taxId, class2count.get(taxId) + 1);
}
progress.incrementProgress();
}
if (progress instanceof ProgressPercentage)
progress.reportTaskCompleted();
// run the minsupport filter
if (doc.getMinSupportPercent() > 0 || doc.getMinSupport() > 1) {
if (doc.getMinSupportPercent() > 0) {
long assigned = 0;
for (int taxId : class2count.keySet()) {
if (taxId > 0)
assigned += class2count.get(taxId);
}
doc.setMinSupport((int) Math.max(1, (doc.getMinSupportPercent() / 100.0) * assigned));
System.err.println("MinSupport set to: " + doc.getMinSupport());
}
if (doc.getMinSupport() > 1) {
final MinSupportFilter minSupportFilter = new MinSupportFilter(Classification.Taxonomy, class2count, doc.getMinSupport(), progress);
try {
Map<Integer, Integer> changes = minSupportFilter.apply();
for (Integer oldTaxId : changes.keySet()) {
Integer newTaxId = changes.get(oldTaxId);
float oldCount = class2counts.get(oldTaxId)[0];
float[] newCounts = class2counts.get(newTaxId);
if (newCounts == null) {
newCounts = new float[]{oldCount};
class2counts.put(newTaxId, newCounts);
} else {
newCounts[0] += oldCount;
}
class2counts.remove(oldTaxId);
}
} catch (CanceledException ignored) {
}
}
}
System.err.printf("Reads in:%,13d%n", countInputReadNames);
System.err.printf("Reads out:%,12d%n", countOutputReadNames);
System.err.printf("Class names:%,10d%n", countClassNames);
if (countUnrecognizedClassNames > 0)
System.err.printf("Unrecognized:%,9d%n", countUnrecognizedClassNames);
if (countOutputReadNames < countInputReadNames) {
float[] unassignedCounts = class2counts.computeIfAbsent(IdMapper.UNASSIGNED_ID, k -> new float[]{0});
unassignedCounts[0] += (countInputReadNames - countOutputReadNames);
}
table.getClassification2Class2Counts().put(ClassificationType.Taxonomy.toString(), class2counts);
} else {
Map<Integer, float[]> class2counts = new HashMap<>();
class2counts.put(IdMapper.UNASSIGNED_ID, new float[]{totalReads});
table.getClassification2Class2Counts().put(ClassificationType.Taxonomy.toString(), class2counts);
}
for (int i = 0; i < cNames.length; i++) {
if (i != taxonomyIndex) {
progress.setSubtask("Classifying " + cNames[i]);
progress.setProgress(0);
progress.setMaximum(readName2IdAndScore[i].size());
Map<Integer, float[]> class2counts = new HashMap<>();
Map<Integer, Float> class2count = new HashMap<>();
for (String readName : readName2IdAndScore[i].keySet()) {
final List<Pair<Integer, Float>> classIdAndScore = readName2IdAndScore[i].get(readName);
final int classId = getBestId(classIdAndScore);
if (classId != 0) {
float[] counts = class2counts.computeIfAbsent(classId, k -> new float[]{0});
counts[0]++;
if (class2count.get(classId) == null)
class2count.put(classId, 1f);
else
class2count.put(classId, class2count.get(classId) + 1);
}
progress.incrementProgress();
}
table.getClassification2Class2Counts().put(cNames[i], class2counts);
if (progress instanceof ProgressPercentage)
progress.reportTaskCompleted();
}
}
table.setSamples(new String[]{FileUtils.getFileBaseName(new File(fileName).getName())}, null, new float[]{totalReads}, new BlastMode[]{BlastMode.Unknown});
table.setTotalReads(totalReads);
doc.setNumberReads(totalReads);
for (int i = 0; i < cNames.length; i++) {
if (i != taxonomyIndex)
doc.getActiveViewers().remove(cNames[i]);
}
if (numberOfErrors > 0)
NotificationsInSwing.showWarning(MainViewer.getLastActiveFrame(), "Lines skipped during import: " + numberOfErrors + " (of " + numberOfLines + ")");
System.err.println("done (" + totalReads + " reads)");
}
private static int getBestId(List<Pair<Integer, Float>> idAndScore) {
int bestId = 0;
float bestScore = 0;
for (Pair<Integer, Float> pair : idAndScore) {
if (pair.getSecond() > bestScore) {
bestScore = pair.getSecond();
bestId = pair.getFirst();
}
}
return bestId;
}
/**
* compute the taxon id for a read using the LCA algorithm
*
* @return taxonId
*/
private static int computeTaxonId(Document doc, List<Pair<Integer, Float>> taxonIdAndScore) {
final Pair<Integer, Float>[] pairs = taxonIdAndScore.toArray((Pair<Integer, Float>[]) new Pair[taxonIdAndScore.size()]);
// sort by decreasing bit-score:
Arrays.sort(pairs, (pair1, pair2) -> pair2.getSecond().compareTo(pair1.getSecond()));
Set<Integer> taxonIds = new HashSet<>();
Float bestScore = null;
double threshold = doc.getMinScore();
for (Pair<Integer, Float> pair : pairs) {
Integer taxonId = pair.getFirst();
Float score = pair.getSecond();
if (score >= threshold) {
if (bestScore == null) {
bestScore = score;
taxonIds.add(taxonId);
if (doc.getTopPercent() != 0) {
threshold = Math.max((1.0 - doc.getTopPercent() / 100.0) * bestScore, threshold);
}
}
taxonIds.add(taxonId);
}
}
return TaxonomyData.getLCA(taxonIds, true);
}
}
| 14,582 | Java | .java | husonlab/megan-ce | 62 | 21 | 18 | 2016-05-09T10:55:38Z | 2024-02-22T23:23:42Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.