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
TabbedTopicSelector.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/TabbedTopicSelector.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TabbedTopicSelector.java * * Created on 17. helmikuuta 2006, 13:09 */ package org.wandora.application.gui; import java.awt.Component; import java.util.ArrayList; import java.util.List; import org.wandora.application.gui.search.SearchPanel; import org.wandora.application.gui.search.SelectTopicPanel; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.topicmap.Topic; import org.wandora.utils.swing.GuiTools; /** * * @author olli */ public class TabbedTopicSelector extends javax.swing.JPanel implements TopicSelector { private static final long serialVersionUID = 1L; private List<TopicSelector> selectors; private boolean wasCancelled=true; private boolean cleared=false; /** Creates new form TabbedTopicSelector */ public TabbedTopicSelector() { selectors=new ArrayList<>(); initComponents(); clearButton.setVisible(false); } public void insertTab(TopicSelector selector, int index){ selectors.add(index, selector); tabbedPane.insertTab(selector.getSelectorName(),null,selector.getPanel(),null,index); } public void addTab(TopicSelector selector){ selectors.add(selector); tabbedPane.addTab(selector.getSelectorName(),selector.getPanel()); } @Override public Topic[] getSelectedTopics() { if(cleared) return new Topic[0]; TopicSelector selector=selectors.get(tabbedPane.getSelectedIndex()); return selector.getSelectedTopics(); } @Override public Topic getSelectedTopic() { if(cleared) return null; TopicSelector selector=selectors.get(tabbedPane.getSelectedIndex()); return selector.getSelectedTopic(); } @Override public Component getPanel() { return this; } @Override public String getSelectorName(){ return "Tabbed selector"; } public void setClearVisible(boolean b){ clearButton.setVisible(b); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; tabbedPane = new SimpleTabbedPane(); buttonPanel = new javax.swing.JPanel(); rememberCheckBox = new SimpleCheckBox(); jPanel1 = new javax.swing.JPanel(); clearButton = new SimpleButton(); selectButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); tabbedPane.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { tabbedPaneMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(tabbedPane, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); rememberCheckBox.setText("Remember"); buttonPanel.add(rememberCheckBox, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(jPanel1, gridBagConstraints); clearButton.setLabel("Select none"); clearButton.setMargin(new java.awt.Insets(2, 1, 2, 1)); clearButton.setMaximumSize(new java.awt.Dimension(80, 23)); clearButton.setMinimumSize(new java.awt.Dimension(80, 23)); clearButton.setPreferredSize(new java.awt.Dimension(80, 23)); clearButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 8); buttonPanel.add(clearButton, gridBagConstraints); selectButton.setText("Select"); selectButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); selectButton.setMaximumSize(new java.awt.Dimension(70, 23)); selectButton.setMinimumSize(new java.awt.Dimension(70, 23)); selectButton.setPreferredSize(new java.awt.Dimension(70, 23)); selectButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { selectButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); buttonPanel.add(selectButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed wasCancelled=false; cleared=true; java.awt.Window w=GuiTools.getWindow(this); if(w!=null) w.setVisible(false); }//GEN-LAST:event_clearButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed wasCancelled=true; cleared=false; java.awt.Window w=GuiTools.getWindow(this); if(w!=null) w.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void selectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectButtonActionPerformed wasCancelled=false; java.awt.Window w=GuiTools.getWindow(this); if(w!=null) w.setVisible(false); }//GEN-LAST:event_selectButtonActionPerformed private void tabbedPaneMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabbedPaneMouseReleased Component currentTab = tabbedPane.getSelectedComponent(); if(currentTab != null) { if(currentTab instanceof SearchPanel) { ((SearchPanel) currentTab).requestSearchFieldFocus(); } else if(currentTab instanceof SelectTopicPanel) { ((SelectTopicPanel) currentTab).requestSearchFieldFocus(); } } }//GEN-LAST:event_tabbedPaneMouseReleased public boolean wasCancelled(){ return wasCancelled; } @Override public void init(){ // tabbedPane.setSelectedIndex(0); for(TopicSelector s : selectors) s.init(); } @Override public void cleanup(){ for(TopicSelector s : selectors) s.cleanup(); } public boolean remember() { return rememberCheckBox.isSelected(); } public void setRemember(boolean remember) { rememberCheckBox.setSelected(remember); } public Component getSelectedSelector() { return tabbedPane.getSelectedComponent(); } public void setSelectedSelector(Component s) { tabbedPane.setSelectedComponent(s); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JButton clearButton; private javax.swing.JPanel jPanel1; private javax.swing.JCheckBox rememberCheckBox; private javax.swing.JButton selectButton; private javax.swing.JTabbedPane tabbedPane; // End of variables declaration//GEN-END:variables }
9,795
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolTree.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/WandoraToolTree.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * ToolTree.java * * Created on 19.2.2008, 10:47 * */ package org.wandora.application.gui; import java.awt.Component; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.util.Enumeration; import javax.swing.DropMode; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.JTree; import javax.swing.ToolTipManager; import javax.swing.TransferHandler; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.WandoraToolManager2; import org.wandora.application.WandoraToolSet; import org.wandora.application.gui.simple.SimpleTree; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.utils.Textbox; /** * * @author akivela */ public class WandoraToolTree extends SimpleTree implements MouseListener, TreeModelListener, TreeSelectionListener, ActionListener /*, DragSourceListener, DragGestureListener*/ { private static final long serialVersionUID = 1L; private Wandora wandora; private MouseEvent mouseEvent; private WandoraToolSet toolSet = null; protected TreeModel toolTreeModel = null; private Object[] toolTreeMenuStruct = new Object[] { "Add tool...", "Add group...", "---", "Rename...", "Delete...", "---", "Execute...", "Configure...", "Release tool locks...", "Kill threads...", "---", "Info...", }; private JPopupMenu toolTreeMenu = null; public WandoraToolTree(Wandora parent) { this.wandora = parent; } public void initialize(WandoraToolSet toolSet) { this.toolSet = toolSet; this.setRootVisible(false); this.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); this.addTreeSelectionListener(this); this.putClientProperty("JTree.lineStyle", "None"); this.setCellRenderer(new ToolTreeRenderer()); this.setEditable(false); this.setDragEnabled(true); this.setDropMode(DropMode.ON); this.setTransferHandler(new ToolTreeTransferHandler()); ToolTipManager.sharedInstance().registerComponent(this); this.addMouseListener(this); this.toolTreeMenu = UIBox.makePopupMenu(toolTreeMenuStruct, this); this.setComponentPopupMenu(toolTreeMenu); ToolTreeNode top = new ToolTreeNode(toolSet); createNodes(top, toolSet); toolTreeModel = new DefaultTreeModel(top); toolTreeModel.addTreeModelListener(this); this.setModel(toolTreeModel); } public void createNodes(ToolTreeNode node, WandoraToolSet toolSet) { Object[] ts = toolSet.asArray(); Object to = null; ToolTreeNode subnode = null; WandoraToolSet subset = null; WandoraToolSet.ToolItem toolWrapper = null; for(int i=0; i<ts.length; i++) { to = ts[i]; if(to != null) { if(to instanceof WandoraToolSet) { subset = (WandoraToolSet) to; //System.out.println("adding subtree "+subset+" to tool tree"); subnode = new ToolTreeNode(subset); createNodes(subnode, subset); subnode.setParentNode(node); node.add(subnode); } else if(to instanceof WandoraToolSet.ToolItem) { toolWrapper = (WandoraToolSet.ToolItem) to; //System.out.println("adding tool "+toolWrapper+" to tool tree"); subnode = new ToolTreeNode(toolWrapper); subnode.setParentNode(node); node.add(subnode); } } } } public Object addNode(WandoraToolSet set) { return addNode((Object) set); } public Object addNode(WandoraToolSet.ToolItem tool) { return addNode((Object) tool); } private Object addNode(Object n) { TreePath parentPath = this.getSelectionPath(); ToolTreeNode parentNode = null; if(parentPath == null) { //There is no selection. Default to the root node. parentNode = (ToolTreeNode) this.getModel().getRoot(); } else { parentNode = (ToolTreeNode) (parentPath.getLastPathComponent()); while(!parentNode.isSet()) { parentNode = parentNode.getParentNode(); } } ToolTreeNode childNode = null; if(n instanceof WandoraToolSet.ToolItem) { childNode = new ToolTreeNode((WandoraToolSet.ToolItem) n); } if(n instanceof WandoraToolSet) { childNode = new ToolTreeNode((WandoraToolSet) n); } if(childNode != null) { childNode.setParentNode(parentNode); ((DefaultTreeModel) toolTreeModel).insertNodeInto( childNode, parentNode, parentNode.getChildCount() ); scrollPathToVisible(new TreePath(childNode.getPath())); WandoraToolSet set = (WandoraToolSet) parentNode.getUserObject(); set.add(n); return parentNode.getUserObject(); } return null; } public Object renameCurrentNode(String newName) { TreePath parentPath = this.getSelectionPath(); if(parentPath != null) { ToolTreeNode node = (ToolTreeNode) (parentPath.getLastPathComponent()); Object o = node.getUserObject(); if(o instanceof WandoraToolSet) { ((WandoraToolSet) o).setName(newName); } else if(o instanceof WandoraToolSet.ToolItem) { ((WandoraToolSet.ToolItem) o).setName(newName); } return o; } return null; } public Object removeCurrentNode() { TreePath selectionPath = this.getSelectionPath(); if(selectionPath != null) { ToolTreeNode currentNode = (ToolTreeNode) (selectionPath.getLastPathComponent()); if(currentNode != null) { ((DefaultTreeModel) toolTreeModel).removeNodeFromParent(currentNode); ToolTreeNode parentNode = currentNode.getParentNode(); WandoraToolSet set = (WandoraToolSet) parentNode.getUserObject(); set.remove(currentNode.getUserObject()); return currentNode.getUserObject(); } } return null; } public ToolTreeNode solveNode(int nodeHash) { ToolTreeNode root = (ToolTreeNode) this.getModel().getRoot(); return solveNode(nodeHash, root); } public ToolTreeNode solveNode(int hash, ToolTreeNode node) { if(hash == node.hashCode()) return node; else { ToolTreeNode child = null; for(Enumeration children = node.children() ; children.hasMoreElements(); ) { child = (ToolTreeNode) children.nextElement(); ToolTreeNode childnode = solveNode(hash, child); if(childnode != null) return childnode; } } return null; } public void refresh() { this.setModel(toolTreeModel); this.validate(); this.repaint(); // System.out.println("refresh acquired"); } public WandoraToolSet getToolSet() { return toolSet; } public WandoraToolSet.ToolItem getSelectedTool() { TreePath parentPath = this.getSelectionPath(); if(parentPath != null) { ToolTreeNode node = (ToolTreeNode) (parentPath.getLastPathComponent()); Object o = node.getUserObject(); if(o instanceof WandoraToolSet.ToolItem) { return (WandoraToolSet.ToolItem) o; } } return null; } // ------------------------------------------------------------------------- @Override public void actionPerformed(ActionEvent e) { String c = e.getActionCommand(); if(c == null) return; c = c.toLowerCase(); // System.out.println("actionPerformed @ ToolTree "+e); // ***** EXECUTE ***** if(c.startsWith("execute")) { try { WandoraToolSet.ToolItem toolItem = getSelectedTool(); if(toolItem != null) { WandoraTool t = toolItem.getTool(); t.execute(wandora); } } catch(Exception ex) { ex.printStackTrace(); } catch(Error er) { er.printStackTrace(); } } // ***** CONFIGURE ***** else if(c.startsWith("configure")) { try { WandoraToolSet.ToolItem toolItem = getSelectedTool(); if(toolItem != null) { WandoraTool t = toolItem.getTool(); if(t.isConfigurable()) { t.configure(wandora, wandora.getOptions(), wandora.getToolManager().getOptionsPrefix(t)); } else { WandoraOptionPane.showMessageDialog(wandora, "Tool is not configurable!", "Not configurable"); } } } catch(Exception ex) { ex.printStackTrace(); } catch(Error er) { er.printStackTrace(); } } // ***** RENAME ***** else if(c.startsWith("rename")) { if(getSelectionPath() != null) { String newName = WandoraOptionPane.showInputDialog(wandora, "Give new name for selected node?", "", "Rename node"); if(newName != null) { renameCurrentNode(newName); } } } // ***** DELETE ***** else if(c.startsWith("delete")) { if(getSelectionPath() != null) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Remove selected tool or folder?", "Confirm remove"); if(a == WandoraOptionPane.YES_OPTION) { removeCurrentNode(); } } } // ***** ADD TOOL ***** else if(c.startsWith("add tool")) { WandoraToolSelector toolSelector = new WandoraToolSelector(wandora); if(toolSelector.selectToolAccepted()) { WandoraTool addedTool = toolSelector.getSelectedTool(); if(addedTool != null) { // toolSet.new ToolWrapper(toolName, (WandoraTool) n) String toolName = addedTool.getName(); WandoraToolSet rootSet = getRootSet(); WandoraToolSet.ToolItem toolWrapper = rootSet.new ToolItem(toolName, addedTool); addNode(toolWrapper); } } } // ***** ADD GROUP ***** else if(c.startsWith("add group")) { String name = WandoraOptionPane.showInputDialog(wandora, "Give name for new group?", "", "Group name"); if(name != null) { if(name.length() > 0) { WandoraToolSet group = new WandoraToolSet(name, wandora); addNode(group); } else { WandoraOptionPane.showMessageDialog(wandora, "Given name is zero length. Cancelling folder creation.", "Too short folder name"); } } } // ***** RELEASE TOOL LOCKS ***** else if(c.startsWith("release tool locks")) { try { WandoraToolSet.ToolItem toolItem = getSelectedTool(); if(toolItem != null) { WandoraTool t = toolItem.getTool(); String className = t.getClass().getSimpleName(); if(t instanceof AbstractWandoraTool && !((AbstractWandoraTool) t).allowMultipleInvocations()) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Are you sure you want to release tool lock for class '"+className+"'", "Release tool lock"); if(a == WandoraOptionPane.YES_OPTION) { boolean released = ((AbstractWandoraTool) t).clearToolLock(); if(!released) WandoraOptionPane.showMessageDialog(wandora, "Tool class '"+className+"' was not locked. Couldn't release tool locks."); } } else { WandoraOptionPane.showMessageDialog(wandora, "Tool class '"+className+"' doesn't support tool locks. Can't release tool locks."); } } } catch(Exception ex) { ex.printStackTrace(); } catch(Error er) { er.printStackTrace(); } } // ***** KILL TOOL THREADS ***** else if(c.startsWith("kill threads")) { try { WandoraToolSet.ToolItem toolItem = getSelectedTool(); if(toolItem != null) { WandoraTool t = toolItem.getTool(); String className = t.getClass().getSimpleName(); if(t instanceof AbstractWandoraTool && ((AbstractWandoraTool) t).runInOwnThread()) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Are you sure you want to interrupt tool threads for class '"+className+"'", "Interrupt tool threads"); if(a == WandoraOptionPane.YES_OPTION) { ((AbstractWandoraTool) t).interruptThreads(); } } else { WandoraOptionPane.showMessageDialog(wandora, "Tool class '"+className+"' doesn't support interrups. Can't kill tool threads."); } } } catch(Exception ex) { ex.printStackTrace(); } catch(Error er) { er.printStackTrace(); } } // ***** TOOL INFO ***** else if(c.startsWith("info")) { try { WandoraToolSet.ToolItem wrappedTool = getSelectedTool(); if(wrappedTool != null) { WandoraToolManager2 toolManager=wandora.getToolManager(); WandoraToolManager2.ToolInfo info=null; WandoraTool tool=getSelectedTool().getTool(); if(toolManager!=null) info=toolManager.getToolInfo(tool); new WandoraToolInfoDialog(wandora, tool,info); } } catch(Exception ex) { ex.printStackTrace(); } } // ****** FINALLY REFRESH TOOL TREE this.refresh(); } public WandoraToolSet getRootSet() { ToolTreeNode rootNode = (ToolTreeNode) this.getModel().getRoot(); return (WandoraToolSet) rootNode.getUserObject(); } // ------------------------------------------------------------------------- @Override public void valueChanged(TreeSelectionEvent e) { //System.out.println("valueChanged @ tooltree"); } // ------------------------------------------------------------------------- @Override public void treeNodesChanged(TreeModelEvent e) { DefaultMutableTreeNode node; node = (DefaultMutableTreeNode) (e.getTreePath().getLastPathComponent()); /* * If the event lists children, then the changed * node is the child of the node we have already * gotten. Otherwise, the changed node and the * specified node are the same. */ try { int index = e.getChildIndices()[0]; node = (DefaultMutableTreeNode) (node.getChildAt(index)); } catch (NullPointerException exc) {} System.out.println("The user has finished editing the node."); System.out.println("New value: " + node.getUserObject()); } @Override public void treeNodesInserted(TreeModelEvent e) { } @Override public void treeNodesRemoved(TreeModelEvent e) { } @Override public void treeStructureChanged(TreeModelEvent e) { } // ------------------------------------------------------------------------- @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; if(mouseEvent.getClickCount()>=2) { try { WandoraToolSet.ToolItem wrappedTool = getSelectedTool(); if(wrappedTool != null) { WandoraToolManager2 toolManager=wandora.getToolManager(); WandoraToolManager2.ToolInfo info=null; WandoraTool tool=getSelectedTool().getTool(); if(toolManager!=null) info=toolManager.getToolInfo(tool); new WandoraToolInfoDialog(wandora, tool,info); } } catch(Exception e) { e.printStackTrace(); } } } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } // ------------------------------------------------------------------------- public class ToolTreeNode extends DefaultMutableTreeNode { private WandoraToolSet toolSet = null; private WandoraToolSet.ToolItem toolItem = null; private ToolTreeNode parentNode = null; public ToolTreeNode(WandoraToolSet set) { super(); this.toolSet = set; } public ToolTreeNode(WandoraToolSet.ToolItem wrapper) { super(); this.toolItem = wrapper; } @Override public Object getUserObject() { return (toolSet != null ? toolSet : toolItem); } public void setParentNode(ToolTreeNode node) { this.parentNode = node; } public ToolTreeNode getParentNode() { return parentNode; } public boolean isSet() { return (toolSet != null); } @Override public String toString() { Object o = getUserObject(); return (o != null ? o.toString() : "null"); } } // ------------------------------------------------------------------------- public class ToolTreeRenderer extends DefaultTreeCellRenderer implements TreeCellRenderer { private Icon toolSetIcon = null; public ToolTreeRenderer() { toolSetIcon = UIBox.getIcon("gui/icons/tool_set.png"); } @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); try { if(c instanceof JLabel) { JLabel l = (JLabel) c; Object userValueContent = ((DefaultMutableTreeNode) value).getUserObject(); //System.out.println("userValue == " +userValueContent+" --- " +userValueContent.getClass()); if(userValueContent instanceof WandoraToolSet.ToolItem) { WandoraToolSet.ToolItem tool = (WandoraToolSet.ToolItem) userValueContent; l.setText(tool.getName()); l.setIcon(tool.getTool().getIcon()); setToolTipText(Textbox.makeHTMLParagraph(tool.getTool().getDescription(), 40)); } else if(userValueContent instanceof WandoraToolSet) { if(toolSetIcon != null) { l.setIcon(toolSetIcon); } } } } catch(Exception e) { e.printStackTrace(); } return c; } } // ------------------------------------------------------------------------- public static class ToolTreeTransferable extends DnDHelper.WandoraTransferable { public static final DataFlavor toolTreeNodeFlavor = new DataFlavor(ToolTreeNode.class,"ToolTreeNode"); protected Object transferable; public ToolTreeTransferable(ToolTreeNode node) { this.transferable=node.hashCode(); } @Override public void updateFlavors() { super.updateFlavors(); if(this.transferable==null) return; DataFlavor[] old=supportedFlavors; supportedFlavors=new DataFlavor[old.length+1]; supportedFlavors[0]=toolTreeNodeFlavor; System.arraycopy(old, 0, supportedFlavors, 1, old.length); } @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if(transferable!=null && (flavor.equals(toolTreeNodeFlavor))) return transferable; else return super.getTransferData(flavor); } } public class ToolTreeTransferHandler extends TransferHandler { @Override public boolean canImport(TransferSupport support) { if(!support.isDrop()) return false; return support.isDataFlavorSupported(ToolTreeTransferable.toolTreeNodeFlavor); } @Override protected Transferable createTransferable(JComponent c) { TreePath path=getSelectionPath(); if(path==null) return new ToolTreeTransferable(null); else { ToolTreeNode toolNode = (ToolTreeNode) path.getLastPathComponent(); return new ToolTreeTransferable(toolNode); } } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY_OR_MOVE; } @Override public boolean importData(TransferSupport support) { if(!support.isDrop()) return false; try{ if(support.isDataFlavorSupported(ToolTreeTransferable.toolTreeNodeFlavor)) { Object movedNodeHash = (Object)support.getTransferable().getTransferData(ToolTreeTransferable.toolTreeNodeFlavor); ToolTreeNode movedNode = solveNode(((Integer)movedNodeHash).intValue()); int action=support.getDropAction(); JTree.DropLocation location=(JTree.DropLocation)support.getDropLocation(); TreePath dropPath=location.getPath(); if(dropPath==null){ //WandoraOptionPane.showMessageDialog(TopicTree.this.parent,"Invalid drop location, drop cancelled."); return false; } ToolTreeNode targetNode = (ToolTreeNode)dropPath.getLastPathComponent(); ToolTreeNode targetSetNode = targetNode; while(!targetSetNode.isSet()) { targetSetNode = targetSetNode.getParentNode(); } int index = targetSetNode.getIndex(targetNode); index = Math.max(0, Math.min(index, targetSetNode.getChildCount()-1)); if(targetSetNode.isNodeAncestor(movedNode)) { WandoraOptionPane.showMessageDialog(wandora, "Can't move the item in itself.", "Illegal drop path"); return false; } try { ((DefaultTreeModel) toolTreeModel).removeNodeFromParent(movedNode); WandoraToolSet sourceSet = (WandoraToolSet) movedNode.getParentNode().getUserObject(); sourceSet.remove(movedNode.getUserObject()); ((DefaultTreeModel) toolTreeModel).insertNodeInto(movedNode, targetSetNode, index); WandoraToolSet targetSet = (WandoraToolSet) targetSetNode.getUserObject(); Object o = movedNode.getUserObject(); targetSet.add(o, index); scrollPathToVisible(new TreePath(movedNode.getPath())); } catch(Exception e){ e.printStackTrace(); return false; } doRefresh(); return true; } } //catch(UnsupportedFlavorException ufe){ufe.printStackTrace();} catch(Exception e) { e.printStackTrace(); } return false; } public void doRefresh(){ WandoraToolTree.this.refresh(); } } }
28,044
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ResourceEditor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/ResourceEditor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * ResourceAssociationEditor.java * * Created on August 9, 2004, 2:47 PM */ package org.wandora.application.gui; import org.wandora.application.Wandora; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public abstract class ResourceEditor extends javax.swing.JPanel { public abstract void initializeAssociation(Topic t,Association a,Wandora parent) throws TopicMapException ; public abstract void initializeOccurrence(Topic t,Topic otype,Wandora parent) throws TopicMapException ; public abstract boolean applyChanges(Topic t,Wandora parent) throws TopicMapException ; public abstract boolean hasChanged() throws TopicMapException ; }
1,563
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SchemaAssociationPrompt.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/SchemaAssociationPrompt.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SchemaAssociationPrompt.java * * Created on August 11, 2004, 9:16 AM */ package org.wandora.application.gui; import java.awt.Dimension; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Vector; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.topicmap.Association; import org.wandora.topicmap.SchemaBox; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.layered.LayerStack; import org.wandora.topicmap.layered.LayeredAssociation; import org.wandora.topicmap.layered.LayeredTopic; /** * @deprecated * * @author olli, ak */ public class SchemaAssociationPrompt extends javax.swing.JDialog implements Runnable { private Topic topic; private Wandora parent; private boolean running; private Object newAssociationType; private Object newRole; private HashMap roleMap; private Thread workerThread; private Topic associationType; private Topic associationTypeBeforeAdd; private Topic topicRole; private Topic topicRoleBeforeAdd; private boolean cancelled; private Association original; /** Creates new form SchemaAssociationPrompt */ public SchemaAssociationPrompt(Wandora parent, Topic topic,boolean modal) throws TopicMapException { this(parent,topic,modal,null); } public SchemaAssociationPrompt(Wandora parent, Topic topic,boolean modal,Association original) throws TopicMapException { super(parent, modal); this.original=original; this.parent=parent; this.topic=topic; roleMap=new HashMap(); initComponents(); topicLabel.setText(topic.getBaseName()); workerThread=new Thread(this); running=true; workerThread.start(); parent.centerWindow(this); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonPanel = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); cancelButton = new org.wandora.application.gui.simple.SimpleButton(); jPanel4 = new javax.swing.JPanel(); applyButton = new org.wandora.application.gui.simple.SimpleButton(); okButton = new org.wandora.application.gui.simple.SimpleButton(); associationPanel = new javax.swing.JPanel(); associationTypePanel = new javax.swing.JPanel(); associationTypeComboBox = new javax.swing.JComboBox(); jSeparator1 = new javax.swing.JSeparator(); thisPanel = new javax.swing.JPanel(); roleComboBox = new javax.swing.JComboBox(); topicLabel = new javax.swing.JLabel(); otherPanel = new javax.swing.JPanel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Association editor"); getContentPane().setLayout(new java.awt.BorderLayout(15, 5)); buttonPanel.setPreferredSize(new java.awt.Dimension(300, 45)); buttonPanel.setLayout(new java.awt.BorderLayout()); jPanel5.setPreferredSize(new java.awt.Dimension(105, 45)); jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 15, 10)); cancelButton.setText("Cancel"); cancelButton.setMinimumSize(new java.awt.Dimension(75, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(75, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); jPanel5.add(cancelButton); buttonPanel.add(jPanel5, java.awt.BorderLayout.WEST); jPanel4.setPreferredSize(new java.awt.Dimension(185, 45)); jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 10)); applyButton.setText("Add"); applyButton.setEnabled(false); applyButton.setMaximumSize(new java.awt.Dimension(75, 23)); applyButton.setMinimumSize(new java.awt.Dimension(75, 23)); applyButton.setPreferredSize(new java.awt.Dimension(75, 23)); applyButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { applyButtonActionPerformed(evt); } }); jPanel4.add(applyButton); okButton.setText("OK"); okButton.setEnabled(false); okButton.setMinimumSize(new java.awt.Dimension(75, 23)); okButton.setPreferredSize(new java.awt.Dimension(75, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); jPanel4.add(okButton); buttonPanel.add(jPanel4, java.awt.BorderLayout.EAST); getContentPane().add(buttonPanel, java.awt.BorderLayout.SOUTH); associationPanel.setMinimumSize(new java.awt.Dimension(686, 200)); associationPanel.setPreferredSize(new java.awt.Dimension(930, 200)); associationPanel.setLayout(new java.awt.GridBagLayout()); associationTypePanel.setMaximumSize(new java.awt.Dimension(500, 22)); associationTypePanel.setMinimumSize(new java.awt.Dimension(300, 22)); associationTypePanel.setPreferredSize(new java.awt.Dimension(300, 22)); associationTypePanel.setLayout(new java.awt.BorderLayout(15, 5)); associationTypeComboBox.setFont(new java.awt.Font("SansSerif", 1, 14)); associationTypeComboBox.setMaximumSize(new java.awt.Dimension(300, 22)); associationTypeComboBox.setMinimumSize(new java.awt.Dimension(300, 22)); associationTypeComboBox.setPreferredSize(new java.awt.Dimension(300, 22)); associationTypeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { associationTypeComboBoxActionPerformed(evt); } }); associationTypePanel.add(associationTypeComboBox, java.awt.BorderLayout.CENTER); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); associationPanel.add(associationTypePanel, gridBagConstraints); jSeparator1.setPreferredSize(new java.awt.Dimension(300, 1)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); associationPanel.add(jSeparator1, gridBagConstraints); thisPanel.setMaximumSize(new java.awt.Dimension(300, 45)); thisPanel.setMinimumSize(new java.awt.Dimension(300, 45)); thisPanel.setPreferredSize(new java.awt.Dimension(300, 45)); thisPanel.setLayout(new java.awt.GridBagLayout()); roleComboBox.setFont(new java.awt.Font("SansSerif", 0, 11)); roleComboBox.setMaximumSize(new java.awt.Dimension(300, 20)); roleComboBox.setMinimumSize(new java.awt.Dimension(300, 20)); roleComboBox.setPreferredSize(new java.awt.Dimension(300, 20)); roleComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { roleComboBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0); thisPanel.add(roleComboBox, gridBagConstraints); topicLabel.setText("Topic name"); topicLabel.setMaximumSize(new java.awt.Dimension(54, 20)); topicLabel.setMinimumSize(new java.awt.Dimension(54, 20)); topicLabel.setPreferredSize(new java.awt.Dimension(54, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; thisPanel.add(topicLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); associationPanel.add(thisPanel, gridBagConstraints); otherPanel.setMaximumSize(new java.awt.Dimension(500, 800)); otherPanel.setMinimumSize(new java.awt.Dimension(300, 50)); otherPanel.setPreferredSize(new java.awt.Dimension(300, 50)); otherPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 15, 15)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); associationPanel.add(otherPanel, gridBagConstraints); getContentPane().add(associationPanel, java.awt.BorderLayout.NORTH); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-472)/2, (screenSize.height-300)/2, 472, 300); }// </editor-fold>//GEN-END:initComponents private void applyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyButtonActionPerformed running=false; cancelled=false; synchronized(this){this.notifyAll();} try{ workerThread.join(); }catch(InterruptedException e){} if(!shouldCreate()) { WandoraOptionPane.showMessageDialog(this,"No association created as one or more fields were left empty!"); //System.out.println("No association created as one or more fields were empty!"); } else { try{ if(!createAssociation()) cancelled=true; }catch(TopicMapException tme){tme.printStackTrace();cancelled=true;} try { associationTypeBeforeAdd = associationType; topicRoleBeforeAdd = topicRole; parent.doRefresh(); workerThread=new Thread(this); running=true; workerThread.start(); } catch (Exception e) { e.printStackTrace(); } } }//GEN-LAST:event_applyButtonActionPerformed private Map<LayeredTopic,Collection<Topic>> resolveRoleMap(LayeredAssociation oldAssociation) throws TopicMapException { if(original==null) return null; Association selectedOriginal=((LayeredAssociation)original).findAssociationForSelectedLayer(); if(selectedOriginal==null) return null; HashMap<LayeredTopic,Collection<Topic>> newRoleMap=new HashMap<LayeredTopic,Collection<Topic>>(); for(Topic _role : oldAssociation.getRoles()){ LayeredTopic role=(LayeredTopic)_role; for(Topic selectedRole : selectedOriginal.getRoles()){ if(role.mergesWithTopic(selectedRole)){ Topic player=oldAssociation.getPlayer(role); Topic selectedPlayer=selectedOriginal.getPlayer(selectedRole); if(player.mergesWithTopic(selectedPlayer)){ Collection<Topic> c=newRoleMap.get(role); if(c==null){ c=new HashSet<Topic>(); newRoleMap.put(role,c); } c.add(selectedRole); } } } } return newRoleMap; } private void createAssociation2() throws TopicMapException { Association original2=((LayeredAssociation)original).findAssociationForSelectedLayer(); Collection<Topic> originalRoles=original2.getRoles(); HashMap<Topic,Topic> originalPlayers=new HashMap<Topic,Topic>(); for(Topic role : originalRoles){ // original players of the individual association originalPlayers.put(role,original2.getPlayer(role)); } TopicMap tm=((LayerStack)(original.getTopicMap())).getSelectedLayer().getTopicMap(); LayeredTopic type=(LayeredTopic)associationType; HashMap roleMap=new HashMap(); // this contains roles mapped to new players roleMap.putAll(this.roleMap); // players may be either TopicSelectLists, Strings roleMap.put(topicRole,topic); // or Topics // this maps roles of the LayeredAssociation to roles in the individual new Association Map<LayeredTopic,Collection<Topic>> newRoleMap=resolveRoleMap((LayeredAssociation)original); // fill in roles that are not inherited from the original association Iterator iter=roleMap.entrySet().iterator(); while(iter.hasNext()){ Map.Entry e=(Map.Entry)iter.next(); LayeredTopic role=(LayeredTopic)e.getKey(); if(newRoleMap.get(role)==null){ Topic t=role.getTopicForSelectedLayer(); if(t==null) t=role.copyStubTo(tm); Vector<Topic> v=new Vector<Topic>(); v.add(t); newRoleMap.put(role,v); } } original2.remove(); // collect used roles from the individual association here HashSet<Topic> usedRoles=new HashSet<Topic>(); Association a=null; if(type.getTopicsForSelectedLayer().contains(original2.getType())){ a=tm.createAssociation(original2.getType()); } else{ Topic st=type.getTopicForSelectedLayer(); if(st==null) st=type.copyStubTo(tm); a=tm.createAssociation(st); } iter=roleMap.entrySet().iterator(); while(iter.hasNext()){ Map.Entry e=(Map.Entry)iter.next(); LayeredTopic role=(LayeredTopic)e.getKey(); Collection<Topic> selectedRoles=newRoleMap.get(role); Topic newPlayer=null; Object o=null; if(e.getValue() instanceof Topic) o=e.getValue(); else{ TopicSelectList cbox=(TopicSelectList)e.getValue(); o=cbox.getSelection(); } if(o instanceof Topic){ LayeredTopic player=(LayeredTopic)o; Collection<Topic> sp=player.getTopicsForSelectedLayer(); for(Topic selectedRole : selectedRoles){ Topic originalPlayer=originalPlayers.get(selectedRole); if(originalPlayer!=null && player.getTopicsForSelectedLayer().contains(originalPlayer)){ newPlayer=originalPlayer; break; } } if(newPlayer==null){ newPlayer=player.getTopicForSelectedLayer(); if(newPlayer==null) newPlayer=player.copyStubTo(tm); } } else{ String baseName = o.toString(); if(baseName == null || baseName.length() == 0) baseName="(empty topic)"; Topic layeredPlayer=original.getTopicMap().getTopicWithBaseName(baseName); if(layeredPlayer==null){ layeredPlayer=original.getTopicMap().createTopic(); layeredPlayer.setBaseName(baseName); } if(layeredPlayer.getSubjectIdentifiers().isEmpty()) layeredPlayer.addSubjectIdentifier(original.getTopicMap().makeSubjectIndicatorAsLocator()); newPlayer=((LayeredTopic)layeredPlayer).getTopicForSelectedLayer(); } for(Topic selectedRole : selectedRoles){ usedRoles.add(selectedRole); Topic roleClass=SchemaBox.getRoleClass(selectedRole); if(!SchemaBox.isInstanceOf(newPlayer,selectedRole)) newPlayer.addType(roleClass); a.addPlayer(newPlayer,selectedRole); } } // if original association contains roles that haven't been used yet and // that merge with some (layered)role of the new association, add old players // for them for(Map.Entry<Topic,Topic> e : originalPlayers.entrySet()){ if(!usedRoles.contains(e.getKey())){ iter=roleMap.entrySet().iterator(); while(iter.hasNext()){ Map.Entry e2=(Map.Entry)iter.next(); LayeredTopic role=(LayeredTopic)e2.getKey(); if(role.mergesWithTopic(e.getKey())){ usedRoles.add(e.getKey()); a.addPlayer(e.getValue(),e.getKey()); break; } } } } } private boolean createAssociation() throws TopicMapException { if(shouldCreate()) { if(original!=null && original instanceof LayeredAssociation){ if( ((LayeredAssociation)original).findAssociationForSelectedLayer()!=null ){ createAssociation2(); return true; } } if(original!=null) { original.remove(); original = null; } TopicMap tm=topic.getTopicMap(); Association a=tm.createAssociation(associationType); Topic roleClass=SchemaBox.getRoleClass(topicRole); if(!SchemaBox.isInstanceOf(topic,roleClass)) topic.addType(roleClass); a.addPlayer(topic,topicRole); Iterator iter=roleMap.entrySet().iterator(); while(iter.hasNext()){ Map.Entry e=(Map.Entry)iter.next(); // Topic role=(Topic)e.getKey(); Topic role=tm.getMergingTopics((Topic)e.getKey()).iterator().next(); TopicSelectList cbox=(TopicSelectList)e.getValue(); Object o=cbox.getSelection(); if(o instanceof Topic){ // Topic player=(Topic)o; Topic player=tm.getMergingTopics((Topic)o).iterator().next(); roleClass=SchemaBox.getRoleClass(role); if(!SchemaBox.isInstanceOf(player,roleClass)) player.addType(roleClass); a.addPlayer(player,role); } else { String baseName = o.toString(); if(baseName == null || baseName.length() == 0) baseName="(empty topic)"; Topic player=tm.getTopicWithBaseName(baseName); if(player==null){ player=tm.createTopic(); player.setBaseName(baseName); } if(player.getSubjectIdentifiers().isEmpty()) player.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); roleClass=SchemaBox.getRoleClass(role); if(!SchemaBox.isInstanceOf(player,roleClass)) player.addType(roleClass); a.addPlayer(player,role); } } } return true; } private boolean shouldCreate() { boolean shouldCreate = true; Iterator iter=roleMap.entrySet().iterator(); while(iter.hasNext()) { try { Map.Entry e=(Map.Entry)iter.next(); TopicSelectList cbox=(TopicSelectList)e.getValue(); Object o=cbox.getSelection(); if(! (o instanceof Topic)) { String baseName = o.toString(); if(baseName == null || baseName.length() == 0) { shouldCreate = false; } } } catch (Exception e) { e.printStackTrace(); shouldCreate = false; } } return shouldCreate; } public boolean wasCancelled(){ return cancelled; } private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed running=false; cancelled=false; synchronized(this){this.notifyAll();} try{ workerThread.join(); }catch(InterruptedException e){} if(!shouldCreate() && associationTypeBeforeAdd == null) { WandoraOptionPane.showMessageDialog(this,"No association created as one or more fields were left empty!"); System.out.print("No association created as one or more fields were empty!"); } else { try{ if(!createAssociation()) cancelled=true; }catch(TopicMapException tme){tme.printStackTrace();cancelled=true;} } this.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed cancelled=true; running=false; synchronized(this){this.notifyAll();} try{ workerThread.join(); }catch(InterruptedException e){} this.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void roleComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_roleComboBoxActionPerformed okButton.setEnabled(false); applyButton.setEnabled(false); synchronized(this){ newRole=roleComboBox.getSelectedItem(); this.notifyAll(); } }//GEN-LAST:event_roleComboBoxActionPerformed private void associationTypeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_associationTypeComboBoxActionPerformed okButton.setEnabled(false); applyButton.setEnabled(false); synchronized(this){ newAssociationType=associationTypeComboBox.getSelectedItem(); this.notifyAll(); } }//GEN-LAST:event_associationTypeComboBoxActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton applyButton; private javax.swing.JPanel associationPanel; private javax.swing.JComboBox associationTypeComboBox; private javax.swing.JPanel associationTypePanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JSeparator jSeparator1; private javax.swing.JButton okButton; private javax.swing.JPanel otherPanel; private javax.swing.JComboBox roleComboBox; private javax.swing.JPanel thisPanel; private javax.swing.JLabel topicLabel; // End of variables declaration//GEN-END:variables public void run(){ Collection atypes=null; try{ topic.getTopicMap().getTopicsOfType(TMBox.ASSOCIATIONTYPE_SI); atypes=SchemaBox.getAssociationTypesFor(topic); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION return; } atypes=TMBox.sortTopics(atypes,null); associationTypeComboBox.removeAllItems(); { Iterator iter=atypes.iterator(); ComboBoxTopicWrapper select=null; while(iter.hasNext()){ Topic t=(Topic)iter.next(); ComboBoxTopicWrapper wrapper=new ComboBoxTopicWrapper(t); try{ if(original!=null && t.mergesWithTopic(original.getType())) select=wrapper; if(associationTypeBeforeAdd!=null && t.mergesWithTopic(associationTypeBeforeAdd)) select=wrapper; }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION; return; } associationTypeComboBox.addItem(wrapper); } if(select!=null) associationTypeComboBox.setSelectedItem(select); } Collection typeroles=null; while(running){ Object copiedAType=null; Object copiedRole=null; synchronized(this){ while(running && newAssociationType==null && newRole==null){ try{ this.wait(); }catch(InterruptedException e){ running=false; } } copiedAType=newAssociationType; copiedRole=newRole; newAssociationType=null; newRole=null; } if(!running) break; if(copiedAType!=null){ System.out.println("New association type"); Topic atype=((ComboBoxTopicWrapper)copiedAType).topic; associationType=atype; try{ typeroles=SchemaBox.getAssociationTypeRoles(atype); }catch(TopicMapException tme){tme.printStackTrace();typeroles=new Vector();} // TODO EXCEPTION typeroles=TMBox.sortTopics(typeroles,null); Collection possibleRoles=new HashSet(); System.out.println("found total of "+typeroles.size()+" roles for chosen association type"); Iterator iter=typeroles.iterator(); while(iter.hasNext()){ Topic role=(Topic)iter.next(); try{ Topic roleClass=SchemaBox.getRoleClass(role); if(SchemaBox.isInstanceOf(topic,roleClass)){ possibleRoles.add(role); } }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } } possibleRoles=TMBox.sortTopics(possibleRoles,null); Topic selectRole=null; if(!possibleRoles.isEmpty()){ selectRole=(Topic)possibleRoles.iterator().next(); } if(original!=null){ try{ Iterator iter2=original.getRoles().iterator(); while(iter2.hasNext()){ Topic role=(Topic)iter2.next(); Topic player=original.getPlayer(role); if(player.mergesWithTopic(topic)){ selectRole=role; break; } } }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } } System.out.println("found "+possibleRoles.size()+" possible roles for chosen topic"); roleComboBox.removeAllItems(); iter=typeroles.iterator(); // iter=possibleRoles.iterator(); ComboBoxTopicWrapper select=null; while(iter.hasNext()){ Topic t=(Topic)iter.next(); ComboBoxTopicWrapper wrapper=new ComboBoxTopicWrapper(t); try{ if(selectRole!=null && t != null && !t.isRemoved() && t.mergesWithTopic(selectRole)) select = wrapper; if(topicRoleBeforeAdd != null && topicRoleBeforeAdd.mergesWithTopic(t)) select = wrapper; }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } roleComboBox.addItem(wrapper); } if(select!=null) roleComboBox.setSelectedItem(select); } TopicSelectList focusFirstHere = null; if(copiedRole!=null){ System.out.println("New role"); otherPanel.removeAll(); otherPanel.setLayout(new java.awt.GridBagLayout()); Topic trole=((ComboBoxTopicWrapper)copiedRole).topic; topicRole=trole; roleMap=new HashMap(); Iterator iter=typeroles.iterator(); int counter=0; while(iter.hasNext()){ Topic role=(Topic)iter.next(); if(role==trole) continue; java.awt.GridBagConstraints gbc=new java.awt.GridBagConstraints(); gbc.gridx=counter; gbc.gridy=0; gbc.fill=gbc.HORIZONTAL; gbc.weightx=1.0; String name=""; try{ name=role.getBaseName(); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION name="Exception retrieving name"; } javax.swing.JLabel label=new SimpleLabel(name); label.setFont(UIConstants.smallButtonLabelFont); label.setPreferredSize(new Dimension(300, 23)); label.setAlignmentX(label.LEFT_ALIGNMENT); otherPanel.add(label,gbc); gbc=new java.awt.GridBagConstraints(); gbc.gridx=counter; gbc.gridy=1; gbc.fill=gbc.HORIZONTAL; gbc.weightx=1.0; // javax.swing.JComboBox cbox=new javax.swing.JComboBox(); Collection insts=null; try{ insts=SchemaBox.getInstancesOf(SchemaBox.getRoleClass(role)); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION insts=new Vector(); } insts=TMBox.sortTopics(insts,null); TopicSelectList cbox=new TopicSelectList(insts,true,this); focusFirstHere = cbox; if(original!=null){ try{ Topic player=original.getPlayer(role); if(player!=null) cbox.setText(player.getBaseName()); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } } // System.out.println("Found "+insts.size()+" instances of topic "+role.getBaseName()); /* Iterator iter2=insts.iterator(); while(iter2.hasNext()){ Topic inst=(Topic)iter2.next(); cbox.addItem(new ComboBoxTopicWrapper(inst)); }*/ roleMap.put(role,cbox); otherPanel.add(cbox,gbc); counter++; } okButton.setEnabled(true); applyButton.setEnabled(true); } this.validate(); this.repaint(); if(focusFirstHere != null) focusFirstHere.requestFocusOnField(); } } }
33,623
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolSelector.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/WandoraToolSelector.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * * WandoraToolSelector.java * * Created on 23. helmikuuta 2009, 17:46 */ package org.wandora.application.gui; import java.awt.BorderLayout; import java.util.ArrayList; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; /** * * @author akivela */ public class WandoraToolSelector extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private Wandora wandora = null; private boolean selectToolAccepted = false; private WandoraToolTable toolTable = null; /** Creates new form WandoraToolSelector */ public WandoraToolSelector(Wandora wandora) { super(wandora, true); this.wandora = wandora; initComponents(); ArrayList<WandoraTool> allTools = wandora.getToolManager().getAllTools(); toolTable = new WandoraToolTable(wandora); toolTable.initialize(allTools.toArray( new WandoraTool[] {} )); selectToolAccepted = false; toolSelectTablePanel.removeAll(); toolSelectTablePanel.add(toolTable, BorderLayout.NORTH); toolSelectScrollPane.setColumnHeaderView(toolTable.getTableHeader()); // toolSelectTitlePanel.add(toolTable.getTableHeader(), BorderLayout.CENTER); this.setSize(700, 350); wandora.centerWindow(this); this.setVisible(true); } public boolean selectToolAccepted() { return selectToolAccepted; } public WandoraTool getSelectedTool() { if(selectToolAccepted() && toolTable != null) { return toolTable.getSelectedTool(); } return null; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; toolSelectPanel = new javax.swing.JPanel(); toolSelectLabel = new org.wandora.application.gui.simple.SimpleLabel(); toolSelectTitlePanel = new javax.swing.JPanel(); toolSelectScrollPane = new org.wandora.application.gui.simple.SimpleScrollPane(); toolSelectTablePanel = new javax.swing.JPanel(); toolSelectButtonPanel = new javax.swing.JPanel(); toolSelectFillerPanel = new javax.swing.JPanel(); toolSelectButton = new org.wandora.application.gui.simple.SimpleButton(); toolSelectCancelButton = new org.wandora.application.gui.simple.SimpleButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Tool Selector"); toolSelectPanel.setLayout(new java.awt.GridBagLayout()); toolSelectLabel.setText("Select tool and click Select"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); toolSelectPanel.add(toolSelectLabel, gridBagConstraints); toolSelectTitlePanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5); toolSelectPanel.add(toolSelectTitlePanel, gridBagConstraints); toolSelectTablePanel.setLayout(new java.awt.BorderLayout()); toolSelectScrollPane.setViewportView(toolSelectTablePanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5); toolSelectPanel.add(toolSelectScrollPane, gridBagConstraints); toolSelectButtonPanel.setLayout(new java.awt.GridBagLayout()); javax.swing.GroupLayout toolSelectFillerPanelLayout = new javax.swing.GroupLayout(toolSelectFillerPanel); toolSelectFillerPanel.setLayout(toolSelectFillerPanelLayout); toolSelectFillerPanelLayout.setHorizontalGroup( toolSelectFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); toolSelectFillerPanelLayout.setVerticalGroup( toolSelectFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; toolSelectButtonPanel.add(toolSelectFillerPanel, gridBagConstraints); toolSelectButton.setText("Select"); toolSelectButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); toolSelectButton.setMaximumSize(new java.awt.Dimension(70, 23)); toolSelectButton.setMinimumSize(new java.awt.Dimension(70, 23)); toolSelectButton.setPreferredSize(new java.awt.Dimension(70, 23)); toolSelectButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { toolSelectButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); toolSelectButtonPanel.add(toolSelectButton, gridBagConstraints); toolSelectCancelButton.setText("Cancel"); toolSelectCancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); toolSelectCancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); toolSelectCancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); toolSelectCancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); toolSelectCancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { toolSelectCancelButtonActionPerformed(evt); } }); toolSelectButtonPanel.add(toolSelectCancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5); toolSelectPanel.add(toolSelectButtonPanel, gridBagConstraints); getContentPane().add(toolSelectPanel, java.awt.BorderLayout.CENTER); pack(); }// </editor-fold>//GEN-END:initComponents private void toolSelectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toolSelectButtonActionPerformed this.selectToolAccepted = true; this.setVisible(false); }//GEN-LAST:event_toolSelectButtonActionPerformed private void toolSelectCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toolSelectCancelButtonActionPerformed this.selectToolAccepted = false; this.setVisible(false); }//GEN-LAST:event_toolSelectCancelButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton toolSelectButton; private javax.swing.JPanel toolSelectButtonPanel; private javax.swing.JButton toolSelectCancelButton; private javax.swing.JPanel toolSelectFillerPanel; private javax.swing.JLabel toolSelectLabel; private javax.swing.JPanel toolSelectPanel; private javax.swing.JScrollPane toolSelectScrollPane; private javax.swing.JPanel toolSelectTablePanel; private javax.swing.JPanel toolSelectTitlePanel; // End of variables declaration//GEN-END:variables }
9,114
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SchemaOccurrencePrompt.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/SchemaOccurrencePrompt.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SchemaOccurrencePrompt.java * * Created on August 16, 2004, 10:39 AM */ package org.wandora.application.gui; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleComboBox; import org.wandora.topicmap.SchemaBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * @deprecated * * @author olli */ public class SchemaOccurrencePrompt extends javax.swing.JDialog { private Topic topic; private Wandora parent; private boolean cancelled; private ResourceEditor editor; /** Creates new form SchemaOccurrencePrompt */ public SchemaOccurrencePrompt(Wandora parent, boolean modal,Topic topic) { super(parent, modal); this.parent=parent; this.topic=topic; initComponents(); typeComboBox.setEditable(false); try{ Iterator iter=SchemaBox.getOccurrenceTypesFor(topic).iterator(); while(iter.hasNext()){ Topic t=(Topic)iter.next(); typeComboBox.addItem(new ComboBoxTopicWrapper(t)); } }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } this.cancelled=true; parent.centerWindow(this); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; typeComboBox = new SimpleComboBox(); dataPanel = new javax.swing.JPanel(); buttonPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); getContentPane().setLayout(new java.awt.GridBagLayout()); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Occurrence Editor"); typeComboBox.setMinimumSize(new java.awt.Dimension(50, 20)); typeComboBox.setPreferredSize(new java.awt.Dimension(200, 20)); typeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { typeComboBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); getContentPane().add(typeComboBox, gridBagConstraints); dataPanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 9); getContentPane().add(dataPanel, gridBagConstraints); okButton.setText("OK"); okButton.setMaximumSize(new java.awt.Dimension(70, 23)); okButton.setMinimumSize(new java.awt.Dimension(70, 23)); okButton.setPreferredSize(new java.awt.Dimension(70, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); buttonPanel.add(okButton); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 7, 2, 7)); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 10, 5, 5); getContentPane().add(buttonPanel, gridBagConstraints); setBounds(0, 0, 603, 227); }// </editor-fold>//GEN-END:initComponents private void typeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeComboBoxActionPerformed try{ makeDataPanel(); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } }//GEN-LAST:event_typeComboBoxActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed cancelled=false; try{ makeOccurrence(); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } this.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed cancelled=true; this.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void makeOccurrence() throws TopicMapException { if(editor!=null) { editor.applyChanges(topic, parent); } else cancelled=true; } public boolean wasCancelled(){ return cancelled; } private void makeDataPanel() throws TopicMapException { Topic t=((ComboBoxTopicWrapper)typeComboBox.getSelectedItem()).topic; editor=new OccurrencePanel(); editor.initializeOccurrence(topic,t,parent); dataPanel.removeAll(); dataPanel.add(editor,java.awt.BorderLayout.CENTER); dataPanel.validate(); this.repaint(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel dataPanel; private javax.swing.JButton okButton; private javax.swing.JComboBox typeComboBox; // End of variables declaration//GEN-END:variables }
7,520
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicEditorPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/TopicEditorPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicEditorPanel.java * * Created on 31.7.2006, 11:41 * */ package org.wandora.application.gui; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Rectangle; import javax.swing.Scrollable; import javax.swing.SwingConstants; import org.wandora.application.Wandora; /** * * @author olli */ public class TopicEditorPanel extends EditorPanel implements Scrollable { private static final long serialVersionUID = 1L; /** Creates a new instance of TopicEditorPanel */ public TopicEditorPanel(Wandora wandora, Object dc) { super(wandora,dc); } /** Creates a new instance of EditorPanel */ public TopicEditorPanel(Wandora wandora, int o, Object dc) { super(wandora,o,dc); } @Override public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 10; } @Override public boolean getScrollableTracksViewportWidth() { if(this.getComponentCount()>0){ Component co=this.getComponent(0); if(co!=null && co instanceof Scrollable) return ((Scrollable)co).getScrollableTracksViewportWidth(); } Container c=this.getParent(); if(c==null) return true; if(c.getWidth()>500) return true; else return false; } @Override public boolean getScrollableTracksViewportHeight() { if(this.getComponentCount()==0) return false; Component c=this.getComponent(0); if(c==null) return false; if(c instanceof Scrollable) return ((Scrollable)c).getScrollableTracksViewportHeight(); if(c==parent.getStartupPanel()) return true; else return false; } @Override public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { if(orientation==SwingConstants.VERTICAL) return visibleRect.height; else return visibleRect.width; } @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } }
2,907
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DropExtractPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/DropExtractPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * DropExtractPanel.java * * Created on 8.6.2006, 15:25 */ package org.wandora.application.gui; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseListener; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.WandoraToolLogger; import org.wandora.application.WandoraToolSet; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.application.gui.simple.SimpleTextPane; import org.wandora.application.tools.DropExtractor; import org.wandora.application.tools.extractors.AbstractExtractor; /** * * @author akivela */ public class DropExtractPanel extends JPanel implements ComponentListener, ActionListener, MouseListener, DropTargetListener, DragGestureListener, WandoraToolLogger { private static final long serialVersionUID = 1L; private Wandora wandora = null; private WandoraTool tool = null; private DropTarget dt; private JPopupMenu popup = null; private WandoraToolSet extractTools = null; private Color mouseOverColor = new Color(0,0,0); private Color mouseOutColor = new Color(102,102,102); private boolean forceStop = false; /** Creates new form DropExtractPanel */ public DropExtractPanel() { this.wandora = Wandora.getWandora(); initComponents(); extractorPanel.addMouseListener(this); addComponentListener(this); updateMenu(); dt = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this); String toolName = wandora.options.get("dropExtractor.currentTool"); if(toolName == null) { toolName = "Simple File Extractor"; } if(toolName != null) { setTool(toolName); } try { tabbedPane.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // System.out.println("Tab: " + tabbedPane.getSelectedIndex()); setCurrentPanel(tabbedPane.getSelectedComponent()); } }); setCurrentPanel(extractorPanel); } catch(Exception e) { e.printStackTrace(); } } private void setCurrentPanel(Component p) { if(p != null) { if(p.equals(extractorPanel)) { logTextPane.setText(""); } else if(p.equals(loggerPanel)) { logTextPane.setText(log.toString()); } this.revalidate(); } } public void setTool(String toolName) { forceStop = false; WandoraTool t = extractTools.getToolForName(toolName); if(t == null) t = extractTools.getToolForRealName(toolName); if(t != null) { setTool(t, toolName); } else { extractorNameLabel.setText("No tool available"); } } public void setTool(WandoraTool tool, String toolName) { forceStop = false; this.tool = tool; if(tool != null) { extractorNameLabel.setText(toolName); //extractorNameLabel.setToolTipText(Textbox.makeHTMLParagraph(tool.getDescription(), 40)); } wandora.options.put("dropExtractor.currentTool", toolName); } public void updateMenu() { this.setComponentPopupMenu(getPopupMenu()); } public JPopupMenu getPopupMenu() { extractTools = wandora.toolManager.getToolSet("extract"); Object[] menuItems = getPopupMenu(extractTools); popup = UIBox.makePopupMenu(menuItems, this); return popup; } public Object[] getPopupMenu(WandoraToolSet tools) { final ActionListener popupListener = this; return tools.getAsObjectArray( tools.new ToolFilter() { @Override public boolean acceptTool(WandoraTool tool) { return (tool instanceof DropExtractor); } @Override public Object[] addAfterTool(WandoraTool tool) { return new Object[] { tool.getIcon(), popupListener }; } } ); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; tabbedPane = new SimpleTabbedPane(); extractorPanel = new javax.swing.JPanel(); centeringPanel = new javax.swing.JPanel(); extractorNameLabel = new javax.swing.JLabel(); iconLabel = new javax.swing.JLabel(); infoPanel = new javax.swing.JPanel(); infoLabel = new javax.swing.JLabel(); loggerPanel = new javax.swing.JPanel(); jScrollPane1 = new SimpleScrollPane(); logTextPane = new SimpleTextPane(); setLayout(new java.awt.GridBagLayout()); extractorPanel.setBackground(new java.awt.Color(255, 255, 255)); extractorPanel.setLayout(new java.awt.GridBagLayout()); centeringPanel.setBackground(new java.awt.Color(255, 255, 255)); centeringPanel.setLayout(new java.awt.GridBagLayout()); extractorNameLabel.setFont(new java.awt.Font("SansSerif", 0, 14)); // NOI18N extractorNameLabel.setForeground(new java.awt.Color(102, 102, 102)); extractorNameLabel.setText("No extractor selected"); centeringPanel.add(extractorNameLabel, new java.awt.GridBagConstraints()); iconLabel.setIcon(org.wandora.application.gui.UIBox.getIcon("gui/drop_extract.gif")); centeringPanel.add(iconLabel, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; extractorPanel.add(centeringPanel, gridBagConstraints); infoPanel.setBackground(new java.awt.Color(255, 255, 255)); infoPanel.setLayout(new java.awt.GridBagLayout()); infoLabel.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N infoLabel.setForeground(new java.awt.Color(102, 102, 102)); infoLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); infoLabel.setText("<html><p align=\"center\">Drop extractor applies selected \nextractor to dropped files/text. First, select \nextractor in the popup menu. Then, drop a file/text here to start \nextraction.</p></html>\n"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); infoPanel.add(infoLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; extractorPanel.add(infoPanel, gridBagConstraints); tabbedPane.addTab("Extract", extractorPanel); loggerPanel.setLayout(new java.awt.GridBagLayout()); logTextPane.setBorder(null); logTextPane.setFont(new java.awt.Font("Monospaced", 0, 11)); // NOI18N logTextPane.setFocusable(false); jScrollPane1.setViewportView(logTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; loggerPanel.add(jScrollPane1, gridBagConstraints); tabbedPane.addTab("Log", loggerPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(tabbedPane, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel centeringPanel; private javax.swing.JLabel extractorNameLabel; private javax.swing.JPanel extractorPanel; private javax.swing.JLabel iconLabel; private javax.swing.JLabel infoLabel; private javax.swing.JPanel infoPanel; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextPane logTextPane; private javax.swing.JPanel loggerPanel; private javax.swing.JTabbedPane tabbedPane; // End of variables declaration//GEN-END:variables @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String toolName = actionEvent.getActionCommand(); System.out.println("action performed in Drop extract panel"); setTool(toolName); } // ------------------------------------------------------------- mouse ----- @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { if(popup != null && !popup.isVisible()) { popup.show(this, mouseEvent.getX(), mouseEvent.getY()); } } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { if(popup != null && !popup.isVisible()) { popup.show(this, mouseEvent.getX(), mouseEvent.getY()); } } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { } // --------------------------------------------------------------- dnd ----- @Override public void dragEnter(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { extractorNameLabel.setForeground(mouseOverColor); iconLabel.setIcon(UIBox.getIcon("gui/drop_extract_on.gif")); this.revalidate(); } @Override public void dragExit(java.awt.dnd.DropTargetEvent dropTargetEvent) { extractorNameLabel.setForeground(mouseOutColor); iconLabel.setIcon(UIBox.getIcon("gui/drop_extract.gif")); this.revalidate(); } @Override public void dragOver(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { } private void setLogger(WandoraTool tool) { tool.setToolLogger(this); } @Override public void drop(final java.awt.dnd.DropTargetDropEvent e) { try { final DropExtractPanel dropExtractPanel = this; DataFlavor fileListFlavor = DataFlavor.javaFileListFlavor; DataFlavor stringFlavor = DataFlavor.stringFlavor; DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String"); DataFlavor htmlFlavor = new DataFlavor("text/html; class=java.lang.String"); e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); Transferable tr = e.getTransferable(); java.util.List<File> fileListTransfer = null; if(tr.isDataFlavorSupported(fileListFlavor)) { fileListTransfer = (java.util.List<File>) tr.getTransferData(fileListFlavor); } final java.util.List<File> files = fileListTransfer; Collection<URI> uriListTransfer = null; if(tr.isDataFlavorSupported(uriListFlavor)) { String urisString = (String) tr.getTransferData(uriListFlavor); uriListTransfer = getURIs(urisString); } final Collection<URI> uris = uriListTransfer; String stringTransfer = null; if(tr.isDataFlavorSupported(stringFlavor)) { stringTransfer = (String) tr.getTransferData(stringFlavor); } final String string = stringTransfer; String htmlTransfer = null; if(tr.isDataFlavorSupported(htmlFlavor)) { htmlTransfer = (String) tr.getTransferData(htmlFlavor); } final String html = htmlTransfer; byte[] dataTransfer = null; if(tool instanceof AbstractExtractor) { AbstractExtractor atool = (AbstractExtractor) tool; String[] contentTypes = atool.getContentTypes(); for(String contentType : contentTypes) { DataFlavor contentTypeFlavor = new DataFlavor(contentType+"; class=java.lang.String"); if(tr.isDataFlavorSupported(contentTypeFlavor)) { dataTransfer = (byte[]) tr.getTransferData(contentTypeFlavor); break; } } } final byte[] data = dataTransfer; /** * Actual drop extraction is handled in a separate thread. Thread * is required because drop-thread can't use blocking swing * dialogs properly (in single-thread systems). */ Thread dropThread = new Thread() { public void run() { try { if(tool != null) { setLogger(tool); if(tool instanceof DropExtractor) { System.out.println("Drop!"); DropExtractor dropTool = (DropExtractor) tool; forceStop = false; if(files != null) { dropTool.dropExtract(files.toArray(new File[files.size()])); } else if(uris != null) { Collection<File> fileURIs = substractFileURIs(uris); if(fileURIs != null) { dropTool.dropExtract(files.toArray(new File[files.size()])); } dropTool.dropExtract(getURIStrings(uris).toArray(new String[uris.size()])); } else if(data != null) { // dropTool.dropExtract(data); } else if(html != null) { dropTool.dropExtract(html); } else if(string != null) { dropTool.dropExtract(string); } } else { WandoraOptionPane.showMessageDialog(wandora, "Selected tool does not support drag and drop feature!", "Drag'n'drop not supported", WandoraOptionPane.WARNING_MESSAGE); } } else { WandoraOptionPane.showMessageDialog(wandora, "No extractor selected. Can't extract. Select extractor first.", "No extractor selected", WandoraOptionPane.WARNING_MESSAGE); } } catch(Exception ex) { ex.printStackTrace(); } catch(Error err) { err.printStackTrace(); } extractorNameLabel.setForeground(mouseOutColor); iconLabel.setIcon(UIBox.getIcon("gui/drop_extract.gif")); dropExtractPanel.revalidate(); } }; dropThread.start(); e.dropComplete(true); } catch(IOException ioe) { ioe.printStackTrace(); } catch(UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } catch(Error err) { err.printStackTrace(); } } @Override public void dropActionChanged(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { } @Override public void dragGestureRecognized(java.awt.dnd.DragGestureEvent dragGestureEvent) { } public Collection<URI> getURIs(String urisString) { String[] split = urisString.split("\n"); Collection<URI> uris = new ArrayList<URI>(); for (String splitPart : split) { try { URI u = new URI(splitPart.trim()); if(u.getScheme()==null) continue; uris.add(u); } catch(java.net.URISyntaxException ue) {} } return uris; } public Collection<String> getURIStrings(Collection<URI> uris) { if(uris == null) return null; Collection<String> uriStrings = new ArrayList<String>(); for(URI uri : uris) { try { uriStrings.add(uri.toURL().toExternalForm()); } catch(Exception e) {} } return uriStrings; } public Collection<File> substractFileURIs(Collection<URI> uris) { if(uris == null) return null; Collection<File> files = new ArrayList<>(); Collection<URI> urisCopy = new ArrayList<>(); urisCopy.addAll(uris); for(URI uri : urisCopy) { try { if("file".equals(uri.getScheme())) { files.add(new File(uri.toURL().getFile())); uris.remove(uri); } } catch(Exception e) {} } return files.isEmpty() ? null : files; } // --------------------------------------------------------- tool logger --- // DropExtractorPanel overrides logger in used tool as the default logger // usually popups annoying messages that we don't want to show the user // during drop aextraction. private StringBuilder log = new StringBuilder(""); @Override public void hlog(String message) { dolog(message); } @Override public void log(String message) { dolog(message); } @Override public void log(String message, Exception e) { dolog(message); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); dolog(sw.getBuffer().toString()); } @Override public void log(Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); dolog(sw.getBuffer().toString()); } @Override public void log(Error e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); dolog(sw.getBuffer().toString()); } @Override public void setProgress(int n) { } @Override public void setProgressMax(int maxn) { } @Override public void setLogTitle(String title) { } @Override public void lockLog(boolean lock) { } @Override public String getHistory() { return ""; } @Override public void setState(int state) { } @Override public int getState() { return WandoraToolLogger.EXECUTE; } @Override public boolean forceStop() { return forceStop; } private void dolog(String str) { if(str.length() > 50000) { str = str.substring(str.indexOf('\n')); } log.append("\n").append(str); } // ------------------------------------------------------------------------- @Override public void componentResized(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentHidden(ComponentEvent e) { } public void handleComponentEvent(ComponentEvent e) { try { Dimension size = getSize(); Component c = this.getParent().getParent().getParent(); if(c != null) { if(!(c instanceof JScrollPane)) { size = c.getSize(); } if(!size.equals(getSize())) { //System.out.println("new size treemapcomponent: "+size); setPreferredSize(size); setMinimumSize(size); setSize(size); } } revalidate(); repaint(); } catch(Exception ex) { // SKIP } } }
23,974
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
NewTopicMapPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/NewTopicMapPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * NewTopicMapPanel.java * * Created on 21. marraskuuta 2005, 10:35 */ package org.wandora.application.gui; import java.awt.event.KeyEvent; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleField; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapConfigurationPanel; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapType; import org.wandora.utils.Delegate; import org.wandora.utils.Options; /** * * @author olli */ public class NewTopicMapPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private Wandora wandora; private Delegate<Object,NewTopicMapPanel> okDelegate; private Delegate<Object,NewTopicMapPanel> cancelDelegate; private TopicMapConfigurationPanel confPanel=null; private boolean acceptNamePropositions = true; /** Creates new form NewTopicMapPanel */ public NewTopicMapPanel(Wandora wandora,Delegate<Object,NewTopicMapPanel> okDelegate,Delegate<Object,NewTopicMapPanel> cancelDelegate) { this.wandora=wandora; this.okDelegate=okDelegate; this.cancelDelegate=cancelDelegate; initComponents(); typeComboBox.setEditable(false); Options options = wandora.getOptions(); if(options != null) { int i=0; while(options.get("layers.layer["+i+"]") != null) { String layerTypeClassName = options.get("layers.layer["+i+"]"); try { if(layerTypeClassName != null) { layerTypeClassName = layerTypeClassName.trim(); if(layerTypeClassName.length() > 0) { Class layerTypeClass = Class.forName(layerTypeClassName); if(layerTypeClass != null) { Object layerType = layerTypeClass.newInstance(); if(layerType instanceof TopicMapType) { typeComboBox.addItem(layerType); } } } } } catch(Exception e) { System.out.println("Warning: Can't create topic map layer type with class name '"+layerTypeClassName+"'."); e.printStackTrace(); } i++; } } if(okDelegate==null) okButton.setVisible(false); if(cancelDelegate==null) cancelButton.setVisible(false); //this.setName("NewTopicMapPanel"); } public String getName(){ return nameTextField.getText(); } public TopicMap createTopicMap() throws TopicMapException { TopicMapType type=(TopicMapType)typeComboBox.getSelectedItem(); Object params=confPanel.getParameters(); TopicMap tm=type.createTopicMap(params); return tm; } public void proposeName(String proposedName) { if(acceptNamePropositions) nameTextField.setText(proposedName); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; layerNameLabel = new org.wandora.application.gui.simple.SimpleLabel(); nameTextField = new SimpleField(); layerTypeLabel = new org.wandora.application.gui.simple.SimpleLabel(); typeComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); jSeparator1 = new javax.swing.JSeparator(); confContainerPanel = new javax.swing.JPanel(); jSeparator2 = new javax.swing.JSeparator(); buttonPanel = new javax.swing.JPanel(); okButton = new org.wandora.application.gui.simple.SimpleButton(); cancelButton = new org.wandora.application.gui.simple.SimpleButton(); setName("newLayerPanel"); // NOI18N setLayout(new java.awt.GridBagLayout()); layerNameLabel.setText("Name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(8, 7, 0, 5); add(layerNameLabel, gridBagConstraints); nameTextField.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { rejectNamePropositionsAfterEdit(evt); } }); nameTextField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { nameTextFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 5, 0, 7); add(nameTextField, gridBagConstraints); layerTypeLabel.setText("Type"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 7, 5, 5); add(layerTypeLabel, gridBagConstraints); typeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { typeComboBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 7); add(typeComboBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 7, 2, 7); add(jSeparator1, gridBagConstraints); confContainerPanel.setName("confPanel"); // NOI18N confContainerPanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(confContainerPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 7, 0, 7); add(jSeparator2, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridLayout(1, 0, 3, 0)); okButton.setText("OK"); okButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); okButton.setMaximumSize(new java.awt.Dimension(70, 23)); okButton.setMinimumSize(new java.awt.Dimension(70, 23)); okButton.setPreferredSize(new java.awt.Dimension(70, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); buttonPanel.add(okButton); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void rejectNamePropositionsAfterEdit(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_rejectNamePropositionsAfterEdit acceptNamePropositions = false; }//GEN-LAST:event_rejectNamePropositionsAfterEdit private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed cancelDelegate.invoke(this); }//GEN-LAST:event_cancelButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed okDelegate.invoke(this); }//GEN-LAST:event_okButtonActionPerformed private void typeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeComboBoxActionPerformed TopicMapType type=(TopicMapType)typeComboBox.getSelectedItem(); confContainerPanel.removeAll(); confPanel=type.getConfigurationPanel(wandora, wandora.getOptions()); confContainerPanel.add(confPanel); confContainerPanel.revalidate(); confContainerPanel.repaint(); }//GEN-LAST:event_typeComboBoxActionPerformed private void nameTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nameTextFieldKeyReleased if(evt.getKeyCode() == KeyEvent.VK_ENTER) { okButtonActionPerformed(null); } }//GEN-LAST:event_nameTextFieldKeyReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel confContainerPanel; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JLabel layerNameLabel; private javax.swing.JLabel layerTypeLabel; private javax.swing.JTextField nameTextField; private javax.swing.JButton okButton; private javax.swing.JComboBox typeComboBox; // End of variables declaration//GEN-END:variables }
12,228
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OccurrenceTableSingleType.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/OccurrenceTableSingleType.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * OccurrenceTableSingleType.java * * Created on August 17, 2004, 12:07 PM */ package org.wandora.application.gui; import static org.wandora.topicmap.TMBox.LANGUAGE_SI; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.Point; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.swing.AbstractCellEditor; import javax.swing.DropMode; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTable; import javax.swing.TransferHandler; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableRowSorter; import org.apache.commons.io.IOUtils; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.wandora.application.Wandora; import org.wandora.application.WandoraMenuManager; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleTable; import org.wandora.application.gui.simple.SimpleTextPane; import org.wandora.application.gui.texteditor.OccurrenceTextEditor; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import org.wandora.utils.IObox; import org.wandora.utils.MSOfficeBox; import org.wandora.utils.Options; import org.wandora.utils.Textbox; /** * * @author olli, akivela */ public class OccurrenceTableSingleType extends SimpleTable implements OccurrenceTable, MouseListener, Clipboardable { private static final long serialVersionUID = 1L; public String tableType = VIEW_SCHEMA; private Topic topic; private Topic[] langs; private Topic type; private String[] data; private Color[] colors; private TableRowSorter sorter; private Wandora wandora; private String[] originalData; private int defaultRowHeight = 0; private Object[] popupStruct; private MouseEvent mouseEvent; /** Creates a new instance of OccurrenceTableSingleType */ public OccurrenceTableSingleType(Topic topic, Topic type, Options options, Wandora wandora) throws TopicMapException { this.wandora=wandora; this.topic=topic; TopicMap tm = wandora.getTopicMap(); try { Options opts = options; if(opts == null) opts = wandora.getOptions(); if(opts != null) { tableType = opts.get(VIEW_OPTIONS_KEY); if(tableType == null || tableType.length() == 0) tableType = VIEW_SCHEMA; defaultRowHeight = opts.getInt(ROW_HEIGHT_OPTIONS_KEY); } } catch(Exception e) { e.printStackTrace(); } this.type = type; Set<Topic> langSet = new LinkedHashSet(); if(VIEW_USED.equalsIgnoreCase(tableType) || VIEW_USED_AND_SCHEMA.equalsIgnoreCase(tableType)) { Hashtable<Topic,String> occs = null; Topic langTopic = null; occs = topic.getData(type); for(Enumeration<Topic> keys = occs.keys(); keys.hasMoreElements(); ) { langTopic = keys.nextElement(); langSet.add(langTopic); } } if(VIEW_SCHEMA.equalsIgnoreCase(tableType) || VIEW_USED_AND_SCHEMA.equalsIgnoreCase(tableType)) { Collection<Topic> langTopics = tm.getTopicsOfType(LANGUAGE_SI); langSet.addAll( langTopics ); } langs=langSet.toArray( new Topic[langSet.size()] ); data=new String[langs.length]; originalData=new String[langs.length]; colors=new Color[langs.length]; for(int j=0;j<langs.length;j++){ if(langs[j] != null) { data[j]=topic.getData(type,langs[j]); if(data[j]==null) data[j]=""; originalData[j]=data[j]; colors[j]=wandora.topicHilights.getOccurrenceColor(topic,type,langs[j]); } } dataModel = new DataTableModel(); sorter = new TableRowSorter(dataModel); final TableCellRenderer oldRenderer=this.getTableHeader().getDefaultRenderer(); this.getTableHeader().setPreferredSize(new Dimension(100, 23)); this.getTableHeader().setDefaultRenderer(new TableCellRenderer(){ @Override public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus, int row, int column){ Component c=oldRenderer.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column); return c; } }); this.setAutoCreateColumnsFromModel(false); TableColumn column=new TableColumn(0,40,new TopicCellRenderer(),new TopicCellEditor()); this.addColumn(column); column = new TableColumn(1,400,new DataCellRenderer(),new DataCellEditor()); this.addColumn(column); this.setTableHeader(this.getTableHeader()); this.setModel(dataModel); this.setRowSorter(sorter); sorter.setSortsOnUpdates(true); updateRowHeights(); popupStruct = WandoraMenuManager.getOccurrenceTableMenu(this, options); JPopupMenu popup = UIBox.makePopupMenu(popupStruct, wandora); this.setComponentPopupMenu(popup); this.addMouseListener(this); this.setColumnSelectionAllowed(false); this.setRowSelectionAllowed(false); this.setDragEnabled(true); this.setTransferHandler(new OccurrencesTableTransferHandler()); this.setDropMode(DropMode.ON); this.createDefaultTableSelectionModel(); } protected void updateRowHeights() { for(int row=0; row<data.length; row++) { try { int rowHeight = 16; if(defaultRowHeight == 0) { Component comp = this.prepareRenderer(this.getCellRenderer(row, 1), row, 1); rowHeight = Math.min(2000, Math.max(rowHeight, comp.getPreferredSize().height)); } else { rowHeight = rowHeight * defaultRowHeight + 6; } setRowHeight(row, rowHeight+2); } catch(Exception e) { e.printStackTrace(); } } } @Override public boolean applyChanges(Topic t, Wandora parent) throws TopicMapException { boolean changed=false; for(int j=0; j<langs.length; j++){ String text=data[j]; if(text != null) { // String orig=topic.getData(types[i],langs[j]); String orig=originalData[j]; if(orig==null) orig=""; if(!orig.equals(text)) { changed=true; try { if(text.length()==0) { topic.removeData(type,langs[j]); } else { topic.setData(type, langs[j], text ); } } catch(Exception e) { wandora.handleError(e); } } } } return changed; } @Override public Topic getTopic() { return topic; } @Override public String getToolTipText(java.awt.event.MouseEvent e) { try { Object o = getValueAt(e); if(o != null) { String tooltipText = o.toString(); if(!DataURL.isDataURL(tooltipText)) { if(tooltipText != null && tooltipText.length() > 5) { if(tooltipText.length() > 200) tooltipText = tooltipText.substring(0,199)+"..."; return Textbox.makeHTMLParagraph(tooltipText, 40); } } } } catch(Exception ex) { // Sometimes swing throws index out of bounds exceptions if the table has not initialized yet. } return null; } @Override public int getRowHeightOption() { return defaultRowHeight; } @Override public Object getOccurrenceTableType() { return tableType; } @Override public String getPointedOccurrence() { try { Point p = getTableModelPoint(); if(p != null) { return topic.getData(type, langs[p.y]); } } catch(Exception e) { e.printStackTrace(); } return null; } @Override public Topic getPointedOccurrenceType() { return type; } @Override public Topic getPointedOccurrenceLang() { try { Point p = getTableModelPoint(); if(p != null) { return langs[p.y]; } } catch(Exception e) { e.printStackTrace(); } return null; } @Override public void cut() { try { copy(); Point p = getTableModelPoint(); if(p != null) { topic.removeData(type, langs[p.y]); } } catch(Exception e) { e.printStackTrace(); if(wandora != null) wandora.handleError(e); } } @Override public void paste() { try { Point p = getTableModelPoint(); if(p != null) { topic.setData(type, langs[p.y], ClipboardBox.getClipboard()); } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } @Override public void append() { try { Point p = getTableModelPoint(); if(p != null) { String oldOccurrence = topic.getData(type, langs[p.y]); if(oldOccurrence == null) oldOccurrence = ""; topic.setData(type, langs[p.y], oldOccurrence + ClipboardBox.getClipboard()); } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } @Override public void copy() { ClipboardBox.setClipboard(getCopyString()); } @Override public String getCopyString() { try { Point p = getTableModelPoint(); if(p != null) { return topic.getData(type, langs[p.y]); } } catch(Exception e) {} return ""; } @Override public void delete() { try { Point p = getTableModelPoint(); if(p != null) { topic.removeData(type, langs[p.y]); } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } @Override public void changeType() { try { Point p = getTableModelPoint(); if(p != null) { Topic selectedScope = langs[p.y]; if(type != null && !type.isRemoved()) { Topic newType = wandora.showTopicFinder("Select new occurrence type"); if(newType != null && !newType.isRemoved()) { Hashtable<Topic,String> os = topic.getData(type); if(os != null && !os.isEmpty()) { for(Topic scope : os.keySet()) { if(scope != null && !scope.isRemoved()) { if(selectedScope == null) { String occurrenceText = os.get(scope); topic.setData(newType, scope, occurrenceText); } else if(selectedScope.mergesWithTopic(scope)) { String occurrenceText = os.get(scope); topic.setData(newType, scope, occurrenceText); } } } if(selectedScope == null) { topic.removeData(type); } else { topic.removeData(type, selectedScope); } } } } } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } @Override public void duplicateType() { try { Point p = getTableModelPoint(); if(p != null) { Topic selectedScope = langs[p.y]; if(type != null && !type.isRemoved()) { Topic newType = wandora.showTopicFinder("Select new occurrence type"); if(newType != null && !newType.isRemoved()) { Hashtable<Topic,String> os = topic.getData(type); if(os != null && !os.isEmpty()) { for(Topic scope : os.keySet()) { if(scope != null && !scope.isRemoved()) { if(selectedScope == null) { String occurrenceText = os.get(scope); topic.setData(newType, scope, occurrenceText); } else if(selectedScope.mergesWithTopic(scope)) { String occurrenceText = os.get(scope); topic.setData(newType, scope, occurrenceText); } } } } } } } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } @Override public void openURLOccurrence() { try { String errorMessage = null; Point p = getTableModelPoint(); if(p != null) { String occurrence = topic.getData(type, langs[p.y]); if(occurrence != null) { occurrence = occurrence.trim(); if(occurrence.length() > 0) { try { if(!DataURL.isDataURL(occurrence)) { Desktop desktop = Desktop.getDesktop(); desktop.browse(new URI(occurrence)); } else { errorMessage = "Due to security restrictions Wandora can't open data-urls with desktop browser. "+ "Copy data-url to clipboard and paste it to browser's address field."; } } catch(IOException ioe) { errorMessage = "IOException occurred while starting external browser for occurrence: "+ioe.getMessage(); } catch(Exception e) { if(occurrence.length() > 80) occurrence = occurrence.substring(0, 80)+"..."; errorMessage = "Exception '"+e.getMessage()+"' occurred while starting external browser for occurrence. Check if the occurrence text is a valid URL."; e.printStackTrace(); } } } } if(errorMessage != null) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), errorMessage, "Error while opening URL"); } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } @Override public void downloadURLOccurrence() { try { Point p = getTableModelPoint(); if(p != null) { String occurrence = topic.getData(type, langs[p.y]); if(occurrence != null) { occurrence = occurrence.trim(); if(occurrence.length() > 0) { try { URL url = new URL(occurrence); int a = WandoraOptionPane.showConfirmDialog(wandora, "Make data-url instead of text occurrence?", "Make data-url", WandoraOptionPane.INFORMATION_MESSAGE); if(a == WandoraOptionPane.YES_OPTION) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("HEAD"); connection.connect(); String contentType = connection.getContentType(); connection.disconnect(); InputStream is = url.openStream(); byte[] dataBytes = IOUtils.toByteArray(is); DataURL dataURL = new DataURL(contentType, dataBytes); topic.setData(type, langs[p.y], dataURL.toExternalForm()); } else { String occurrenceContent = IObox.doUrl(url); topic.setData(type, langs[p.y], occurrenceContent); } } catch(MalformedURLException mue) { WandoraOptionPane.showMessageDialog(wandora, "The occurrence is invalid URL. Can't download.", "Invalid URL exception", WandoraOptionPane.ERROR_MESSAGE); } catch(IOException ioe) { WandoraOptionPane.showMessageDialog(wandora, "Can't read the occurrence URL. IOException occurred ('"+ioe.getMessage()+"').", "Can't read the URL", WandoraOptionPane.ERROR_MESSAGE); } catch(TopicMapException tme) { WandoraOptionPane.showMessageDialog(wandora, "Can't set the occurrence because of a topic map exception. Topic map doesn't function as intended", "Topic map exception occurred", WandoraOptionPane.ERROR_MESSAGE); } catch(Exception e) { WandoraOptionPane.showMessageDialog(wandora, "Exception '"+e.getMessage()+"' occurred while downloading URL '"+occurrence+"'.", "Error downloading URL", WandoraOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } } } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } @Override public void spread() { try { Point p = getTableModelPoint(); if(p != null) { boolean overrideAll = false; if(mouseEvent != null && mouseEvent.isAltDown()) overrideAll = true; String occurrenceText = topic.getData(type, langs[p.y]); for(int i=0; i<langs.length; i++) { if(i != p.y) { int override = WandoraOptionPane.YES_OPTION; if(!overrideAll && topic.getData(type, langs[i]) != null) { override = WandoraOptionPane.showConfirmDialog(wandora, "Override existing "+langs[i].getDisplayName()+" occurrence?", "Override existing occurrence?", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION); if(override == WandoraOptionPane.YES_TO_ALL_OPTION) overrideAll = true; if(override == WandoraOptionPane.CANCEL_OPTION) return; } if(override == WandoraOptionPane.YES_OPTION || override == WandoraOptionPane.YES_TO_ALL_OPTION) { topic.setData(type, langs[i], occurrenceText); } } } } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } // ------------------------------------------------------------------------- public Point getTableModelPoint(Point coords) { try { int col = columnAtPoint(coords); int row = rowAtPoint(coords); int modelCol = convertColumnIndexToModel(columnAtPoint(coords)); int modelRow = convertRowIndexToModel(rowAtPoint(coords)); System.out.println("getTableModelPoint: "+col+","+row+" -> "+modelCol+","+modelRow); return new Point(modelCol, modelRow); } catch(Exception ex) { return null; } } public Point getTableModelPoint(java.awt.event.MouseEvent event) { try { Point coords = event.getPoint(); return getTableModelPoint(coords); } catch(Exception ex) { return null; } } public Point getTableModelPoint() { return getTableModelPoint(mouseEvent); } public Point getTablePoint() { return getTablePoint(mouseEvent); } public Point getTablePoint(java.awt.event.MouseEvent e) { try { java.awt.Point p = e.getPoint(); int row = rowAtPoint(p); int col = columnAtPoint(p); return new Point(col, row); } catch (Exception ex) { wandora.handleError(ex); return null; } } public Object getValueAt(MouseEvent e) { return getValueAt(getTablePoint(e)); } public Object getValueAt(Point p) { return getValueAt(p.y, p.x); } @Override public Object getValueAt(int y, int x) { try { int cx = convertColumnIndexToModel(x); int cy = convertRowIndexToModel(y); return dataModel.getValueAt(cy, cx); } catch (Exception e) { e.printStackTrace(); } return null; } // ------------------------------------------------------------------------- @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; //System.out.println("Mouse clicked!"); } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class DataCellRenderer implements TableCellRenderer { private SimpleTextPane occurrenceTextField = null; private SimpleLabel occurrenceInfoLabel = null; private JPanel occurrencePanel = null; private Color noOccurrenceColor = UIConstants.noContentBackgroundColor; private Color occurrenceInfoTextColor = new Color(150,150,150); private Color dataOccurrenceColor = new Color(240,255,250); public DataCellRenderer() { occurrenceTextField = new SimpleTextPane(); occurrenceTextField.setOpaque(true); occurrenceTextField.setMargin(new Insets(0,0,0,0)); Font f = occurrenceTextField.getFont(); occurrenceTextField.setFont(new Font(f.getName(),Font.PLAIN,f.getSize())); occurrenceTextField.setBackground(Color.WHITE); occurrenceTextField.putClientProperty("html.disable", Boolean.TRUE); occurrenceTextField.setBorder(UIConstants.defaultTableCellLabelBorder); occurrenceInfoLabel = new SimpleLabel(); occurrenceInfoLabel.setOpaque(true); occurrenceInfoLabel.setBackground(Color.WHITE); occurrenceInfoLabel.setPreferredSize(new Dimension(60,16)); occurrenceInfoLabel.setAlignmentY(SimpleLabel.TOP_ALIGNMENT); occurrenceInfoLabel.setAlignmentX(SimpleLabel.RIGHT_ALIGNMENT); occurrenceInfoLabel.setHorizontalTextPosition(SimpleLabel.RIGHT); occurrenceInfoLabel.setHorizontalAlignment(SimpleLabel.RIGHT); occurrenceInfoLabel.setVerticalAlignment(SimpleLabel.TOP); occurrenceInfoLabel.setFocusable(false); BorderLayout layout = new BorderLayout(); occurrencePanel = new JPanel(); occurrencePanel.setLayout(layout); occurrencePanel.add(occurrenceTextField, BorderLayout.CENTER); occurrencePanel.add(occurrenceInfoLabel, BorderLayout.EAST); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if(value == null) value = ""; String occurrenceText = value.toString(); String viewedOccurrenceText = occurrenceText; boolean isDataOccurrence = false; if(DataURL.isDataURL(viewedOccurrenceText)) { try { Component preview = UIBox.getPreview(new DataURL(viewedOccurrenceText)); if(preview != null) { return preview; } } catch(MalformedURLException mue) { System.out.println("Warning: Malformed data-url found."); } catch(Exception e) { e.printStackTrace(); } isDataOccurrence = true; viewedOccurrenceText = viewedOccurrenceText.substring(0, Math.max(5, viewedOccurrenceText.indexOf(','))); } else { if(viewedOccurrenceText.length() > 9999) { viewedOccurrenceText = viewedOccurrenceText.substring(0, 9999)+"..."; } } occurrenceTextField.setText(viewedOccurrenceText); String occurrenceInfoText = (occurrenceText.length() > 0 ? " "+occurrenceText.length()+" " : ""); occurrenceInfoLabel.setText(occurrenceInfoText); Color c=colors[row]; if(c != null) { occurrenceTextField.setForeground(c); occurrenceInfoLabel.setForeground(occurrenceInfoTextColor); } else { occurrenceTextField.setForeground(Color.BLACK); occurrenceInfoLabel.setForeground(occurrenceInfoTextColor); } if(occurrenceText.length() == 0) { occurrenceTextField.setBackground(noOccurrenceColor); occurrenceInfoLabel.setBackground(noOccurrenceColor); } else if(isDataOccurrence) { occurrenceTextField.setBackground(dataOccurrenceColor); occurrenceInfoLabel.setBackground(dataOccurrenceColor); } else { occurrenceTextField.setBackground(Color.WHITE); occurrenceInfoLabel.setBackground(Color.WHITE); } return occurrencePanel; } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class DataCellEditor extends AbstractCellEditor implements TableCellEditor, java.awt.event.MouseListener { private static final long serialVersionUID = 1L; private Topic scope; private SimpleTextPane label; private String editedText; public DataCellEditor(){ label=new SimpleTextPane(); label.setMargin(new Insets(0,0,0,0)); Font f=label.getFont(); label.setFont(new Font(f.getName(),Font.PLAIN,f.getSize())); label.addMouseListener(this); label.putClientProperty("html.disable", Boolean.TRUE); label.setBorder(UIConstants.defaultTableCellLabelBorder); } @Override public Object getCellEditorValue() { return editedText; } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { if(value == null) value=""; String viewedOccurrenceText = value.toString(); if(viewedOccurrenceText.length() > 9999) { viewedOccurrenceText = viewedOccurrenceText.substring(0, 9999)+"..."; } label.setText(viewedOccurrenceText); editedText=value.toString(); return label; } @Override public void mouseReleased(java.awt.event.MouseEvent e) { Point p = getTableModelPoint(); if(p != null && label.contains(e.getPoint())) { OccurrenceTextEditor ed = new OccurrenceTextEditor(wandora, true, editedText, topic, type, scope); String typeName = TopicToString.toString(type); String topicName = TopicToString.toString(topic); String scopeName = TopicToString.toString(langs[p.y]); ed.setTitle("Edit occurrence text of '"+typeName+"' and '"+scopeName+"' attached to '"+topicName+"'"); ed.setVisible(true); if(ed.acceptChanges()) { if(ed.getText() != null) { editedText=ed.getText(); data[p.y]=editedText; } try { boolean changed = applyChanges(topic, wandora); if(changed) { wandora.doRefresh(); } } catch(Exception ex) { ex.printStackTrace(); } } } fireEditingStopped(); } @Override public void mouseClicked(java.awt.event.MouseEvent e) {} @Override public void mouseEntered(java.awt.event.MouseEvent e) {} @Override public void mouseExited(java.awt.event.MouseEvent e) {} @Override public void mousePressed(java.awt.event.MouseEvent e) {} } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class TopicCellRenderer implements TableCellRenderer { private JLabel label; public TopicCellRenderer(){ label=new JLabel(""); label.setOpaque(true); Font f=label.getFont(); label.setFont(new Font(f.getName(),Font.PLAIN,f.getSize())); label.setVerticalAlignment(JLabel.TOP); label.setBorder(UIConstants.defaultTableCellLabelBorder); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { int modelRow = convertRowIndexToModel(row); Topic scope = langs[modelRow]; label.setText(TopicToString.toString(scope)); Color c=wandora.topicHilights.get(scope); if(c==null) c=wandora.topicHilights.getLayerColor(scope); if(c!=null) label.setForeground(c); else label.setForeground(Color.BLACK); if(column > 0) { label.setBackground(Color.WHITE); } return label; } } private class TopicCellEditor extends AbstractCellEditor implements TableCellEditor, java.awt.event.MouseListener { private static final long serialVersionUID = 1L; private JLabel label; public TopicCellEditor(){ label= new JLabel(); label.setOpaque(true); Font f=label.getFont(); label.setFont(new Font(f.getName(),Font.PLAIN,f.getSize())); label.addMouseListener(this); } @Override public Object getCellEditorValue() { return TopicToString.toString(topic); } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { int modelRow = convertRowIndexToModel(row); Topic scope = langs[modelRow]; label.setText(TopicToString.toString(scope)); Color c=wandora.topicHilights.get(scope); if(c==null) c=wandora.topicHilights.getLayerColor(scope); if(c!=null) label.setForeground(c); else label.setForeground(Color.BLACK); if(column > 0) { label.setBackground(Color.WHITE); } return label; } @Override public void mouseReleased(java.awt.event.MouseEvent e) { fireEditingStopped(); Point p = getTableModelPoint(); if(p != null && label.contains(e.getPoint())) { wandora.openTopic(langs[p.y]); } } @Override public void mouseClicked(java.awt.event.MouseEvent e) {} @Override public void mouseEntered(java.awt.event.MouseEvent e) {} @Override public void mouseExited(java.awt.event.MouseEvent e) {} @Override public void mousePressed(java.awt.event.MouseEvent e) {} } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class DataTableModel extends AbstractTableModel { private static final long serialVersionUID = 1L; @Override public int getColumnCount() { return 2; } @Override public int getRowCount() { if(langs == null) return 0; return langs.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if(columnIndex==0) { return langs[rowIndex]; } else { return data[rowIndex]; } } @Override public String getColumnName(int columnIndex){ if(columnIndex==0) { return "Occurrence scope"; } else if(columnIndex==1) { return "Occurrence data"; } else { return ""; } } @Override public boolean isCellEditable(int row,int col) { return true; } } // ------------------------------------------------------------------------- private class OccurrencesTableTransferHandler extends TransferHandler { private static final long serialVersionUID = 1L; @Override public boolean canImport(TransferSupport support) { if(!support.isDrop()) return false; return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) || support.isDataFlavorSupported(DataFlavor.stringFlavor) || support.isDataFlavorSupported(DnDHelper.topicDataFlavor); } @Override protected Transferable createTransferable(JComponent c) { String occurrenceText = null; try { Point p = getTableModelPoint(); if(p != null) { Topic sourceLangTopic = langs[p.y]; occurrenceText = topic.getData(type, sourceLangTopic); } } catch(Exception e) { e.printStackTrace(); } if(occurrenceText == null) { return null; } else { return new StringSelection(occurrenceText); } } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY_OR_MOVE; } @Override public boolean importData(TransferSupport support) { if(!support.isDrop()) return false; try { Transferable transferable = support.getTransferable(); Point p = getTableModelPoint(support.getDropLocation().getDropPoint()); if(p != null) { if(transferable.isDataFlavorSupported(DnDHelper.topicDataFlavor)) { TopicMap tm=wandora.getTopicMap(); List<Topic> topics=DnDHelper.getTopicList(support, tm, true); if(topics==null) return false; // DROP ON TYPE COLUMN ==> DUPLICATE/CHANGE TYPE if(p.x == 0 && p.y == 0) { if(type != null && !type.isRemoved()) { Hashtable<Topic,String> os = topic.getData(type); if(os != null && !os.isEmpty()) { for(Topic scope : os.keySet()) { if(scope != null && !scope.isRemoved()) { String occurrenceText = os.get(scope); for(Topic newType : topics) { if(newType != null && !newType.isRemoved()) { topic.setData(newType, scope, occurrenceText); } } } } } } } else if(p.x > 0) { Topic scope = langs[p.y]; if(type != null && scope != null && !type.isRemoved() && !scope.isRemoved()) { for(Topic t : topics) { if(t != null && !t.isRemoved()) { String occurrenceText = t.getData(type, scope); if(occurrenceText != null) { topic.setData(type, scope, occurrenceText); } } } } } } else if(transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { try { java.util.List<File> fileList = (java.util.List<File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); if(fileList != null && !fileList.isEmpty()) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Make data-url occurrence?", "Make data-url occurrence?", WandoraOptionPane.QUESTION_MESSAGE); boolean makeDataURLOccurrence = (a == WandoraOptionPane.YES_OPTION ? true : false); for( File occurrenceFile : fileList ) { if(makeDataURLOccurrence) { DataURL dataUrl = new DataURL(occurrenceFile); topic.setData(type, langs[p.y], dataUrl.toExternalForm()); } else { String content = null; String filename = occurrenceFile.getPath().toLowerCase(); String suffix = filename.substring(Math.max(filename.lastIndexOf(".")+1, 0)); // --- handle rtf files --- if("rtf".equals(suffix)) { content = Textbox.RTF2PlainText(new FileInputStream(occurrenceFile)); } // --- handle pdf files --- else if("pdf".equals(suffix)) { try { PDDocument doc = PDDocument.load(occurrenceFile); PDFTextStripper stripper = new PDFTextStripper(); content = stripper.getText(doc); doc.close(); } catch(Exception e) { System.out.println("No PDF support!"); } } // --- handle MS office files --- else if("doc".equals(suffix) || "ppt".equals(suffix) || "xsl".equals(suffix) || "vsd".equals(suffix) ) { content = MSOfficeBox.getText(occurrenceFile); } else if("docx".equals(suffix)) { content = MSOfficeBox.getDocxText(occurrenceFile); } else if("txt".equals(suffix)) { FileReader inputReader = new FileReader(occurrenceFile); content = IObox.loadFile(inputReader); } // --- handle everything else --- if(content == null) { FileReader inputReader = new FileReader(occurrenceFile); content = IObox.loadFile(inputReader); } if(content != null) { topic.setData(type, langs[p.y], content); } } } } } catch(Exception e) { e.printStackTrace(); } } else if(transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { Object occurrenceText = support.getTransferable().getTransferData(DataFlavor.stringFlavor); if(occurrenceText != null) { topic.setData(type, langs[p.y], occurrenceText.toString()); } } catch(Exception e) { e.printStackTrace(); } } wandora.doRefresh(); } } catch(TopicMapException tme){tme.printStackTrace();} catch(Exception ce){} return false; } } }
47,747
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MixedTopicGuiWrapper.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/MixedTopicGuiWrapper.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * MixedTopicGuiWrapper.java * */ package org.wandora.application.gui; import java.net.URL; import javax.swing.tree.TreePath; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli, akivela */ public class MixedTopicGuiWrapper { public static final String TOPIC_RENDERS_OPTION_KEY = "gui.topicRenders"; public static final int TOPIC_RENDERS_SL = 100; public static final int TOPIC_RENDERS_SI = 110; public static final int TOPIC_RENDERS_SI_WITHOUT_DOMAIN = 120; public static final int TOPIC_RENDERS_BASENAME = 130; public static final int TOPIC_RENDERS_BASENAME_WITH_SL_ICON = 140; public static final String PROCESSING_TYPE="PROCESSING_TYPE"; public Object content; public String icon; public String associationType; public TreePath path; public MixedTopicGuiWrapper(Object content, String icon,String associationType,TreePath parent) { this.content=content; this.icon=icon; this.associationType=associationType; if(parent==null) path=new TreePath(this); else path=parent.pathByAddingChild(this); } public MixedTopicGuiWrapper(Object content, String icon) { this(content,icon,"",null); } public MixedTopicGuiWrapper(Object content) { this(content,null,"",null); } public Object getContent() { return content; } @Override public String toString() { try { if(associationType.equals(PROCESSING_TYPE))return "Processing..."; else if(content == null) return "[null]"; else if(content instanceof Topic) { Topic topic = (Topic) content; if(topic.isRemoved()) { return "[removed]"; } else { if(topic.getBaseName() != null) { return topic.getBaseName(); } else { return topic.getOneSubjectIdentifier().toExternalForm(); } } } else { return content.toString(); } } catch(Exception e){ e.printStackTrace(); // TODO EXCEPTION return "[Exception retrieving name]"; } } public String toString(int stringType) throws TopicMapException { try { if(associationType.equals(PROCESSING_TYPE)) return "Processing..."; else if(content == null) return "[null]"; else if(content instanceof Topic) { Topic topic=(Topic)content; if(topic.isRemoved()) return "[removed]"; else { switch(stringType) { case TOPIC_RENDERS_BASENAME: { if(topic.getBaseName() == null) { return topic.getOneSubjectIdentifier().toExternalForm(); } else { return topic.getBaseName(); } } case TOPIC_RENDERS_SI: { return topic.getOneSubjectIdentifier().toExternalForm(); } case TOPIC_RENDERS_SI_WITHOUT_DOMAIN: { String urlString = topic.getOneSubjectIdentifier().toExternalForm(); URL url = new URL(urlString); urlString = url.getFile(); if(url.getRef() != null) urlString += "#" + url.getRef(); return urlString; } case TOPIC_RENDERS_SL: { if(topic.getSubjectLocator() == null) { return ""; } else { return topic.getSubjectLocator().toExternalForm(); } } // BY DEFAULT TOPIC RENDERS AS THE BASE NAME default: { if(topic.getBaseName() == null) { return topic.getOneSubjectIdentifier().toExternalForm(); } else { return topic.getBaseName(); } } } } } else { return content.toString(); } } catch(Exception e){ e.printStackTrace(); // TODO EXCEPTION return "[Exception retrieving name]"; } } }
5,684
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
UIConstants.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/UIConstants.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * UIConstants.java * * Created on 17.7.2007, 13:15 * */ package org.wandora.application.gui; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.event.KeyEvent; import javax.swing.BorderFactory; import javax.swing.InputMap; import javax.swing.KeyStroke; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.Border; import javax.swing.text.DefaultEditorKit; import org.wandora.application.gui.filechooser.WPRFileChooser; import org.wandora.application.gui.simple.SimpleFileChooser; /** * UIContants class contains static variables related to Wandora's user interface. * Static variables include fonts and colors used by the application. * * @author akivela */ public class UIConstants { public static boolean ANTIALIASING = true; public static Border defaultTableCellLabelBorder = BorderFactory.createEmptyBorder(3, 3, 3, 3); public static Border defaultLabelBorder = BorderFactory.createEmptyBorder(2, 2, 2, 2); public static Font smallButtonLabelFont = new Font("SansSerif", Font.PLAIN, 10); public static Font buttonLabelFont = new Font("SansSerif", Font.PLAIN, 12); public static Font comboBoxFont = new Font("SansSerif", Font.PLAIN, 12); public static Font labelFont = new Font("SansSerif", Font.PLAIN, 12); public static Font largeLabelFont = new Font("SansSerif", Font.PLAIN, 14); public static Font panelTitleFont = new Font("SansSerif", Font.BOLD, 12); //public static Font wandoraBigLabelFont = new Font("SansSerif", Font.BOLD, 12); public static Font plainFont = new Font("SansSerif", Font.PLAIN, 12); public static Font titleFont = new Font("SansSerif", Font.PLAIN, 14); public static Font menuFont = new Font("SansSerif", Font.PLAIN, 12); public static Font tabFont = new Font("SansSerif", Font.PLAIN, 12); public static Font miniButtonLabel = new Font("SansSerif", Font.BOLD, 7); public static Font h3Font = new Font("SansSerif", Font.PLAIN, 14); public static Font h2Font = new Font("SansSerif", Font.PLAIN, 16); public static Font h1Font = new Font("SansSerif", Font.PLAIN, 20); public static Border dragBorder = BorderFactory.createLineBorder(Color.GRAY); private static SimpleFileChooser fileChooser = null; private static WPRFileChooser wandoraProjectFileChooser = null; public static Color menuColor = new Color(60,60,60); public static Color buttonBarLabelColor = new Color(90,90,90); public static Color buttonBarBackgroundColor = new Color(238,238,238); public static Color buttonBarMouseOverBackgroundColor = new Color(220,231,242); public static Color buttonBackgroundColor = new Color(200,221,242); public static Color buttonMouseOverBackgroundColor = new Color(220,231,242); public static Color checkBoxBackgroundColor = new Color(255,255,255); public static final Color defaultTextColor = new Color(60,60,60); public static final Color defaultInactiveBackground = new Color(229, 229, 229); public static final Color defaultActiveBackground = new Color(200,221,242); public static final Color editableBackgroundColor = new Color(255,255,255); public static final Color noContentBackgroundColor = new Color(245,245,245); public static final Color defaultBorderHighlight = new Color(255,255,255); public static final Color defaultBorderShadow = new Color(200,221,242); public static final Color wandoraBlueColor = new Color(53,56,87); public static WPRFileChooser getWandoraProjectFileChooser() { if(wandoraProjectFileChooser == null) wandoraProjectFileChooser = new WPRFileChooser(); return wandoraProjectFileChooser; } public static SimpleFileChooser getFileChooser() { if(fileChooser == null) fileChooser = new SimpleFileChooser(); fileChooser.setFileSelectionMode(SimpleFileChooser.FILES_AND_DIRECTORIES); return fileChooser; } private static final String[] COPY_PASTE_COMPONENTS = { "TextField.focusInputMap", "PasswordField.focusInputMap", "TextArea.focusInputMap", "TextPane.focusInputMap", "EditorPane.focusInputMap", "FormattedTextField.focusInputMap", "List.focusInputMap", "Table.ancestorInputMap", "Tree.focusInputMap" }; // http://deeploveprogram.pbworks.com/w/page/17134461/UIManager,%20set%20default%20look%20and%20feel public static void initializeGUI() { try { javax.swing.plaf.metal.MetalLookAndFeel.setCurrentTheme(new javax.swing.plaf.metal.OceanTheme()); UIManager.put("swing.boldMetal", Boolean.FALSE); UIManager.put("ToolTip.background", defaultActiveBackground); UIManager.put("TabbedPane.selectHighlight", new Color(229, 229, 229)); UIManager.put("TabbedPane.foreground", defaultTextColor); UIManager.put("TabbedPane.background", defaultInactiveBackground); //UIManager.put("TabbedPane.darkShadow", Color.WHITE); UIManager.put("ToggleButton.disabledBackground", defaultActiveBackground); UIManager.put("ToggleButton.background", defaultActiveBackground); UIManager.put("ComboBox.disabledBackground", defaultInactiveBackground); UIManager.put("ComboBox.background", Color.WHITE); UIManager.put("ComboBox.selectionBackground", defaultActiveBackground); UIManager.put("ComboBox.buttonBackground", defaultActiveBackground); UIManager.put("ComboBox.buttonDarkShadow", defaultActiveBackground); UIManager.put("ComboBox.buttonHighlight", defaultActiveBackground); UIManager.put("ComboBox.buttonShadow", defaultActiveBackground); UIManager.put("Table.focusCellBackground", defaultActiveBackground); UIManager.put("Table.selectionBackground", defaultActiveBackground); UIManager.put("TextField.selectionBackground", defaultActiveBackground); UIManager.put("TextField.background", editableBackgroundColor); UIManager.put("TextArea.background", editableBackgroundColor); UIManager.put("MenuItem.selectionBackground", defaultActiveBackground); UIManager.put("Menu.selectionBackground", defaultActiveBackground); UIManager.put("Menu.background", defaultInactiveBackground); UIManager.put("Button.background", defaultActiveBackground); UIManager.put("Button.foreground", defaultTextColor); UIManager.put("Tree.selectionBackground", defaultActiveBackground); UIManager.put("Tree.line", "None"); UIManager.put("Tree.collapsedIcon", UIBox.getIcon("gui/icons/tree_branch.png")); UIManager.put("Tree.expandedIcon", UIBox.getIcon("gui/icons/tree_branch_open.png")); UIManager.put("Slider.foreground", defaultActiveBackground); UIManager.put("Slider.highlight", defaultActiveBackground); UIManager.put("Slider.horizontalThumbIcon", UIBox.getIcon("gui/icons/slider_thumb_horizontal.png")); UIManager.put("Slider.VerticalThumbIcon", UIBox.getIcon("gui/icons/slider_thumb_vertical.png")); UIManager.setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel()); for (String component : COPY_PASTE_COMPONENTS) { InputMap im = (InputMap) UIManager.get(component); int shortcutMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, shortcutMask), DefaultEditorKit.copyAction); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, shortcutMask), DefaultEditorKit.pasteAction); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_X, shortcutMask), DefaultEditorKit.cutAction); } } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * Used to set rendering hints for given graphics before actual * painting is done. At the moment this method doesn't do anything at all! * * @param g */ public static void preparePaint(Graphics g) { /* if(UIConstants.ANTIALIASING && g instanceof Graphics2D) { RenderingHints qualityHints = new RenderingHints( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); RenderingHints antialiasHints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); RenderingHints metricsHints = new RenderingHints( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); ((Graphics2D) g).addRenderingHints(qualityHints); ((Graphics2D) g).addRenderingHints(antialiasHints); //((Graphics2D) g).addRenderingHints(metricsHints); } */ } //private static Font fancyBaseFont = null; /** * Used to set a font of a component. Doesn't do anything at all at the moment. * * @param component */ public static void setFancyFont(Component component) { /* try { if(fancyBaseFont == null) { InputStream is = new BufferedInputStream(new FileInputStream("./gui/fonts/Arimo-Regular.ttf")); fancyBaseFont = Font.createFont(Font.TRUETYPE_FONT, is); } if(fancyBaseFont != null) { Font fancyFont = fancyBaseFont.deriveFont(Font.PLAIN, component.getFont().getSize()); component.setFont(fancyFont); } } catch(Exception e) { e.printStackTrace(); } */ } }
11,048
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VariantNameEditor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/VariantNameEditor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * VariantNameEditor.java * * Created on 26.4.2011, 17:53:33 */ package org.wandora.application.gui; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultListModel; import javax.swing.JDialog; import javax.swing.ListModel; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.XTMPSI; /** * * @author akivela */ public class VariantNameEditor extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private JDialog myDialog = null; private boolean wasAccepted = false; private List<Topic> scopeTopics = new ArrayList<>(); private Wandora wandora = null; private static List<Locator> lastScopeSubjects = new ArrayList<>(); /** Creates new form VariantNameEditor */ public VariantNameEditor(Wandora w) { wandora = w; initComponents(); } public void initialize(Set<Topic> scope, String variantString) { if(variantString != null) variantTextField.setText(variantString); else variantTextField.setText(""); scopeTopics.addAll(scope); wasAccepted = false; } public void openEditor(String title) { wandora = Wandora.getWandora(); myDialog = new JDialog(wandora, true); myDialog.add(this); myDialog.setSize(800,300); myDialog.setTitle(title); wandora.centerWindow(myDialog); myDialog.setVisible(true); } // ----- public boolean wasAccepted() { return wasAccepted; } public String getVariantString() { return variantTextField.getText(); } public Set<Topic> getVariantScope() { Set<Topic> set = new LinkedHashSet<>(); set.addAll(scopeTopics); return set; } private void setScope(String[] scopeLocators) { TopicMap tm = Wandora.getWandora().getTopicMap(); Topic t; for(String l : scopeLocators) { try { if(l != null) { t = tm.getTopic(l); if(t != null && !t.isRemoved()) { scopeTopics.add(t); } } } catch (TopicMapException ex) { Logger.getLogger(VariantNameEditor.class.getName()).log(Level.SEVERE, null, ex); } } scopeTopicList.setModel(new VariantScopeListModel()); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; innerPanel = new javax.swing.JPanel(); nameLabel = new SimpleLabel(); variantTextField = new SimpleField(); scopeLabel = new SimpleLabel(); scopeTopicScrollPane = new SimpleScrollPane(); scopeTopicList = new javax.swing.JList(); scopeButtonPanel = new javax.swing.JPanel(); addScopeTopicButton = new SimpleButton(); removeScopeTopicButton = new SimpleButton(); addEnglishDisplayButton = new SimpleButton(); addLangndepDisplayButton = new SimpleButton(); addSameAsPreviousButton = new SimpleButton(); buttonPanel = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); innerPanel.setLayout(new java.awt.GridBagLayout()); nameLabel.setText("Name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4); innerPanel.add(nameLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); innerPanel.add(variantTextField, gridBagConstraints); scopeLabel.setText("Scope"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); innerPanel.add(scopeLabel, gridBagConstraints); scopeTopicScrollPane.setMinimumSize(new java.awt.Dimension(23, 130)); scopeTopicList.setModel(new VariantScopeListModel()); scopeTopicScrollPane.setViewportView(scopeTopicList); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0); innerPanel.add(scopeTopicScrollPane, gridBagConstraints); scopeButtonPanel.setLayout(new java.awt.GridBagLayout()); addScopeTopicButton.setText("Add scope topic..."); addScopeTopicButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); addScopeTopicButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addScopeTopicButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); scopeButtonPanel.add(addScopeTopicButton, gridBagConstraints); removeScopeTopicButton.setText("Remove selected scope topics"); removeScopeTopicButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); removeScopeTopicButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeScopeTopicButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0); scopeButtonPanel.add(removeScopeTopicButton, gridBagConstraints); addEnglishDisplayButton.setText("Set English display scope"); addEnglishDisplayButton.setActionCommand("Set English display scope"); addEnglishDisplayButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); addEnglishDisplayButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addEnglishDisplayButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); scopeButtonPanel.add(addEnglishDisplayButton, gridBagConstraints); addLangndepDisplayButton.setText("Set lang independent display scope"); addLangndepDisplayButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); addLangndepDisplayButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addLangndepDisplayButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); scopeButtonPanel.add(addLangndepDisplayButton, gridBagConstraints); addSameAsPreviousButton.setText("Set previous scope topics"); addSameAsPreviousButton.setActionCommand("Add previous scope topics"); addSameAsPreviousButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); addSameAsPreviousButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addSameAsPreviousButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; scopeButtonPanel.add(addSameAsPreviousButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); innerPanel.add(scopeButtonPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); add(innerPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(jPanel3, gridBagConstraints); okButton.setText("OK"); okButton.setMargin(new java.awt.Insets(2, 24, 2, 24)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); buttonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed wasAccepted = false; if(myDialog != null) myDialog.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed if(scopeTopics != null && !scopeTopics.isEmpty()) { lastScopeSubjects = new ArrayList<Locator>(); for(Topic t : scopeTopics) { try { if(t != null && !t.isRemoved()) { lastScopeSubjects.add(t.getOneSubjectIdentifier()); } } catch (TopicMapException ex) { Logger.getLogger(VariantNameEditor.class.getName()).log(Level.SEVERE, null, ex); } } } wasAccepted = true; if(myDialog != null) myDialog.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed private void addEnglishDisplayButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addEnglishDisplayButtonActionPerformed setScope( new String[] { XTMPSI.DISPLAY, XTMPSI.getLang("en") } ); }//GEN-LAST:event_addEnglishDisplayButtonActionPerformed private void addSameAsPreviousButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addSameAsPreviousButtonActionPerformed if(lastScopeSubjects != null && !lastScopeSubjects.isEmpty()) { TopicMap tm = Wandora.getWandora().getTopicMap(); Topic t; for(Locator l : lastScopeSubjects) { try { t = tm.getTopic(l); if(t != null && !t.isRemoved()) { scopeTopics.add(t); } } catch (TopicMapException ex) { Logger.getLogger(VariantNameEditor.class.getName()).log(Level.SEVERE, null, ex); } } scopeTopicList.setModel(new VariantScopeListModel()); } }//GEN-LAST:event_addSameAsPreviousButtonActionPerformed private void removeScopeTopicButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeScopeTopicButtonActionPerformed try { int[] selection = scopeTopicList.getSelectedIndices(); ArrayList<Topic> removeScopeTopics = new ArrayList(); for(int i=0; i<selection.length; i++) { removeScopeTopics.add(scopeTopics.get(selection[i])); } scopeTopics.removeAll(removeScopeTopics); scopeTopicList.setModel(new VariantScopeListModel()); } catch(Exception e) { Logger.getLogger(VariantNameEditor.class.getName()).log(Level.SEVERE, null, e); } }//GEN-LAST:event_removeScopeTopicButtonActionPerformed private void addScopeTopicButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addScopeTopicButtonActionPerformed try { Topic addedScope = wandora.showTopicFinder("Select variant scope topic..."); if(addedScope != null) { scopeTopics.add(addedScope); scopeTopicList.setModel(new VariantScopeListModel()); } } catch(Exception e) { Logger.getLogger(VariantNameEditor.class.getName()).log(Level.SEVERE, null, e); } }//GEN-LAST:event_addScopeTopicButtonActionPerformed private void addLangndepDisplayButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addLangndepDisplayButtonActionPerformed setScope( new String[] { XTMPSI.DISPLAY, XTMPSI.LANG_INDEPENDENT } ); }//GEN-LAST:event_addLangndepDisplayButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addEnglishDisplayButton; private javax.swing.JButton addLangndepDisplayButton; private javax.swing.JButton addSameAsPreviousButton; private javax.swing.JButton addScopeTopicButton; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel innerPanel; private javax.swing.JPanel jPanel3; private javax.swing.JLabel nameLabel; private javax.swing.JButton okButton; private javax.swing.JButton removeScopeTopicButton; private javax.swing.JPanel scopeButtonPanel; private javax.swing.JLabel scopeLabel; private javax.swing.JList scopeTopicList; private javax.swing.JScrollPane scopeTopicScrollPane; private javax.swing.JTextField variantTextField; // End of variables declaration//GEN-END:variables private class VariantScopeListModel extends DefaultListModel implements ListModel { private static final long serialVersionUID = 1L; @Override public int getSize() { if(scopeTopics != null) { return scopeTopics.size(); } else { return 0; } } @Override public Object getElementAt(int index) { if(scopeTopics != null) { if(index >= 0 && index < scopeTopics.size()) { return scopeTopics.get(index); } } return null; } } }
18,604
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OccurrenceTableAll.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/OccurrenceTableAll.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * OccurrenceTableAll.java * * Created on August 17, 2004, 12:07 PM */ package org.wandora.application.gui; import java.awt.Color; import java.awt.Component; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import java.awt.Point; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.Reader; import java.io.StringReader; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Hashtable; import java.util.List; import java.util.Set; import javax.swing.AbstractCellEditor; import javax.swing.DropMode; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.JTable; import javax.swing.TransferHandler; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.wandora.application.Wandora; import org.wandora.application.WandoraMenuManager; import org.wandora.application.contexts.ApplicationContext; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleTable; import org.wandora.application.gui.simple.SimpleTextPane; import org.wandora.application.gui.texteditor.OccurrenceTextEditor; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.occurrences.DeleteOccurrence; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.ClipboardBox; import org.wandora.utils.IObox; import org.wandora.utils.MSOfficeBox; import org.wandora.utils.Options; import org.wandora.utils.Textbox; import org.wandora.utils.swing.TableSorter; /** * * @author olli, akivela */ public class OccurrenceTableAll extends SimpleTable implements OccurrenceTable, MouseListener, Clipboardable { private static final long serialVersionUID = 1L; public String tableType = VIEW_SCHEMA; private Topic topic; private Topic[] langs; private Topic[] types; private String[][] data; private Color[][] colors; private TableSorter sorter; private Wandora wandora; private Options options; private TableTopicWrapper[] wrappedTypes; private Set<Topic> removedTypes; private String[][] originalData; private int rowHeight = 1; private Object[] popupStruct; private MouseEvent mouseEvent; /** Creates a new instance of OccurrenceTableAll */ public OccurrenceTableAll(Topic topic, Options options, Wandora wandora) throws TopicMapException { this.wandora = wandora; this.topic = topic; this.options = options; try { Options opts = options; if(opts == null) opts = wandora.getOptions(); if(opts != null) { tableType = opts.get(VIEW_OPTIONS_KEY); if(tableType == null || tableType.length() == 0) tableType = VIEW_SCHEMA; rowHeight = opts.getInt(ROW_HEIGHT_OPTIONS_KEY); if(rowHeight < 1) rowHeight = 1; } } catch(Exception e) { e.printStackTrace(); } types=(Topic[])topic.getDataTypes().toArray(new Topic[0]); ArrayList<Topic> langArray = new ArrayList<Topic>(); if(VIEW_USED.equalsIgnoreCase(tableType) || VIEW_USED_AND_SCHEMA.equalsIgnoreCase(tableType)) { Hashtable<Topic,String> occs = null; Topic langTopic = null; for(int i=0; i<types.length; i++) { occs = topic.getData(types[i]); for(Enumeration<Topic> keys = occs.keys(); keys.hasMoreElements(); ) { langTopic = keys.nextElement(); if(!langArray.contains(langTopic)) { langArray.add(langTopic); } } } } if(VIEW_SCHEMA.equalsIgnoreCase(tableType) || VIEW_USED_AND_SCHEMA.equalsIgnoreCase(tableType)) { String[] langSIs=TMBox.getLanguageSIs(wandora.getTopicMap()); Topic langTopic = null; for(int i=0;i<langSIs.length;i++){ langTopic = wandora.getTopicMap().getTopic(langSIs[i]); if(langTopic != null && !langArray.contains(langTopic)) { langArray.add( langTopic ); } } } langs=langArray.toArray( new Topic[langArray.size()] ); wrappedTypes=new TableTopicWrapper[types.length]; removedTypes=new HashSet<>(); data=new String[types.length][langs.length]; originalData=new String[types.length][langs.length]; colors=new Color[types.length][langs.length]; for(int i=0;i<types.length;i++) { if(types[i] != null) { wrappedTypes[i]=new TableTopicWrapper(types[i]); for(int j=0;j<langs.length;j++){ if(langs[j] != null) { data[i][j]=topic.getData(types[i],langs[j]); if(data[i][j]==null) data[i][j]=""; originalData[i][j]=data[i][j]; colors[i][j]=wandora.topicHilights.getOccurrenceColor(topic,types[i],langs[j]); } } } } this.setColumnSelectionAllowed(false); this.setRowSelectionAllowed(false); sorter=new TableSorter(new DataTableModel()); final Color[] columnColors=new Color[langs.length]; for(int i=0;i<columnColors.length;i++){ columnColors[i]=wandora.topicHilights.get(langs[i]); if(columnColors[i]==null) columnColors[i]=wandora.topicHilights.getLayerColor(langs[i]); } final TableCellRenderer oldRenderer=this.getTableHeader().getDefaultRenderer(); this.getTableHeader().setDefaultRenderer(new TableCellRenderer(){ public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus, int row, int column){ Component c=oldRenderer.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column); column=convertColumnIndexToModel(column); if(column>0 && column-1<columnColors.length && columnColors[column-1]!=null){ c.setForeground(columnColors[column-1]); } return c; } }); this.setRowHeight(2+rowHeight*16); this.setAutoCreateColumnsFromModel(false); this.setModel(sorter); TableColumn column=new TableColumn(0,80,new TopicCellRenderer(),new TopicCellEditor()); this.addColumn(column); for(int i=0;i<langs.length;i++){ this.addColumn(new TableColumn(i+1,80,new DataCellRenderer(),new DataCellEditor())); } column=new TableColumn(langs.length+1,80,new DeleteCellRenderer(),new DeleteCellEditor()); column.setMaxWidth(30); column.setMinWidth(30); this.addColumn(column); sorter.setTableHeader(this.getTableHeader()); initPopupStructures(); JPopupMenu popup = UIBox.makePopupMenu(popupStruct, wandora); this.setComponentPopupMenu(popup); this.addMouseListener(this); this.setDragEnabled(true); this.setTransferHandler(new OccurrencesTableTransferHandler()); this.setDropMode(DropMode.ON); this.createDefaultTableSelectionModel(); } public boolean applyChanges(Topic t, Wandora parent) throws TopicMapException { boolean changed=false; for(int i=0;i<types.length;i++) { if(removedTypes.contains(types[i])) continue; for(int j=0;j<langs.length;j++){ String text=data[i][j]; if(text != null) { // String orig=topic.getData(types[i],langs[j]); String orig=originalData[i][j]; if(orig==null) orig=""; if(!orig.equals(text)) { changed=true; if(text.length()==0) { topic.removeData(types[i],langs[j]); } else { topic.setData(types[i], langs[j], text ); } } } } } return changed; } public Topic getTopic() { return topic; } @Override public String getToolTipText(java.awt.event.MouseEvent e) { java.awt.Point p=e.getPoint(); int row=rowAtPoint(p); int col=columnAtPoint(p); int realCol=convertColumnIndexToModel(col); if(realCol==langs.length+1) return null; String tooltipText = sorter.getValueAt(row,realCol).toString(); if(tooltipText != null && tooltipText.length() > 5) { if(tooltipText.length() > 1000) tooltipText = tooltipText.substring(0,999)+"..."; return Textbox.makeHTMLParagraph(tooltipText, 40); } return null; } public int getRowHeightOption() { return rowHeight; } public Object getOccurrenceTableType() { return tableType; } private void initPopupStructures() { try { popupStruct = WandoraMenuManager.getOccurrenceTableMenu(this, options); } catch(Exception tme){ wandora.handleError(tme); } } public String getPointedOccurrence() { try { Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol > 0 && realRow < types.length && realCol < langs.length+1) { return topic.getData(types[realRow], langs[realCol-1]); } } catch(Exception e) { e.printStackTrace(); } return null; } public Topic getPointedOccurrenceType() { try { Point p = getTablePoint(mouseEvent); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realRow < types.length) { return types[realRow]; } } catch(Exception e) { e.printStackTrace(); } return null; } public Topic getPointedOccurrenceLang() { try { Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); if(realCol > 0 && realCol < langs.length+1) { return langs[realCol-1]; } } catch(Exception e) { e.printStackTrace(); } return null; } public void cut() { try { copy(); Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol > 0 && realRow < types.length && realCol < langs.length+1) { topic.removeData(types[realRow], langs[realCol-1]); } } catch(Exception e) { e.printStackTrace(); if(wandora != null) wandora.handleError(e); } } public void paste() { try { Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol > 0 && realRow < types.length && realCol < langs.length+1) { topic.setData(types[realRow], langs[realCol-1], ClipboardBox.getClipboard()); } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } public void append() { try { Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol > 0 && realRow < types.length && realCol < langs.length+1) { String oldOccurrence = topic.getData(types[realRow], langs[realCol-1]); if(oldOccurrence == null) oldOccurrence = ""; topic.setData(types[realRow], langs[realCol-1], oldOccurrence + ClipboardBox.getClipboard()); } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } public void copy() { ClipboardBox.setClipboard(getCopyString()); } public String getCopyString() { Object cellContent; try { Point loc = getTablePoint(mouseEvent); cellContent = getValueAt(loc); return cellContent.toString(); } catch(Exception e){ if(wandora != null) wandora.handleError(e); } return ""; } public void delete() { try { Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol >= 0 && realRow < types.length && realCol < langs.length+1) { if(realCol == 0) { topic.removeData(types[realRow]); } else { topic.removeData(types[realRow], langs[realCol-1]); } } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } public void changeType() { try { Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol >= 0 && realRow < types.length && realCol <= langs.length) { Topic type = types[realRow]; Topic selectedScope = null; if(realCol > 0 && realCol <= langs.length) { selectedScope = langs[realCol-1]; } if(type != null && !type.isRemoved()) { Topic newType = wandora.showTopicFinder("Select new occurrence type"); if(newType != null && !newType.isRemoved()) { Hashtable<Topic,String> os = topic.getData(type); if(os != null && !os.isEmpty()) { for(Topic scope : os.keySet()) { if(scope != null && !scope.isRemoved()) { if(selectedScope == null) { String occurrenceText = os.get(scope); topic.setData(newType, scope, occurrenceText); } else if(selectedScope.mergesWithTopic(scope)) { String occurrenceText = os.get(scope); topic.setData(newType, scope, occurrenceText); } } } if(selectedScope == null) { topic.removeData(type); } else { topic.removeData(type, selectedScope); } } } } } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } public void duplicateType() { try { Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol >= 0 && realRow < types.length && realCol < langs.length+1) { Topic type = types[realRow]; Topic selectedScope = null; if(realCol > 0 && realCol <= langs.length) { selectedScope = langs[realCol-1]; } if(type != null && !type.isRemoved()) { Topic newType = wandora.showTopicFinder("Select new occurrence type"); if(newType != null && !newType.isRemoved()) { Hashtable<Topic,String> os = topic.getData(type); if(os != null && !os.isEmpty()) { for(Topic scope : os.keySet()) { if(scope != null && !scope.isRemoved()) { if(selectedScope == null) { String occurrenceText = os.get(scope); topic.setData(newType, scope, occurrenceText); } else if(selectedScope.mergesWithTopic(scope)) { String occurrenceText = os.get(scope); topic.setData(newType, scope, occurrenceText); } } } } } } } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } public void openURLOccurrence() { try { String errorMessage = null; Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol > 0 && realRow < types.length && realCol < langs.length+1) { String occurrence = topic.getData(types[realRow], langs[realCol-1]); if(occurrence != null) { occurrence = occurrence.trim(); if(occurrence.length() > 0) { try { Desktop desktop = Desktop.getDesktop(); desktop.browse(new URI(occurrence)); } catch(Exception e) { if(occurrence.length() > 80) occurrence = occurrence.substring(0, 80)+"..."; errorMessage = "Exception occurred while starting external browser for occurrence. Check if occurrence text is a valid URL."; e.printStackTrace(); } } } } if(errorMessage != null) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), errorMessage, "Error while opening URL"); } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } public void downloadURLOccurrence() { try { Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol > 0 && realRow < types.length && realCol < langs.length+1) { String occurrence = topic.getData(types[realRow], langs[realCol-1]); if(occurrence != null) { occurrence = occurrence.trim(); if(occurrence.length() > 0) { try { String occurrenceContent = IObox.doUrl(new URL(occurrence)); topic.setData(types[realRow], langs[realCol-1], occurrenceContent); } catch(Exception e) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Exception '"+e.getMessage()+"' occurred while downloading URL '"+occurrence+"'.", "Error downloading URL", WandoraOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } } } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } public void spread() { try { Point p = getTablePoint(mouseEvent); boolean overrideAll = false; if(mouseEvent != null && mouseEvent.isAltDown()) overrideAll = true; int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol > 0 && realRow < types.length && realCol < langs.length+1) { String occurrenceText = topic.getData(types[realRow], langs[realCol-1]); Topic type = types[realRow]; for(int i=0; i<langs.length; i++) { if(i != realCol-1) { int override = WandoraOptionPane.YES_OPTION; if(!overrideAll && topic.getData(type, langs[i]) != null) { override = WandoraOptionPane.showConfirmDialog(wandora, "Override existing "+langs[i].getDisplayName()+" occurrence?", "Override existing occurrence?", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION); if(override == WandoraOptionPane.YES_TO_ALL_OPTION) overrideAll = true; if(override == WandoraOptionPane.CANCEL_OPTION) return; } if(override == WandoraOptionPane.YES_OPTION || override == WandoraOptionPane.YES_TO_ALL_OPTION) { topic.setData(type, langs[i], occurrenceText); } } } } } catch(Exception e) { if(wandora != null) wandora.handleError(e); } } // ------------------------------------------------------------------------- public Point getTablePoint() { return getTablePoint(mouseEvent); } public Point getTablePoint(java.awt.event.MouseEvent e) { try { java.awt.Point p=e.getPoint(); int row=rowAtPoint(p); int col=columnAtPoint(p); //int realCol=convertColumnIndexToModel(col); return new Point(row, col); } catch (Exception ex) { wandora.handleError(ex); return null; } } public Object getValueAt(MouseEvent e) { return getValueAt(getTablePoint(e)); } public Object getValueAt(Point p) { return getValueAt(p.x, p.y); } @Override public Object getValueAt(int x, int y) { try { return getModel().getValueAt(x, convertColumnIndexToModel(y)); } catch (Exception e) { e.printStackTrace(); } return null; } // ------------------------------------------------------------------------- @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; //System.out.println("Mouse clicked!"); } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class DataCellRenderer implements TableCellRenderer { private SimpleTextPane label; public DataCellRenderer(){ label=new SimpleTextPane(); label.setOpaque(true); label.setMargin(new Insets(0,0,0,0)); Font f=label.getFont(); label.setFont(new Font(f.getName(),Font.PLAIN,f.getSize())); label.setBackground(Color.WHITE); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { label.setText(value.toString()); column=convertColumnIndexToModel(column); Color c=colors[row][column-1]; if(c!=null) label.setForeground(c); else label.setForeground(Color.BLACK); return label; } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class DataCellEditor extends AbstractCellEditor implements TableCellEditor, java.awt.event.MouseListener { private static final long serialVersionUID = 1L; private Topic type,version; private SimpleTextPane label; private String editedText; int realCol,realRow; public DataCellEditor(){ label=new SimpleTextPane(); label.setMargin(new Insets(0,0,0,0)); Font f=label.getFont(); label.setFont(new Font(f.getName(),Font.PLAIN,f.getSize())); label.addMouseListener(this); } public Object getCellEditorValue() { return editedText; } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { realCol=convertColumnIndexToModel(column); realRow=sorter.modelIndex(row); type=types[realRow]; version=langs[realCol-1]; label.setText(value.toString()); editedText=value.toString();; return label; } public void mouseReleased(java.awt.event.MouseEvent e) { if(label.contains(e.getPoint())){ OccurrenceTextEditor ed = new OccurrenceTextEditor(wandora, true, editedText, topic, type, version); String typeName = wandora.getTopicGUIName(type); String topicName = wandora.getTopicGUIName(topic); ed.setTitle("Edit occurrence text of '"+typeName+"' attached to '"+topicName+"'"); ed.setVisible(true); if(ed.acceptChanges()) { if(ed.getText() != null) { editedText=ed.getText(); data[realRow][realCol-1]=editedText; } try { boolean changed = applyChanges(topic, wandora); if(changed) { wandora.doRefresh(); } } catch(Exception ex) { ex.printStackTrace(); } } } fireEditingStopped(); } public void mouseClicked(java.awt.event.MouseEvent e) {} public void mouseEntered(java.awt.event.MouseEvent e) {} public void mouseExited(java.awt.event.MouseEvent e) {} public void mousePressed(java.awt.event.MouseEvent e) {} } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class DeleteCellEditor extends AbstractCellEditor implements TableCellEditor, java.awt.event.ActionListener { private static final long serialVersionUID = 1L; private JButton button; private Topic type; public DeleteCellEditor() { button = new SimpleButton(UIBox.getIcon("gui/icons/delete_occurrence.png")); button.setPreferredSize(new Dimension(16,16)); button.setSize(new Dimension(16,16)); button.setBounds(0, 0, 0, 0); button.setBorderPainted(false); button.setOpaque(true); button.setBackground(UIConstants.buttonBarBackgroundColor); button.setFont(new Font("SansSerif",Font.PLAIN, 10)); button.setToolTipText("Delete occurrence"); button.addActionListener(this); } public Object getCellEditorValue() { return ""; } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { type=types[sorter.modelIndex(row)]; return button; } public void actionPerformed(java.awt.event.ActionEvent e) { try { DeleteOccurrence tool=new DeleteOccurrence(type); tool.setContext(new ApplicationContext()); tool.execute(wandora); } catch(TopicMapException tme) { tme.printStackTrace(); } // TODO EXCEPTION } } private class DeleteCellRenderer implements TableCellRenderer { private JButton button; public DeleteCellRenderer() { button = new SimpleButton(UIBox.getIcon("gui/icons/delete_occurrence.png")); button.setPreferredSize(new Dimension(16,16)); button.setSize(new Dimension(16,16)); button.setBounds(0, 0, 0, 0); button.setBorderPainted(false); button.setOpaque(true); button.setBackground(UIConstants.buttonBarBackgroundColor); button.setFont(new Font("SansSerif",Font.PLAIN, 10)); button.setToolTipText("Delete occurrence"); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return button; } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class TopicCellRenderer implements TableCellRenderer { private JLabel label; public TopicCellRenderer(){ label=new JLabel(""); label.setOpaque(true); Font f=label.getFont(); label.setFont(new Font(f.getName(),Font.PLAIN,f.getSize())); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Topic topic=((TableTopicWrapper)value).topic; if(topic==null) label.setText("--"); else { try { label.setText(TopicToString.toString(topic)); } catch(Exception tme){ tme.printStackTrace(); // TODO EXCEPTION label.setText("[exception retrieving occurrence]"); } } Color c=wandora.topicHilights.get(topic); if(c==null) c=wandora.topicHilights.getLayerColor(topic); if(c!=null) label.setForeground(c); else label.setForeground(Color.BLACK); if(column > 0) { label.setBackground(Color.WHITE); } return label; } } private class TopicCellEditor extends AbstractCellEditor implements TableCellEditor, java.awt.event.MouseListener { private static final long serialVersionUID = 1L; private Topic topic; private JLabel label; public TopicCellEditor(){ label= new JLabel(); label.setOpaque(true); Font f=label.getFont(); label.setFont(new Font(f.getName(),Font.PLAIN,f.getSize())); label.addMouseListener(this); } public Object getCellEditorValue() { if(topic==null) return "--"; else { try{ return TopicToString.toString(topic); }catch(Exception tme){ tme.printStackTrace(); // TODO EXCEPTION return "Exception retrieving name"; } } } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { topic=((TableTopicWrapper)value).topic; if(topic==null) label.setText("--"); else { try{ label.setText(topic.getBaseName()); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION label.setText("Exception retrieving name"); } } return label; } @Override public void mouseReleased(java.awt.event.MouseEvent e) { fireEditingStopped(); if(label.contains(e.getPoint()) && topic!=null) wandora.openTopic(topic); } @Override public void mouseClicked(java.awt.event.MouseEvent e) {} @Override public void mouseEntered(java.awt.event.MouseEvent e) {} @Override public void mouseExited(java.awt.event.MouseEvent e) {} @Override public void mousePressed(java.awt.event.MouseEvent e) {} } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class DataTableModel extends AbstractTableModel { private static final long serialVersionUID = 1L; public int getColumnCount() { if(langs == null) return 0; return langs.length+1; } public int getRowCount() { if(types == null) return 0; return types.length; } public Object getValueAt(int rowIndex, int columnIndex) { if(columnIndex==0){ return wrappedTypes[rowIndex]; } else if(columnIndex==langs.length+1) return ""; else return data[rowIndex][columnIndex-1]; } @Override public String getColumnName(int columnIndex){ if(columnIndex==0) return "Occurrence type"; else if(columnIndex==langs.length+1) return ""; if(langs[columnIndex-1] == null) return "No topic"; else { String name = "[null]"; try { Topic t = langs[columnIndex-1]; if(t != null && !t.isRemoved()) { name = wandora.getTopicGUIName(t); //name = t.getBaseName(); if(name == null) { name = t.getOneSubjectIdentifier().toExternalForm(); } } if(t.isRemoved()) { name = "[removed]"; } } catch(Exception e) { e.printStackTrace(); } return name; } } @Override public boolean isCellEditable(int row,int col) { return true; } } private class TableTopicWrapper { private Topic topic; private String name; public TableTopicWrapper(Topic t){ topic=t; } @Override public String toString(){ if(topic==null) { try { return topic.getOneSubjectIdentifier().toExternalForm(); } catch(Exception e) { return "[null]"; } } else { try { name = topic.getBaseName(); if(name != null) { return name; } else { return topic.getOneSubjectIdentifier().toExternalForm(); } } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION return "[Exception retrieving name]"; } } } } // ------------------------------------------------------------------------- private class OccurrencesTableTransferHandler extends TransferHandler { private static final long serialVersionUID = 1L; @Override public boolean canImport(TransferSupport support) { if(!support.isDrop()) return false; return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) || support.isDataFlavorSupported(DataFlavor.stringFlavor) || support.isDataFlavorSupported(DnDHelper.topicDataFlavor); } @Override protected Transferable createTransferable(JComponent c) { String occurrenceText = null; try { Point p = getTablePoint(mouseEvent); int realCol=convertColumnIndexToModel(p.y); int realRow=sorter.modelIndex(p.x); if(realRow >= 0 && realCol > 0 && realRow < types.length && realCol < langs.length+1) { Topic sourceLangTopic = langs[realCol-1]; occurrenceText = topic.getData(types[realRow], sourceLangTopic); } } catch(Exception e) { e.printStackTrace(); } if(occurrenceText == null) { return null; } else { return new StringSelection(occurrenceText); } } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY_OR_MOVE; } @Override public boolean importData(TransferSupport support) { if(!support.isDrop()) return false; try { Transferable transferable = support.getTransferable(); Point p = support.getDropLocation().getDropPoint(); int realRow=rowAtPoint(p); int realCol=columnAtPoint(p); if(realRow >= 0 && realCol >= 0 && realRow < types.length && realCol < langs.length+1) { if(transferable.isDataFlavorSupported(DnDHelper.topicDataFlavor)) { TopicMap tm=wandora.getTopicMap(); List<Topic> topics=DnDHelper.getTopicList(support, tm, true); if(topics==null) return false; // DROP ON TYPE COLUMN ==> DUPLICATE/CHANGE TYPE if(realCol == 0) { Topic type = types[realRow]; if(type != null && !type.isRemoved()) { Hashtable<Topic,String> os = topic.getData(type); if(os != null && !os.isEmpty()) { for(Topic scope : os.keySet()) { if(scope != null && !scope.isRemoved()) { String occurrenceText = os.get(scope); for(Topic newType : topics) { if(newType != null && !newType.isRemoved()) { topic.setData(newType, scope, occurrenceText); } } } } } } } else if(realCol > 0) { Topic type = types[realRow]; Topic scope = langs[realCol-1]; if(type != null && scope != null && !type.isRemoved() && !scope.isRemoved()) { for(Topic t : topics) { if(t != null && !t.isRemoved()) { String occurrenceText = t.getData(type, scope); if(occurrenceText != null) { topic.setData(type, scope, occurrenceText); } } } } } } else if(transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { try { java.util.List<File> fileList = (java.util.List<File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); if(fileList != null && fileList.size() > 0) { for( File occurrenceFile : fileList ) { Reader inputReader = null; String content = ""; String filename = occurrenceFile.getPath().toLowerCase(); String extension = filename.substring(Math.max(filename.lastIndexOf(".")+1, 0)); // --- handle rtf files --- if("rtf".equals(extension)) { content=Textbox.RTF2PlainText(new FileInputStream(occurrenceFile)); inputReader = new StringReader(content); } // --- handle pdf files --- if("pdf".equals(extension)) { try { PDDocument doc = PDDocument.load(occurrenceFile); PDFTextStripper stripper = new PDFTextStripper(); content = stripper.getText(doc); doc.close(); inputReader = new StringReader(content); } catch(Exception e) { System.out.println("No PDF support!"); } } // --- handle MS office files --- if("doc".equals(extension) || "ppt".equals(extension) || "xsl".equals(extension) || "vsd".equals(extension) ) { content = MSOfficeBox.getText(occurrenceFile); if(content != null) { inputReader = new StringReader(content); } } if("docx".equals(extension)) { content = MSOfficeBox.getDocxText(occurrenceFile); if(content != null) { inputReader = new StringReader(content); } } // --- handle everything else --- if(inputReader == null) { inputReader = new FileReader(occurrenceFile); } String occurrenceText = IObox.loadFile(inputReader); if(occurrenceText != null) { topic.setData(types[realRow], langs[realCol-1], occurrenceText); } } } } catch(Exception e) { e.printStackTrace(); } } else if(transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { Object occurrenceText = support.getTransferable().getTransferData(DataFlavor.stringFlavor); if(occurrenceText != null) { topic.setData(types[realRow], langs[realCol-1], occurrenceText.toString()); } } catch(Exception e) { e.printStackTrace(); } } wandora.doRefresh(); } } catch(TopicMapException tme){tme.printStackTrace();} catch(Exception ce){} return false; } } }
48,091
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicSelectList.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/TopicSelectList.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicSelectList.java * * Created on August 11, 2004, 2:00 PM */ package org.wandora.application.gui; import java.awt.event.KeyEvent; import java.util.Collection; import java.util.Vector; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class TopicSelectList extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private Topic[] topics; private JComboBox cbox; private JTextField field; private boolean running; private ListWindow listWindow; private boolean editable; private JDialog owner; /** Creates new form TopicSelector */ public TopicSelectList(Collection ts,boolean editable,JDialog owner) { this.owner=owner; this.topics=(Topic[])TMBox.sortTopics(ts,null).toArray(new Topic[0]); this.editable=editable; initComponents(); this.setLayout(new java.awt.BorderLayout()); if(topics.length<0){ cbox=new JComboBox(); for(int i=0;i<topics.length;i++){ Topic t=topics[i]; cbox.addItem(new ComboBoxTopicWrapper(t)); } cbox.setEditable(editable); this.add(cbox,java.awt.BorderLayout.CENTER); } else{ field=new JTextField(); field.setFocusTraversalKeysEnabled(false); /* field.getDocument().addDocumentListener(new javax.swing.event.DocumentListener(){ public void changedUpdate(javax.swing.event.DocumentEvent e){ if(listWindow!=null){ listWindow.hide(); listWindow.dispose(); showList(); } } public void insertUpdate(javax.swing.event.DocumentEvent e){changedUpdate(e);} public void removeUpdate(javax.swing.event.DocumentEvent e){changedUpdate(e);} });*/ field.addKeyListener(new java.awt.event.KeyAdapter(){ public void keyReleased(java.awt.event.KeyEvent e){ /*if(listWindow!=null){ e.consume(); e.setSource(listWindow.l); listWindow.l.dispatchEvent(e); } else */ if(listWindow==null && e.getKeyCode()==e.VK_TAB){ e.consume(); showList(); } } public void keyTyped(java.awt.event.KeyEvent e){ if(listWindow!=null){ e.setSource(listWindow.l); listWindow.l.dispatchEvent(e); } } /* public void keyPressed(java.awt.event.KeyEvent e){ if(listWindow!=null){ if(e.getKeyCode()==e.VK_ENTER){ if(listWindow.l.getSelectedIndex()!=-1){ String text=((ComboBoxTopicWrapper)listWindow.l.getSelectedValue()).topic.getBaseName(); setText(text); } listWindow.hide(); listWindow.dispose(); listWindow=null; } else if(e.getKeyCode()==e.VK_ESCAPE){ listWindow.hide(); listWindow.dispose(); listWindow=null; } else{ e.setSource(listWindow.l); listWindow.l.dispatchEvent(e); } } }*/ }); this.add(field,java.awt.BorderLayout.CENTER); } } public void requestFocusOnField() { field.requestFocusInWindow(); } private void showList(){ if(listWindow!=null){ listWindow.setVisible(false); listWindow.dispose(); } listWindow=new ListWindow(topics,field.getText(),this,owner); if(!listWindow.isVisible()){ listWindow.dispose(); listWindow=null; } } public void hideList(){ if(listWindow!=null){ listWindow.setVisible(false); listWindow.dispose(); listWindow=null; } } public void setText(String text){ field.setText(text); } public JTextField getField(){ return field; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents private void initComponents() { setLayout(new java.awt.BorderLayout()); } // </editor-fold>//GEN-END:initComponents public Object getSelection() throws TopicMapException { if(cbox!=null) { Object o=cbox.getSelectedItem(); if(o instanceof ComboBoxTopicWrapper) return ((ComboBoxTopicWrapper)o).topic; else return o; } else{ String text=field.getText(); for(int i=0;i<topics.length;i++){ String basename = topics[i].getBaseName(); if(basename != null) if(basename.equals(text)) return topics[i]; } if(!editable) return null; else return text; } } // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables } // ----------------------------------------------------------------------------- class ListWindow extends JDialog { public JList l; public Vector data; public ListWindow(Topic[] topics,final String written,TopicSelectList selector,JDialog owner) { super(owner,"",false); final JDialog wnd=this; final TopicSelectList s=selector; final JList list=new JList(); JScrollPane scroller=new JScrollPane(); scroller.setViewportView(list); l=list; data=new Vector(); String prefix=null; for(int i=0;i<topics.length;i++){ try{ if(topics[i].getBaseName()!=null && topics[i].getBaseName().startsWith(written)){ if(prefix==null) prefix=topics[i].getBaseName(); else{ String name=topics[i].getBaseName(); int j; for(j=written.length();j<prefix.length() && j<name.length() && prefix.charAt(j)==name.charAt(j);j++) ; if(j<prefix.length()) prefix=name.substring(0,j); } data.add(new ComboBoxTopicWrapper(topics[i])); } }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } } if(data.size()==0) return; if(prefix!=null && prefix.length()>written.length()) { s.setText(prefix); // s.setText( ((ComboBoxTopicWrapper)data.elementAt(0)).topic.getBaseName() ); return; } list.setListData(data); list.addFocusListener(new java.awt.event.FocusAdapter(){ public void focusLost(java.awt.event.FocusEvent e){ s.hideList(); } }); /* list.addListSelectionListener(new javax.swing.event.ListSelectionListener(){ public void valueChanged(javax.swing.event.ListSelectionEvent e){ if(list.getSelectedIndex()!=-1){ String text=((ComboBoxTopicWrapper)list.getSelectedValue()).topic.getBaseName(); s.setText(text); } } });*/ list.addMouseListener(new java.awt.event.MouseAdapter(){ public void mouseClicked(java.awt.event.MouseEvent e){ if(list.getSelectedIndex()!=-1){ s.hideList(); try{ String text=((ComboBoxTopicWrapper)list.getSelectedValue()).topic.getBaseName(); s.setText(text); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION; s.setText("Exception retrieving name"); } } } }); list.addKeyListener(new java.awt.event.KeyAdapter(){ public void keyReleased(java.awt.event.KeyEvent e){ int key=e.getKeyCode(); switch(key){ case KeyEvent.VK_ENTER: case KeyEvent.VK_SPACE: if(list.getSelectedIndex()!=-1){ s.hideList(); try{ String text=((ComboBoxTopicWrapper)list.getSelectedValue()).topic.getBaseName(); s.setText(text); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION; s.setText("Exception retrieving name"); } } break; case KeyEvent.VK_ESCAPE: s.hideList(); break; case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: case KeyEvent.VK_PAGE_DOWN: case KeyEvent.VK_PAGE_UP: break; default: char c=e.getKeyChar(); s.hideList(); if(c!=e.CHAR_UNDEFINED && !Character.isISOControl(c)){ s.setText(written+c); } break; } } }); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setEnabled(true); this.setUndecorated(true); this.getContentPane().add(scroller); this.pack(); this.setLocation(selector.getLocationOnScreen().x,selector.getLocationOnScreen().y+selector.getHeight()); this.show(); /// this.toFront(); } }
11,657
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
NewTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/NewTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * NewTopicPanel.java * * Created on 29. joulukuuta 2005, 22:04 */ package org.wandora.application.gui; import java.awt.event.KeyEvent; import javax.swing.JDialog; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.utils.Textbox; /** * @author akivela */ public class NewTopicPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private boolean accepted = false; private JDialog parent = null; /** Creates new form NewTopicPanel */ public NewTopicPanel(JDialog parent) { this.parent = parent; initComponents(); if(parent != null) { parent.add(this); parent.setVisible(true); } } public boolean getAccepted() { return accepted; } public String getBasename() { return Textbox.trimExtraSpaces(basenameTextField.getText()); } public String getSI() { return Textbox.trimExtraSpaces(SITextField.getText()); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; fieldPanel = new javax.swing.JPanel(); basenameLabel = new org.wandora.application.gui.simple.SimpleLabel(); basenameTextField = new org.wandora.application.gui.simple.SimpleField(); SILabel = new org.wandora.application.gui.simple.SimpleLabel(); SITextField = new org.wandora.application.gui.simple.SimpleField(); buttonPanel = new javax.swing.JPanel(); dummyPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); fieldPanel.setLayout(new java.awt.GridBagLayout()); basenameLabel.setText("Base name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 5, 2, 5); fieldPanel.add(basenameLabel, gridBagConstraints); basenameTextField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { basenameTextFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 5); fieldPanel.add(basenameTextField, gridBagConstraints); SILabel.setText("Subject identifier"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5); fieldPanel.add(SILabel, gridBagConstraints); SITextField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { SITextFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5); fieldPanel.add(SITextField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(fieldPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(dummyPanel, gridBagConstraints); okButton.setText("Create"); okButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); okButton.setMaximumSize(new java.awt.Dimension(70, 23)); okButton.setMinimumSize(new java.awt.Dimension(70, 23)); okButton.setPreferredSize(new java.awt.Dimension(70, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { accepted(evt); } }); okButton.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { okButtonKeyReleased(evt); } }); buttonPanel.add(okButton, new java.awt.GridBagConstraints()); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelled(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 3, 0, 0); buttonPanel.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void accepted(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_accepted accepted = true; if(parent != null) parent.setVisible(false); }//GEN-LAST:event_accepted private void cancelled(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelled accepted = false; if(parent != null) parent.setVisible(false); }//GEN-LAST:event_cancelled private void basenameTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_basenameTextFieldKeyReleased if(evt.getKeyCode() == KeyEvent.VK_ENTER) { accepted(null); } }//GEN-LAST:event_basenameTextFieldKeyReleased private void SITextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_SITextFieldKeyReleased if(evt.getKeyCode() == KeyEvent.VK_ENTER) { accepted(null); } }//GEN-LAST:event_SITextFieldKeyReleased private void okButtonKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_okButtonKeyReleased if(evt.getKeyCode() == KeyEvent.VK_ENTER) { accepted(null); } }//GEN-LAST:event_okButtonKeyReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel SILabel; private javax.swing.JTextField SITextField; private javax.swing.JLabel basenameLabel; private javax.swing.JTextField basenameTextField; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel dummyPanel; private javax.swing.JPanel fieldPanel; private javax.swing.JButton okButton; // End of variables declaration//GEN-END:variables }
9,244
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraToolTable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/WandoraToolTable.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * * WandoraToolTable.java * * Created on June 17, 2004, 3:35 PM */ package org.wandora.application.gui; import java.awt.Component; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.WandoraToolManager2; import org.wandora.application.WandoraToolManager2.ToolInfo; import org.wandora.application.gui.table.TopicTableSorter; import org.wandora.application.tools.AbstractWandoraTool; import org.wandora.utils.swing.TableSorter; /** * * @author akivela */ public class WandoraToolTable extends JTable implements MouseListener, ActionListener /*, DragSourceListener , DragGestureListener*/ { private static final long serialVersionUID = 1L; private Wandora wandora = null; private Object[] cols = { "Name", "Class", "Types", "Source" }; private int[] colsWidths = { 170, 400, 80, 200 }; private String[] descriptions; private Object[][] data; private TableModel tableModel; private WandoraTool[] tools = null; private Object[] popupStruct = new Object[] { "Info...", "---", "Execute...", "Configure...", "Release tool locks...", "Kill threads...", }; private JPopupMenu toolTableMenu = null; private TableSorter sorter; private MouseEvent mouseEvent; public WandoraToolTable(Wandora w) { this.wandora = w; } public void initialize(WandoraTool[] t) { WandoraToolManager2 toolManager=wandora.getToolManager(); try { if(t == null) return; tools = t; this.setAutoCreateColumnsFromModel(false); descriptions = new String[tools.length]; data = new Object[tools.length][4]; for(int i=0; i<tools.length; i++) { data[i][0]=tools[i].getName(); data[i][1]=tools[i].getClass().getName(); data[i][2]=tools[i].getType().toString(); data[i][3]="unknown"; if(toolManager!=null){ ToolInfo info=toolManager.getToolInfo(tools[i]); if(info!=null) data[i][3]=info.sourceType+":"+info.source; } descriptions[i] = tools[i].getDescription(); } tableModel = new ToolTableModel(); sorter = new TopicTableSorter(tableModel); sorter.setTableHeader(this.getTableHeader()); this.setModel(sorter); this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); this.setRowSelectionAllowed(true); this.setColumnSelectionAllowed(false); for(int i=0; i<cols.length; i++) { this.addColumn(new TableColumn(i,colsWidths[i],new ToolTableCellRenderer(),null)); } this.addMouseListener(this); toolTableMenu = UIBox.makePopupMenu(popupStruct, this); this.setComponentPopupMenu(toolTableMenu); } catch(Exception e) { if(wandora != null) wandora.handleError(e); else e.printStackTrace(); } } public WandoraTool getSelectedTool() { int row = this.getSelectedRow(); if(row >= 0 && row < tools.length) { return tools[mapRowIndexToModel(row)]; } return null; } public WandoraTool getToolAt(MouseEvent e) { return getToolAt(e.getPoint()); } public WandoraTool getToolAt(int x, int y) { return getToolAt(new Point(x,y)); } public WandoraTool getToolAt(Point point) { int row=rowAtPoint(point); return tools[mapRowIndexToModel(row)]; } public int mapRowIndexToModel(int row){ //return row; return sorter.modelIndex(row); } public int mapRowIndexToView(int row){ //return row; return sorter.viewIndex(row); } // ------------------------------------------------------------------------- @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; if(mouseEvent.getClickCount()>=2){ WandoraToolManager2 toolManager=wandora.getToolManager(); ToolInfo info=null; WandoraTool tool=getToolAt(mouseEvent); if(toolManager!=null) info=toolManager.getToolInfo(tool); new WandoraToolInfoDialog(wandora, tool, info); } } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } @Override public void actionPerformed(ActionEvent e) { // System.out.println("Action event == "+e.getActionCommand()); String c = e.getActionCommand(); if(c == null) return; c = c.toLowerCase(); // ***** EXECUTE ***** if(c.startsWith("execute")) { try { WandoraTool t = getSelectedTool(); if(t != null) { t.execute(wandora); } } catch(Exception ex) { ex.printStackTrace(); } catch(Error er) { er.printStackTrace(); } } // ***** CONFIGURE ***** else if(c.startsWith("configure")) { try { WandoraTool t = getSelectedTool(); if(t != null) { if(t.isConfigurable()) { t.configure(wandora, wandora.getOptions(), wandora.getToolManager().getOptionsPrefix(t)); } else { WandoraOptionPane.showMessageDialog(wandora, "Tool is not configurable!", "Not configurable"); } } } catch(Exception ex) { ex.printStackTrace(); } catch(Error er) { er.printStackTrace(); } } // ***** RELEASE TOOL LOCKS ***** else if(c.startsWith("release tool locks")) { try { WandoraTool t = getSelectedTool(); if(t != null) { String className = t.getClass().getSimpleName(); if(t instanceof AbstractWandoraTool && !((AbstractWandoraTool) t).allowMultipleInvocations()) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Are you sure you want to release tool lock for class '"+className+"'", "Release tool lock"); if(a == WandoraOptionPane.YES_OPTION) { boolean released = ((AbstractWandoraTool) t).clearToolLock(); if(!released) WandoraOptionPane.showMessageDialog(wandora, "Tool class '"+className+"' was not locked. Couldn't release tool locks."); } } else { WandoraOptionPane.showMessageDialog(wandora, "Tool class '"+className+"' doesn't support tool locks. Can't release tool locks."); } } } catch(Exception ex) { ex.printStackTrace(); } catch(Error er) { er.printStackTrace(); } } // ***** KILL TOOL THREADS ***** else if(c.startsWith("kill threads")) { try { WandoraTool t = getSelectedTool(); if(t != null) { String className = t.getClass().getSimpleName(); if(t instanceof AbstractWandoraTool && ((AbstractWandoraTool) t).runInOwnThread()) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Are you sure you want to interrupt tool threads for class '"+className+"'", "Interrupt tool threads"); if(a == WandoraOptionPane.YES_OPTION) { ((AbstractWandoraTool) t).interruptThreads(); } } else { WandoraOptionPane.showMessageDialog(wandora, "Tool class '"+className+"' doesn't support interrups. Can't kill tool threads."); } } } catch(Exception ex) { ex.printStackTrace(); } catch(Error er) { er.printStackTrace(); } } // ***** TOOL INFO ***** else if(c.startsWith("info")) { try { WandoraTool t = getSelectedTool(); if(t != null) { WandoraToolManager2 toolManager=wandora.getToolManager(); ToolInfo info=null; if(toolManager!=null) info=toolManager.getToolInfo(t); new WandoraToolInfoDialog(wandora, t, info); } } catch(Exception ex) { ex.printStackTrace(); } } } // ------------------------------------------------------------------------- // ------------------------------------------------------ ToolTableModel --- // ------------------------------------------------------------------------- protected class ToolTableModel extends AbstractTableModel { @Override public int getColumnCount() { if(cols != null) return cols.length; return 0; } @Override public int getRowCount() { if(data != null) return data.length; return 0; } @Override public Object getValueAt(int rowIndex, int columnIndex) { try { if(data != null && rowIndex >= 0 && columnIndex >= 0) { return data[rowIndex][columnIndex]; } } catch (Exception e) { if(wandora != null) wandora.handleError(e); else e.printStackTrace(); } return null; } @Override public String getColumnName(int columnIndex){ try { if(cols != null && columnIndex >= 0 && cols.length > columnIndex && cols[columnIndex] != null) { return cols[columnIndex].toString(); } return ""; } catch (Exception e) { if(wandora != null) wandora.handleError(e); e.printStackTrace(); } return "ERROR"; } @Override public boolean isCellEditable(int row,int col){ return false; } } // ------------------------------------------------------------------------- public class ToolTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer { @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if(c instanceof JLabel) { JLabel l = (JLabel) c; if(column == 0) { l.setIcon(tools[mapRowIndexToModel(row)].getIcon()); } //l.setToolTipText(Textbox.makeHTMLParagraph(descriptions[row], 40)); } return c; } } // ------------------------------------------------------------------------- public class ToolTableSorter extends TableSorter { public ToolTableSorter() { super(); } public ToolTableSorter(TableModel tableModel) { super(tableModel); } public ToolTableSorter(TableModel tableModel, JTableHeader tableHeader) { super(tableModel, tableHeader); } } }
14,191
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RegularExpressionEditor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/RegularExpressionEditor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * RegularExpressionEditor.java * * Created on 2. joulukuuta 2004, 11:49 */ package org.wandora.application.gui; import java.awt.Color; import java.awt.Container; import java.awt.Cursor; import java.awt.event.ActionListener; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.swing.JFileChooser; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; import org.wandora.application.gui.simple.SimpleComboBox; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleTextPane; import org.wandora.utils.EasyReplaceExpression; import org.wandora.utils.IObox; import org.wandora.utils.Options; /** * * @author akivela */ public class RegularExpressionEditor extends javax.swing.JDialog implements ActionListener { private static final long serialVersionUID = 1L; public static final String OPTIONS_PREFIX = "regexp."; public static final String DEFAULT_PATTERN_NAME = "User expression"; public static Color TEST_ERROR = new Color(255,220,220); public static Color TEST_MATCH = new Color(220,255,220); public static Color TEST_MISMATCH = new Color(240,220,220); private Wandora wandora; private HashMap<String,EasyReplaceExpression> patterns; public boolean approve; private EasyReplaceExpression originalPattern; private static RegularExpressionEditor editor = null; private static RegularExpressionEditor matchEditor = null; public RegularExpressionEditor() { this(null); } /** Creates new form RegularExpressionEditor */ public RegularExpressionEditor(Wandora w) { super(w, true); this.wandora = w; patterns = new LinkedHashMap<>(); if(wandora != null) { parsePatternOptions(wandora.options); //setIconImage(wandora.getIconImage()); } originalPattern = null; initGui(); refresh(); } // ------------------------------------------------------------------------- // RegularExpressionEditor should be used as singleton! // Instead of creating new instances of RegularExpressionEditor you should // get RegularExpressionEditor instance with next! // ------------------------------------------------------------------------- public static RegularExpressionEditor getReplaceExpressionEditor(Wandora w) { if(editor == null) { editor = new RegularExpressionEditor(w); } return editor; } public static RegularExpressionEditor getMatchExpressionEditor(Wandora w) { if(matchEditor == null) { matchEditor = new RegularExpressionEditor(w); matchEditor.replacementLabel.setVisible(false); matchEditor.replacementScrollPane.setVisible(false); matchEditor.setTitle("Regular expressions matcher"); } return matchEditor; } public void initGui() { initComponents(); nameComboBox.setEditable(false); initPatternsComboBox(); } public void initPatternsComboBox() { ((SimpleComboBox) nameComboBox).setOptions(patterns.keySet()); } @Override public void setVisible(boolean v) { if(v == true) { refresh(); approve = false; } super.setVisible(v); } public void refresh() { if(wandora != null) { wandora.centerWindow(this); } } @Override public Container getParent() { return wandora; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); matchCheckBox = new SimpleCheckBox(); caseSensitivityCheckBox = new SimpleCheckBox(); jPanel4 = new javax.swing.JPanel(); nameLabel = new SimpleLabel(); nameComboBox = new SimpleComboBox(); patternLabel = new SimpleLabel(); regexScrollPane = new javax.swing.JScrollPane(); regexPane = new SimpleTextPane(); replacementLabel = new SimpleLabel(); replacementScrollPane = new javax.swing.JScrollPane(); replacementPane = new SimpleTextPane(); buttonPanel = new javax.swing.JPanel(); applyButton = new SimpleButton(); cancelButton = new SimpleButton(); testPanel = new javax.swing.JPanel(); testStringLabel = new SimpleLabel(); testStringScrollPane = new javax.swing.JScrollPane(); testStringPane = new SimpleTextPane(); testButtonPanel = new javax.swing.JPanel(); javax.swing.JButton testButton = new SimpleButton(); testResultLabel = new SimpleLabel(); testResultScrollPane = new javax.swing.JScrollPane(); testResultPane = new SimpleTextPane(); jMenuBar1 = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); newMenuItem = new javax.swing.JMenuItem(); storeExpressionMenuItem = new javax.swing.JMenuItem(); jSeparator1 = new javax.swing.JSeparator(); loadMenuItem = new javax.swing.JMenuItem(); saveMenuItem = new javax.swing.JMenuItem(); deleteMenuItem = new javax.swing.JMenuItem(); jSeparator2 = new javax.swing.JSeparator(); cancelMenuItem = new javax.swing.JMenuItem(); setTitle("Regular expression replacer"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); getContentPane().setLayout(new java.awt.GridBagLayout()); jPanel1.setMinimumSize(new java.awt.Dimension(200, 300)); jPanel1.setPreferredSize(new java.awt.Dimension(290, 490)); jPanel1.setLayout(new java.awt.GridBagLayout()); jPanel2.setMinimumSize(new java.awt.Dimension(100, 20)); jPanel2.setPreferredSize(new java.awt.Dimension(100, 20)); jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 0, 0)); matchCheckBox.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont); matchCheckBox.setText("Full match"); matchCheckBox.setToolTipText("If selected regular expression must fully match the string"); matchCheckBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); jPanel2.add(matchCheckBox); caseSensitivityCheckBox.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont); caseSensitivityCheckBox.setText("Case insensitivity"); caseSensitivityCheckBox.setToolTipText("Case sensitive / Case insensitive"); caseSensitivityCheckBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); jPanel2.add(caseSensitivityCheckBox); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; jPanel1.add(jPanel2, gridBagConstraints); jPanel4.setLayout(new java.awt.GridBagLayout()); nameLabel.setText("Regular expression name"); nameLabel.setMinimumSize(new java.awt.Dimension(100, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0); jPanel4.add(nameLabel, gridBagConstraints); nameComboBox.setPreferredSize(new java.awt.Dimension(400, 20)); nameComboBox.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); nameComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { comboBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; jPanel4.add(nameComboBox, gridBagConstraints); patternLabel.setText("Regular expression"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 0); jPanel4.add(patternLabel, gridBagConstraints); regexScrollPane.setPreferredSize(new java.awt.Dimension(400, 75)); regexScrollPane.setViewportView(regexPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel4.add(regexScrollPane, gridBagConstraints); replacementLabel.setText("Replacement"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 0); jPanel4.add(replacementLabel, gridBagConstraints); replacementScrollPane.setPreferredSize(new java.awt.Dimension(400, 75)); replacementScrollPane.setViewportView(replacementPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel4.add(replacementScrollPane, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; jPanel1.add(jPanel4, gridBagConstraints); buttonPanel.setPreferredSize(new java.awt.Dimension(400, 33)); buttonPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 3, 4)); applyButton.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont); applyButton.setText("Apply"); applyButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); applyButton.setMaximumSize(new java.awt.Dimension(70, 23)); applyButton.setMinimumSize(new java.awt.Dimension(70, 23)); applyButton.setPreferredSize(new java.awt.Dimension(70, 23)); applyButton.addActionListener(this); buttonPanel.add(applyButton); cancelButton.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(this); buttonPanel.add(cancelButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; jPanel1.add(buttonPanel, gridBagConstraints); testPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); testPanel.setPreferredSize(new java.awt.Dimension(384, 190)); testPanel.setLayout(new java.awt.GridBagLayout()); testStringLabel.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont); testStringLabel.setText("Test string"); testStringLabel.setPreferredSize(new java.awt.Dimension(150, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 4, 0, 4); testPanel.add(testStringLabel, gridBagConstraints); testStringScrollPane.setPreferredSize(new java.awt.Dimension(380, 50)); testStringScrollPane.setViewportView(testStringPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4); testPanel.add(testStringScrollPane, gridBagConstraints); testButtonPanel.setPreferredSize(new java.awt.Dimension(150, 33)); testButtonPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 3, 3)); testButton.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont); testButton.setText("Test regular expression"); testButton.setMargin(new java.awt.Insets(2, 4, 2, 4)); testButton.setMaximumSize(new java.awt.Dimension(57, 21)); testButton.setMinimumSize(new java.awt.Dimension(150, 20)); testButton.setPreferredSize(new java.awt.Dimension(150, 20)); testButton.addActionListener(this); testButtonPanel.add(testButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4); testPanel.add(testButtonPanel, gridBagConstraints); testResultLabel.setFont(org.wandora.application.gui.UIConstants.buttonLabelFont); testResultLabel.setText("Test result"); testResultLabel.setPreferredSize(new java.awt.Dimension(150, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 4, 0, 4); testPanel.add(testResultLabel, gridBagConstraints); testResultScrollPane.setPreferredSize(new java.awt.Dimension(380, 70)); testResultScrollPane.setViewportView(testResultPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); testPanel.add(testResultScrollPane, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.ipadx = 10; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(15, 0, 0, 0); jPanel1.add(testPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.ipadx = 15; gridBagConstraints.ipady = 15; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 6, 5, 6); getContentPane().add(jPanel1, gridBagConstraints); fileMenu.setText("File"); fileMenu.setFont(org.wandora.application.gui.UIConstants.menuFont); newMenuItem.setFont(org.wandora.application.gui.UIConstants.menuFont); newMenuItem.setText("New expression"); newMenuItem.addActionListener(this); fileMenu.add(newMenuItem); storeExpressionMenuItem.setFont(org.wandora.application.gui.UIConstants.menuFont); storeExpressionMenuItem.setText("Store current expression..."); storeExpressionMenuItem.addActionListener(this); fileMenu.add(storeExpressionMenuItem); fileMenu.add(jSeparator1); loadMenuItem.setFont(org.wandora.application.gui.UIConstants.menuFont); loadMenuItem.setText("Import expressions..."); loadMenuItem.addActionListener(this); fileMenu.add(loadMenuItem); saveMenuItem.setFont(org.wandora.application.gui.UIConstants.menuFont); saveMenuItem.setText("Export expressions..."); saveMenuItem.addActionListener(this); fileMenu.add(saveMenuItem); deleteMenuItem.setFont(org.wandora.application.gui.UIConstants.menuFont); deleteMenuItem.setText("Delete all expressions..."); deleteMenuItem.addActionListener(this); fileMenu.add(deleteMenuItem); fileMenu.add(jSeparator2); cancelMenuItem.setFont(org.wandora.application.gui.UIConstants.menuFont); cancelMenuItem.setText("Close"); cancelMenuItem.addActionListener(this); fileMenu.add(cancelMenuItem); jMenuBar1.add(fileMenu); setJMenuBar(jMenuBar1); pack(); }// </editor-fold>//GEN-END:initComponents private void comboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboBoxActionPerformed selectPattern(); }//GEN-LAST:event_comboBoxActionPerformed /** Exit the Application */ private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm tryExit(); }//GEN-LAST:event_exitForm /** * @param args the command line arguments */ public static void main(String args[]) { new RegularExpressionEditor().setVisible(true); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c == null) return; System.out.println("Regular expression editor action command: " +c); if("New expression".equalsIgnoreCase(c)) { this.regexPane.setText(""); this.replacementPane.setText(""); this.testStringPane.setText(""); this.testResultPane.setText(""); testResultPane.setBackground(new Color(255,255,255)); } else if("Cancel".equalsIgnoreCase(c) || "Exit".equalsIgnoreCase(c) || "Close".equalsIgnoreCase(c)) { approve = false; tryExit(); } else if("Apply".equalsIgnoreCase(c)) { approve = true; tryExit(); } else if("Store current expression...".equalsIgnoreCase(c)) { savePattern(); } else if(c.startsWith("Test")) { testPattern(); } else if("Import expressions...".equalsIgnoreCase(c)) { importPatterns(); } else if("Export expressions...".equalsIgnoreCase(c)) { exportPatterns(); } else if("Delete all expressions...".equalsIgnoreCase(c)) { patterns = new LinkedHashMap<>(); wandora.options.removeAll(OPTIONS_PREFIX); initPatternsComboBox(); } } public void tryExit() { if(wandora != null) { this.savePatternsToOptions(wandora.options); } this.setVisible(false); } public void show(Object o, int column, EasyReplaceExpression pattern, boolean isAnd) { originalPattern = pattern; approve = false; if(pattern != null) { String name = pattern.getName(); if(name == null) name = DEFAULT_PATTERN_NAME; if(patterns.isEmpty() || !patterns.containsKey(name)) { patterns.put(name, pattern); ((SimpleComboBox) nameComboBox).setOptions(patterns.keySet()); } nameComboBox.setSelectedItem(name); caseSensitivityCheckBox.setSelected(!pattern.isCaseInsensitive()); matchCheckBox.setSelected(!pattern.findInsteadMatch()); regexPane.setText(pattern.getPatternString()); } //andCheckBox.setSelected(isAnd); this.setVisible(false); } public boolean findInsteadMatch() { if(matchCheckBox.isSelected()) return false; else return true; } // --- THE REPLACER -------------------------------------------------------- public String replace(String target) { try { if(target != null && target.length() > 0) { //System.out.println("Replacing " + regexPane.getText() + " with " + replacementPane.getText()); int flags = 0; if(caseSensitivityCheckBox.isSelected()) flags |= Pattern.CASE_INSENSITIVE; Pattern pattern = Pattern.compile(regexPane.getText(), flags); Matcher matcher = pattern.matcher(target); boolean match = false; if(!matchCheckBox.isSelected() == true) { match = matcher.find(); } else { match = matcher.matches(); } if(match) { return matcher.replaceAll(replacementPane.getText()); } } } catch(Exception e) { e.printStackTrace(); } return null; } public boolean matches(String target) { try { if(target != null && target.length() > 0) { //System.out.println("Replacing " + regexPane.getText() + " with " + replacementPane.getText()); int flags = 0; if(caseSensitivityCheckBox.isSelected()) flags |= Pattern.CASE_INSENSITIVE; Pattern pattern = Pattern.compile(regexPane.getText(), flags); Matcher matcher = pattern.matcher(target); if(!matchCheckBox.isSelected() == true) { return matcher.find(); } else { return matcher.matches(); } } } catch(Exception e) { e.printStackTrace(); } return false; } // --- HANDLE PATTERNS ----------------------------------------------------- public EasyReplaceExpression getCurrentPattern() { if(approve == true) { try { Pattern p = Pattern.compile(regexPane.getText()); // TRYING String name = (String) nameComboBox.getSelectedItem(); if(name == null) name = DEFAULT_PATTERN_NAME; return new EasyReplaceExpression((String) nameComboBox.getSelectedItem(), regexPane.getText(), replacementPane.getText(), !matchCheckBox.isSelected(), !caseSensitivityCheckBox.isSelected()); } catch (Exception e) { testResultPane.setBackground(TEST_ERROR); testResultPane.setText("Syntax error in regular expression!\n\n" + e.toString()); return null; } } else { return originalPattern; } } public void selectPattern() { try { if(nameComboBox.getSelectedItem() != null) { EasyReplaceExpression currentPattern = patterns.get(nameComboBox.getSelectedItem().toString()); if(currentPattern != null) { regexPane.setText(currentPattern.getPatternString()); replacementPane.setText(currentPattern.getReplacementString()); matchCheckBox.setSelected(!currentPattern.findInsteadMatch()); caseSensitivityCheckBox.setSelected(!currentPattern.isCaseInsensitive()); } } } catch (Exception e) { e.printStackTrace(); } } public void savePattern() { String n = "New pattern"; if(nameComboBox.getSelectedItem() != null) n = nameComboBox.getSelectedItem().toString(); String patternNameString=WandoraOptionPane.showInputDialog(this, "Enter name for the regular expression", n); String patternString = regexPane.getText(); if(patternNameString != null && patternNameString.length() > 0) { if(patternString != null && patternString.length() > 0) { try { Pattern p = Pattern.compile(regexPane.getText()); // TESTING! EasyReplaceExpression kp = new EasyReplaceExpression(patternNameString, regexPane.getText(), replacementPane.getText(), !matchCheckBox.isSelected(), !caseSensitivityCheckBox.isSelected()); patterns.put(patternNameString, kp); initPatternsComboBox(); nameComboBox.setSelectedItem(patternNameString); } catch (Exception e) { testResultPane.setBackground(TEST_ERROR); testResultPane.setText("Storing regular expression failed! Syntax error in regular expression!\n\n" + e.toString()); } } else { if(patterns.get(patternString) != null) patterns.remove(patternString); } } } public void testPattern() { String patternString = regexPane.getText(); String replacement = replacementPane.getText(); String testString = testStringPane.getText(); if(patternString != null && patternString.length() > 0) { if(testString != null && testString.length() > 0) { try { int flags = 0; if(caseSensitivityCheckBox.isSelected()) flags |= Pattern.CASE_INSENSITIVE; Pattern pattern = Pattern.compile(patternString, flags); Matcher matcher = pattern.matcher(testString); boolean match = false; if(!matchCheckBox.isSelected() == true) { match = matcher.find(); } else { match = matcher.matches(); } if(match) { testResultPane.setBackground(TEST_MATCH); testResultPane.setText(matcher.replaceAll(replacement)); } else { testResultPane.setBackground(TEST_MISMATCH); testResultPane.setText("Tested string does not match regular expression!"); } } catch (PatternSyntaxException pse) { testResultPane.setBackground(TEST_ERROR); StringWriter sw = new StringWriter(); pse.printStackTrace(new PrintWriter(sw)); testResultPane.setBackground(TEST_ERROR); testResultPane.setText("Syntax error in regular expression!\n\n" + sw.toString()); } catch (Exception e) { testResultPane.setBackground(TEST_ERROR); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); testResultPane.setText(sw.toString()); } } else { testResultPane.setBackground(TEST_ERROR); testResultPane.setText("String to be tested is empty!"); } } else { testResultPane.setBackground(TEST_ERROR); testResultPane.setText("Regular expression is empty!"); } } // --- IMPORT PATTERNS ----------------------------------------------------- public void importPatterns() { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle("Loading regular expressions"); chooser.setApproveButtonText("Load"); chooser.setFileSelectionMode(SimpleFileChooser.FILES_ONLY); if(chooser.open(wandora) == SimpleFileChooser.APPROVE_OPTION) { importPatterns(chooser.getSelectedFile()); initPatternsComboBox(); } } public void importPatterns(File file) { patterns = new LinkedHashMap<>(); mergePatterns(file); } public void mergePatterns(File file) { if(file != null) { try { String s = IObox.loadFile(file); parsePatterns(s); } catch (Exception e) { e.printStackTrace(); } } } public void importPatterns(String resourceName) { patterns = new LinkedHashMap<>(); mergePatterns(resourceName); } public void mergePatterns(String resourceName) { if(resourceName != null) { try { String s = IObox.loadResource(resourceName); parsePatterns(s); } catch (Exception e) { e.printStackTrace(); } } } public void parsePatterns(String s) { if(s != null) { try { StringTokenizer lines = new StringTokenizer(s, "\n"); while(lines.hasMoreTokens()) { String line = lines.nextToken(); StringTokenizer parts = new StringTokenizer(line, "\t"); if(parts.countTokens()>4) { String name = parts.nextToken(); String pattern = parts.nextToken(); String replacement = parts.nextToken(); String findInstead = parts.nextToken(); String caseSensitivity = parts.nextToken(); if(name != null && name.length() > 0 && pattern != null && pattern.length() > 0) { patterns.put(name, new EasyReplaceExpression(name, pattern, replacement, "true".equalsIgnoreCase(findInstead), "true".equalsIgnoreCase(caseSensitivity))); } } else { System.out.println("Rejecting pattern!"); } } } catch (Exception e) { e.printStackTrace(); } } } public void parsePatternOptions(Options opts) { if(opts != null) { boolean noRejects = true; int i=0; try { while(noRejects) { String name = opts.get(OPTIONS_PREFIX+"expression["+i+"].name"); String pattern = opts.get(OPTIONS_PREFIX+"expression["+i+"].pattern"); String replacement = opts.get(OPTIONS_PREFIX+"expression["+i+"].replacement"); String findInstead = opts.get(OPTIONS_PREFIX+"expression["+i+"].partialMatch"); String caseSensitivity = opts.get(OPTIONS_PREFIX+"expression["+i+"].caseSensitive"); if(name != null && name.length() > 0 && pattern != null && pattern.length() > 0) { patterns.put(name, new EasyReplaceExpression(name, pattern, replacement, "true".equalsIgnoreCase(findInstead), "true".equalsIgnoreCase(caseSensitivity))); } else { //System.out.println("Rejecting pattern!"); noRejects = false; } i++; } } catch (Exception e) { e.printStackTrace(); } } } public void savePatternsToOptions(Options opts) { if(opts != null) { int i = 0; for(String key : patterns.keySet()) { try { EasyReplaceExpression kp = (EasyReplaceExpression) patterns.get(key); opts.put(OPTIONS_PREFIX+"expression["+i+"].name", kp.getName()); opts.put(OPTIONS_PREFIX+"expression["+i+"].pattern", kp.getPatternString()); opts.put(OPTIONS_PREFIX+"expression["+i+"].replacement", kp.getReplacementString()); opts.put(OPTIONS_PREFIX+"expression["+i+"].partialMatch", kp.findInsteadMatch() ? "true" : "false"); opts.put(OPTIONS_PREFIX+"expression["+i+"].caseSensitive", kp.isCaseInsensitive() ? "true" : "false"); i++; } catch (Exception ex) { System.out.println(ex); } } } } // --- EXPORT PATTERNS ----------------------------------------------------- public void exportPatterns() { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle("Saving regular expressions"); chooser.setApproveButtonText("Save"); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); if(chooser.open(wandora, SimpleFileChooser.SAVE_DIALOG) == SimpleFileChooser.APPROVE_OPTION) { exportPatterns(chooser.getSelectedFile()); } } public void exportPatterns(File file) { try { IObox.saveFile(file, patterns2String()); } catch (Exception e) { System.out.println(e); } } public String patterns2String() { StringBuilder sb = new StringBuilder(""); for(String key : patterns.keySet()) { try { EasyReplaceExpression kp = patterns.get(key); sb.append(key).append("\t").append(kp.getPatternString()).append("\t").append(kp.getReplacementString()).append("\t").append(kp.findInsteadMatch()).append("\t").append(kp.isCaseInsensitive()); sb.append("\n"); } catch (Exception ex) { System.out.println(ex); } } return sb.toString(); } // ------------------------------------------------------------------------- // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton applyButton; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JMenuItem cancelMenuItem; private javax.swing.JCheckBox caseSensitivityCheckBox; private javax.swing.JMenuItem deleteMenuItem; private javax.swing.JMenu fileMenu; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JMenuItem loadMenuItem; private javax.swing.JCheckBox matchCheckBox; private javax.swing.JComboBox nameComboBox; private javax.swing.JLabel nameLabel; private javax.swing.JMenuItem newMenuItem; private javax.swing.JLabel patternLabel; private javax.swing.JTextPane regexPane; private javax.swing.JScrollPane regexScrollPane; private javax.swing.JLabel replacementLabel; private javax.swing.JTextPane replacementPane; private javax.swing.JScrollPane replacementScrollPane; private javax.swing.JMenuItem saveMenuItem; private javax.swing.JMenuItem storeExpressionMenuItem; private javax.swing.JPanel testButtonPanel; private javax.swing.JPanel testPanel; private javax.swing.JLabel testResultLabel; private javax.swing.JTextPane testResultPane; private javax.swing.JScrollPane testResultScrollPane; private javax.swing.JLabel testStringLabel; private javax.swing.JTextPane testStringPane; private javax.swing.JScrollPane testStringScrollPane; // End of variables declaration//GEN-END:variables }
38,166
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicsOfTypeSelector.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/TopicsOfTypeSelector.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicsOfTypeSelector.java * * Created on 9.7.2007, 13:56 */ package org.wandora.application.gui; import java.awt.Component; import java.util.Collection; import javax.swing.DefaultListModel; import org.wandora.topicmap.SchemaBox; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class TopicsOfTypeSelector extends javax.swing.JPanel implements TopicSelector, Runnable { private static final long serialVersionUID = 1L; private DefaultListModel listModel; private Topic typeTopic; private Thread thread; private boolean running; private Collection<Topic> topicsOfType; private long lastTyped=0; private long lastPopulated=0; private String name; private boolean forcePopulate=false; private boolean useSchema; /** Creates new form TopicsOfTypeSelector */ public TopicsOfTypeSelector(Topic typeTopic) { this(typeTopic,null,true); } public TopicsOfTypeSelector(Topic typeTopic,String name) { this(typeTopic,name,true); } public TopicsOfTypeSelector(Topic typeTopic,String name,boolean useSchema) { this.typeTopic=typeTopic; if(name==null) { try{ this.name=typeTopic.getDisplayName("en"); }catch(TopicMapException tme){tme.printStackTrace();} } else this.name=name; this.useSchema=useSchema; listModel=new DefaultListModel(); initComponents(); textField.setFocusTraversalKeysEnabled(false); } private void populateList(){ // listModel.clear(); DefaultListModel newModel=new DefaultListModel(); String written=textField.getText().toLowerCase(); try{ for(Topic t : topicsOfType){ String bn=t.getBaseName(); if(bn==null) continue; if(bn.toLowerCase().startsWith(written)){ newModel.addElement(new ListWrapper(t)); } } } catch(TopicMapException tme){tme.printStackTrace();} list.setModel(newModel); } public void init() { thread=new Thread(this); running=true; thread.start(); } public String getSelectorName() { return name; } public Topic[] getSelectedTopics() { Topic t=getSelectedTopic(); if(t==null) return new Topic[0]; else return new Topic[]{t}; } public Topic getSelectedTopic() { return ((ListWrapper)list.getSelectedValue()).t; } public Component getPanel() { return this; } public void cleanup() { running=false; } public void run() { try{ Collection<Topic> temp; if(useSchema) temp=SchemaBox.getInstancesOf(typeTopic); else temp=typeTopic.getTopicMap().getTopicsOfType(typeTopic); topicsOfType=TMBox.sortTopics(temp,null); if(topicsOfType.size()<100) forcePopulate=true; }catch(TopicMapException tme){tme.printStackTrace();} while(running){ long delay=0; long t=System.currentTimeMillis(); if( (lastTyped>0 && t>=lastTyped+1000 && lastPopulated<lastTyped && textField.getText().length()>=3) || forcePopulate){ forcePopulate=false; populateList(); lastPopulated=t; } else if(lastTyped>0 && lastPopulated<lastTyped && textField.getText().length()>=3){ delay=lastTyped+1000-t; } synchronized(this){ try{ if(delay==0) this.wait(); else this.wait(delay); }catch(InterruptedException ie){} } } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; textField = new javax.swing.JTextField(); scrollPane = new javax.swing.JScrollPane(); list = new javax.swing.JList(); findButton = new org.wandora.application.gui.simple.SimpleButton(); setLayout(new java.awt.GridBagLayout()); textField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { textFieldKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { textFieldKeyTyped(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 2); add(textField, gridBagConstraints); list.setFont(UIConstants.smallButtonLabelFont); list.setModel(listModel); list.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { listKeyReleased(evt); } }); scrollPane.setViewportView(list); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 4); add(scrollPane, gridBagConstraints); findButton.setText("Find"); findButton.setMargin(new java.awt.Insets(0, 2, 0, 2)); findButton.setMaximumSize(new java.awt.Dimension(50, 19)); findButton.setMinimumSize(new java.awt.Dimension(50, 19)); findButton.setPreferredSize(new java.awt.Dimension(50, 19)); findButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { findButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(4, 0, 4, 4); add(findButton, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void listKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_listKeyReleased if(evt.getKeyCode()==evt.VK_ENTER){ // select topic and close dialog // current topic selector doesn't have a mechanism to close the dialog } }//GEN-LAST:event_listKeyReleased private void textFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldKeyReleased if(evt.getKeyCode()==evt.VK_DOWN){ if(listModel.size()>0){ list.setSelectedIndex(0); list.requestFocus(); } } else if(evt.getKeyCode()==evt.VK_UP){ if(listModel.size()>0){ list.setSelectedIndex(listModel.size()-1); list.requestFocus(); } } else if(evt.getKeyCode()==evt.VK_TAB){ forcePopulate=true; synchronized(this){ this.notifyAll(); } } }//GEN-LAST:event_textFieldKeyReleased private void findButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_findButtonActionPerformed forcePopulate=true; synchronized(this){ this.notifyAll(); } }//GEN-LAST:event_findButtonActionPerformed private void textFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldKeyTyped lastTyped=System.currentTimeMillis(); synchronized(this){ this.notifyAll(); } }//GEN-LAST:event_textFieldKeyTyped // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton findButton; private javax.swing.JList list; private javax.swing.JScrollPane scrollPane; private javax.swing.JTextField textField; // End of variables declaration//GEN-END:variables private static class ListWrapper{ public Topic t; public ListWrapper(Topic t){this.t=t;}; public String toString(){ try{ String r=t.getBaseName(); if(r!=null) return r; else return t.getOneSubjectIdentifier().toExternalForm(); }catch(TopicMapException tme){tme.printStackTrace(); return "Exception";} } } }
9,768
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Clipboardable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/Clipboardable.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * Clipboardable.java * * Created on 9. marraskuuta 2005, 19:10 * */ package org.wandora.application.gui; /** * * @author akivela */ public interface Clipboardable { public void copy(); public void cut(); public void paste(); }
1,050
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PasswordPrompt.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/PasswordPrompt.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * PasswordPrompt.java * * Created on July 19, 2004, 12:41 PM */ package org.wandora.application.gui; import javax.swing.Icon; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; /** * * @author olli, ak */ public class PasswordPrompt extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private boolean cancelled; public static Icon lockIcon = UIBox.getIcon("gui/icons/dialog/lock.gif"); /** Creates new form PasswordPrompt */ public PasswordPrompt(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); cancelled=false; if(parent.isVisible()) { this.setLocation(parent.getLocation().x+parent.getWidth()/2-this.getWidth()/2, parent.getLocation().y+parent.getHeight()/2-this.getHeight()/2); } else { UIBox.centerScreen(this); } this.setAlwaysOnTop(true); } public void setLabelText(String str) { this.passwordInfoLabel.setText(str); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; fieldPanel = new javax.swing.JPanel(); passwordFieldPanel = new javax.swing.JPanel(); usernameLabel = new SimpleLabel(); passwordLabel2 = new SimpleLabel(); usernameField = new SimpleField(); passwordField = new javax.swing.JPasswordField(); passwordLabelPanel = new javax.swing.JPanel(); passwordInfoLabel = new SimpleLabel(); iconPanel = new javax.swing.JPanel(); iconLabel = new javax.swing.JLabel(); passwordButtonPanel = new javax.swing.JPanel(); passwordDummyPanel = new javax.swing.JPanel(); okButton = new SimpleButton(); cancelButton = new SimpleButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); getContentPane().setLayout(new java.awt.GridBagLayout()); fieldPanel.setLayout(new java.awt.GridBagLayout()); passwordFieldPanel.setMinimumSize(new java.awt.Dimension(300, 50)); passwordFieldPanel.setLayout(new java.awt.GridBagLayout()); usernameLabel.setText("Username"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0); passwordFieldPanel.add(usernameLabel, gridBagConstraints); passwordLabel2.setText("Password"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; passwordFieldPanel.add(passwordLabel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 2, 0); passwordFieldPanel.add(usernameField, gridBagConstraints); passwordField.setMargin(new java.awt.Insets(2, 2, 2, 3)); passwordField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { passwordFieldKeyPressed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); passwordFieldPanel.add(passwordField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 0); fieldPanel.add(passwordFieldPanel, gridBagConstraints); passwordLabelPanel.setMinimumSize(new java.awt.Dimension(220, 20)); passwordLabelPanel.setPreferredSize(new java.awt.Dimension(220, 20)); passwordLabelPanel.setLayout(new java.awt.BorderLayout()); passwordInfoLabel.setText("Enter username and password to access URL:"); passwordInfoLabel.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM); passwordInfoLabel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); passwordLabelPanel.add(passwordInfoLabel, java.awt.BorderLayout.CENTER); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0); fieldPanel.add(passwordLabelPanel, gridBagConstraints); iconLabel.setMaximumSize(new java.awt.Dimension(65, 65)); iconLabel.setMinimumSize(new java.awt.Dimension(65, 65)); iconLabel.setPreferredSize(new java.awt.Dimension(65, 65)); iconLabel.setIcon(lockIcon); iconPanel.add(iconLabel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 2; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 0); fieldPanel.add(iconPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); getContentPane().add(fieldPanel, gridBagConstraints); passwordButtonPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; passwordButtonPanel.add(passwordDummyPanel, gridBagConstraints); okButton.setText("OK"); okButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); okButton.setPreferredSize(new java.awt.Dimension(70, 25)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); passwordButtonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 25)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); passwordButtonPanel.add(cancelButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); getContentPane().add(passwordButtonPanel, gridBagConstraints); setBounds(0, 0, 437, 187); }// </editor-fold>//GEN-END:initComponents private void passwordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordFieldKeyPressed if(evt.getKeyCode()==evt.VK_ENTER){ cancelled=false; this.setVisible(false); } }//GEN-LAST:event_passwordFieldKeyPressed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed cancelled=false; this.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed cancelled=true; this.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton cancelButton; private javax.swing.JPanel fieldPanel; private javax.swing.JLabel iconLabel; private javax.swing.JPanel iconPanel; private javax.swing.JButton okButton; private javax.swing.JPanel passwordButtonPanel; private javax.swing.JPanel passwordDummyPanel; private javax.swing.JPasswordField passwordField; private javax.swing.JPanel passwordFieldPanel; private javax.swing.JLabel passwordInfoLabel; private javax.swing.JLabel passwordLabel2; private javax.swing.JPanel passwordLabelPanel; private javax.swing.JTextField usernameField; private javax.swing.JLabel usernameLabel; // End of variables declaration//GEN-END:variables public String getUsername(){ return usernameField.getText(); } public char[] getPassword(){ return passwordField.getPassword(); } public boolean wasCancelled(){ return cancelled; } }
11,146
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTreePanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/tree/TopicTreePanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicTreePanel.java * * Created on 14.7.2005, 14:45 */ package org.wandora.application.gui.tree; import java.awt.Component; import java.util.Collection; import java.util.Set; import javax.swing.JPanel; import javax.swing.tree.TreePath; import org.wandora.application.RefreshListener; import org.wandora.application.Wandora; import org.wandora.application.gui.ConfirmResult; import org.wandora.application.gui.TopicGuiWrapper; import org.wandora.application.gui.TopicSelector; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; /** * @author olli */ public class TopicTreePanel extends JPanel implements TopicSelector,TopicMapListener,RefreshListener { private static final long serialVersionUID = 1L; private String rootTopic; // private TopicTreeModel model; private Wandora wandora; private String name; private Set<String> initialSelectedRelations; private TopicTreeRelation[] initialAllRelations; private boolean treeEnabled; /** Creates new form TopicTreePanel */ public TopicTreePanel(String rootTopic, Wandora parent) throws TopicMapException { this(rootTopic,parent,null,null); } public TopicTreePanel(String rootTopic, Wandora parent,Set<String> selectedAssociations, TopicTreeRelation[] associations) throws TopicMapException { this(rootTopic,parent,selectedAssociations,associations,"Topic tree"); } /** * @param rootTopic Subject identifier of the topic that is used as root for the tree * @param selectedRelations Names of the associations in associations array that * are used in this topic tree chooser. * @param allRelations A list of tree association types. Not all of them are * necessarily used in this topic tree chooser. selectedAssociations * contains the names of the used association types. */ public TopicTreePanel(String rootTopic, Wandora wandora, Set<String> selectedRelations, TopicTreeRelation[] allRelations,String name) throws TopicMapException { this.rootTopic=rootTopic; this.wandora=wandora; this.initialSelectedRelations=selectedRelations; this.initialAllRelations=allRelations; this.name=name; treeEnabled=true; jTree = initialSelectedRelations==null ? new TopicTree(rootTopic, wandora, this) : new TopicTree(rootTopic, wandora, initialSelectedRelations, initialAllRelations, this); initComponents(); setTreeEnabled(treeEnabled); jTreeTreeExpanded(null); } /** * @param rootSI Subject identifier of the topic that is used as root for the tree * @param selectedRelations Names of the associations in associations array that * are used in this topic tree chooser. * @param allRelations A list of tree association types. Not all of them are * necessarily used in this topic tree chooser. selectedAssociations * contains the names of the used association types. */ public void setModel(String rootSI, Set<String> selectedRelations, TopicTreeRelation[] allRelations ) throws TopicMapException { ((TopicTree)jTree).updateModel(rootSI, selectedRelations, allRelations); } @Override public String getSelectorName(){ return name; } public void setTreeEnabled(boolean b) { treeEnabled=b; if(jTree!=null){ if(b==true && this.getComponent(0)!=scrollPane) { this.removeAll(); this.add(scrollPane); this.revalidate(); } else if(b==false && this.getComponent(0)!=newRootPanel) { this.removeAll(); this.add(newRootPanel); this.revalidate(); } } } public String getRootSI(){ return rootTopic; } public void updateSelectedAssociation(String oldRelation, String newRelation) { if(initialSelectedRelations.contains(oldRelation)) { initialSelectedRelations.remove(oldRelation); initialSelectedRelations.add(newRelation); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonPanel = new javax.swing.JPanel(); newInstanceButton = new org.wandora.application.gui.simple.SimpleButton(); newSubclassButton = new org.wandora.application.gui.simple.SimpleButton(); jPanel1 = new javax.swing.JPanel(); newRootPanel = new javax.swing.JPanel(); jLabel1 = new org.wandora.application.gui.simple.SimpleLabel(); newRootButton = new org.wandora.application.gui.simple.SimpleButton(); scrollPane = new javax.swing.JScrollPane(); jTree = jTree; buttonPanel.setLayout(new java.awt.GridBagLayout()); newInstanceButton.setText("New Instance"); newInstanceButton.setMargin(new java.awt.Insets(2, 3, 2, 3)); newInstanceButton.setMinimumSize(new java.awt.Dimension(79, 21)); newInstanceButton.setPreferredSize(new java.awt.Dimension(85, 21)); newInstanceButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newInstanceButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 0); buttonPanel.add(newInstanceButton, gridBagConstraints); newSubclassButton.setText("New Subclass"); newSubclassButton.setMargin(new java.awt.Insets(2, 3, 2, 3)); newSubclassButton.setMinimumSize(new java.awt.Dimension(77, 21)); newSubclassButton.setPreferredSize(new java.awt.Dimension(85, 21)); newSubclassButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newSubclassButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(3, 5, 3, 5); buttonPanel.add(newSubclassButton, gridBagConstraints); jPanel1.setLayout(new java.awt.BorderLayout()); newRootPanel.setLayout(new java.awt.GridBagLayout()); jLabel1.setText("Topic tree root not found."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(15, 5, 5, 5); newRootPanel.add(jLabel1, gridBagConstraints); newRootButton.setText("Create root topic"); newRootButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newRootButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); newRootPanel.add(newRootButton, gridBagConstraints); setLayout(new java.awt.BorderLayout(2, 2)); scrollPane.setBorder(null); scrollPane.setMinimumSize(new java.awt.Dimension(0, 0)); jTree.setMaximumSize(new java.awt.Dimension(32768, 999999)); jTree.setMinimumSize(new java.awt.Dimension(10, 10)); jTree.setPreferredSize(new java.awt.Dimension(10, 10)); jTree.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener() { public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt) { } public void treeExpanded(javax.swing.event.TreeExpansionEvent evt) { jTreeTreeExpanded(evt); } }); scrollPane.setViewportView(jTree); add(scrollPane, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void newRootButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newRootButtonActionPerformed if(rootTopic == null) { WandoraOptionPane.showMessageDialog(wandora, "Can't find root topic. Update the root topic in configuration panel."); return; } String bn=WandoraOptionPane.showInputDialog(wandora,"Enter topic base name","Wandora class","Create root topic"); if(bn==null) return; try { Topic t=wandora.getTopicMap().createTopic(); if(TMBox.checkBaseNameChange(wandora,t,bn)!=ConfirmResult.yes){ t.remove(); return; } t.setBaseName(bn); t.addSubjectIdentifier(t.getTopicMap().createLocator(rootTopic)); wandora.doRefresh(); wandora.refreshTopicTrees(); } catch(TopicMapException tme) { tme.printStackTrace(); wandora.displayException("Unable to create root topic.", tme); } }//GEN-LAST:event_newRootButtonActionPerformed private void newSubclassButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newSubclassButtonActionPerformed //((TopicTree) jTree).createNewSubclass(); }//GEN-LAST:event_newSubclassButtonActionPerformed private void newInstanceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newInstanceButtonActionPerformed //((TopicTree) jTree).createNewInstance(); }//GEN-LAST:event_newInstanceButtonActionPerformed private void jTreeTreeExpanded(javax.swing.event.TreeExpansionEvent evt) {//GEN-FIRST:event_jTreeTreeExpanded java.awt.Rectangle rect=jTree.getRowBounds(jTree.getRowCount()-1); java.awt.Dimension dim=new java.awt.Dimension(rect.x+rect.width,rect.y+rect.height); // note that JTree.getPreferredScrollableViewpartSize doesn't seem to work jTree.setMinimumSize(dim); jTree.setPreferredSize(dim); //this.validateTree(); // TRIGGERS EXCEPTION IN JAVA 1.7 }//GEN-LAST:event_jTreeTreeExpanded public Topic getSelection() { TreePath path=jTree.getSelectionPath(); if(path==null) return null; return ((TopicGuiWrapper)path.getLastPathComponent()).topic; } public boolean needsRefresh() { return ((TopicTree)jTree).getNeedsRefresh(); } public void refresh() throws TopicMapException { ((TopicTree) jTree).refresh(); } @Override public Topic[] getSelectedTopics() { Topic t=getSelection(); if(t==null) return new Topic[0]; else return new Topic[]{t}; } @Override public Topic getSelectedTopic() { return getSelection(); } @Override public void init() { wandora.addTopicMapListener(this); wandora.addRefreshListener(this); } @Override public void cleanup() { wandora.removeTopicMapListener(this); wandora.removeRefreshListener(this); } @Override public Component getPanel() { ((TopicTree)jTree).setOpenWithDoubleClick(false); return this; } // ---------------------------------------------------- TopicMapListener --- @Override public void topicSubjectIdentifierChanged(Topic t,Locator added,Locator removed) throws TopicMapException { ((TopicTree)jTree).topicSubjectIdentifierChanged(t,added,removed); } @Override public void topicBaseNameChanged(Topic t,String newName,String oldName) throws TopicMapException { ((TopicTree)jTree).topicBaseNameChanged(t,newName,oldName); } @Override public void topicTypeChanged(Topic t,Topic added,Topic removed) throws TopicMapException { ((TopicTree)jTree).topicTypeChanged(t,added,removed); } @Override public void topicVariantChanged(Topic t,Collection<Topic> scope,String newName,String oldName) throws TopicMapException { ((TopicTree)jTree).topicVariantChanged(t,scope,newName,oldName); } @Override public void topicDataChanged(Topic t,Topic type,Topic version,String newValue,String oldValue) throws TopicMapException { ((TopicTree)jTree).topicDataChanged(t,type,version,newValue,oldValue); } @Override public void topicSubjectLocatorChanged(Topic t,Locator newLocator,Locator oldLocator) throws TopicMapException { ((TopicTree)jTree).topicSubjectLocatorChanged(t,newLocator,oldLocator); } @Override public void topicRemoved(Topic t) throws TopicMapException { ((TopicTree)jTree).topicRemoved(t); } @Override public void topicChanged(Topic t) throws TopicMapException { ((TopicTree)jTree).topicChanged(t); } @Override public void associationTypeChanged(Association a,Topic newType,Topic oldType) throws TopicMapException { ((TopicTree)jTree).associationTypeChanged(a,newType,oldType); } @Override public void associationPlayerChanged(Association a,Topic role,Topic newPlayer,Topic oldPlayer) throws TopicMapException { ((TopicTree)jTree).associationPlayerChanged(a,role,newPlayer,oldPlayer); } @Override public void associationRemoved(Association a) throws TopicMapException { ((TopicTree)jTree).associationRemoved(a); } @Override public void associationChanged(Association a) throws TopicMapException { ((TopicTree)jTree).associationChanged(a); } // --------------------------------------------------- /TopicMapListener --- @Override public void doRefresh() throws TopicMapException { //if(needsRefresh()){ refresh(); //} } public TopicTree getTopicTree() { return (TopicTree)jTree; } // Variables declaration - do not modify//GEN-BEGIN:variables public javax.swing.JPanel buttonPanel; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JTree jTree; private javax.swing.JButton newInstanceButton; private javax.swing.JButton newRootButton; private javax.swing.JPanel newRootPanel; private javax.swing.JButton newSubclassButton; private javax.swing.JScrollPane scrollPane; // End of variables declaration//GEN-END:variables }
16,023
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTreeRelationsEditor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/tree/TopicTreeRelationsEditor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicTreeRelationsEditor.java * * Created on 13. helmikuuta 2006, 13:13 */ package org.wandora.application.gui.tree; import java.awt.Component; import java.awt.GridBagConstraints; import java.util.ArrayList; import java.util.List; import javax.swing.JDialog; import javax.swing.JPanel; import org.wandora.application.Wandora; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.GripCollections; import org.wandora.utils.Options; /** * * @author olli */ public class TopicTreeRelationsEditor extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private TopicTreeRelation[] relations; private boolean cancelled=true; private Component parent; private Wandora wandora; /** Creates new form TreeAssociationTypesEditor */ public TopicTreeRelationsEditor() { initComponents(); } public void open(Wandora wandora) { this.wandora = wandora; relations = readRelationTypes(); updateRelationsPanel(); JDialog jd=new JDialog(wandora,true); jd.setTitle("Configure topic tree relations"); jd.add(this); jd.setSize(800,400); parent = jd; wandora.centerWindow(jd); jd.setVisible(true); // Blocks till closed. } public static TopicTreeRelation[] readRelationTypes() { int counter = 0; Options options = Wandora.getWandora().getOptions(); List<TopicTreeRelation> v = new ArrayList<>(); if(options != null) { while(true) { String name=options.get("trees.type["+counter+"].name"); if(name==null) break; String subSI=options.get("trees.type["+counter+"].subsi"); String assocSI=options.get("trees.type["+counter+"].assocsi"); String superSI=options.get("trees.type["+counter+"].supersi"); String icon=options.get("trees.type["+counter+"].icon"); v.add(new TopicTreeRelation(name,subSI,assocSI,superSI,icon)); counter++; } } return GripCollections.collectionToArray(v,TopicTreeRelation.class); } public static void writeAssociationTypes(TopicTreeRelation[] associations) { Options options = Wandora.getWandora().getOptions(); System.out.println("Writing tree associations: "+associations.length); if(options != null) { for(int i=0;i<associations.length;i++){ options.put("trees.type["+i+"].name",associations[i].name); options.put("trees.type["+i+"].subsi",associations[i].subSI); options.put("trees.type["+i+"].assocsi",associations[i].assocSI); options.put("trees.type["+i+"].supersi",associations[i].superSI); options.put("trees.type["+i+"].icon",associations[i].icon); } int counter=associations.length; while(true){ String name=options.get("trees.type["+counter+"].name"); if(name==null) break; options.put("trees.type["+counter+"].name",null); options.put("trees.type["+counter+"].subsi",null); options.put("trees.type["+counter+"].assocsi",null); options.put("trees.type["+counter+"].supersi",null); options.put("trees.type["+counter+"].icon",null); counter++; } } } private void updateRelationsPanel() { relationsPanel.removeAll(); for(int i=0; i<relations.length; i++) { try { GridBagConstraints gbc=new GridBagConstraints(); gbc.gridx=0; gbc.gridy=i; gbc.weightx=1.0; gbc.weighty=0.0; gbc.fill=GridBagConstraints.HORIZONTAL; TopicTreeRelationEditorPanel tatep = new TopicTreeRelationEditorPanel( relations[i].name, relations[i].subSI, relations[i].assocSI, relations[i].superSI, relations[i].icon, this, wandora ); relationsPanel.add(tatep,gbc); } catch(Exception e) { e.printStackTrace(); } } addFillerPanel(); relationsPanel.revalidate(); relationsPanel.repaint(); } private void addFillerPanel(){ GridBagConstraints gbc=new GridBagConstraints(); gbc.gridx=0; gbc.gridy=relationsPanel.getComponentCount(); gbc.fill=GridBagConstraints.VERTICAL; gbc.weighty=1.0; JPanel panel=new JPanel(); relationsPanel.add(panel,gbc); } public void deleted(TopicTreeRelationEditorPanel editor){ TopicTreeRelationEditorPanel[] panels=new TopicTreeRelationEditorPanel[relationsPanel.getComponentCount()-2]; int counter=0; TopicTreeRelationEditorPanel panel = null; GridBagConstraints gbc = null; for(int i=0; i<relationsPanel.getComponentCount()-1; i++){ panel=(TopicTreeRelationEditorPanel)relationsPanel.getComponent(i); if(panel!=editor) panels[counter++]=panel; } relationsPanel.removeAll(); for(int i=0; i<panels.length; i++){ gbc=new GridBagConstraints(); gbc.gridx=0; gbc.gridy=i; gbc.weightx=1.0; gbc.fill=GridBagConstraints.HORIZONTAL; relationsPanel.add(panels[i],gbc); } addFillerPanel(); this.revalidate(); this.repaint(); } public TopicTreeRelation[] getRelationTypes() { List<TopicTreeRelation> v = new ArrayList<>(); for(int i=0; i<relationsPanel.getComponentCount()-1; i++){ try { TopicTreeRelationEditorPanel panel = (TopicTreeRelationEditorPanel)relationsPanel.getComponent(i); v.add(panel.getRelation()); } catch(TopicMapException e) { e.printStackTrace(); } } return GripCollections.collectionToArray(v, TopicTreeRelation.class); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; relationsScrollPane = new javax.swing.JScrollPane(); relationsPanel = new javax.swing.JPanel(); buttonPanel = new javax.swing.JPanel(); addButton = new org.wandora.application.gui.simple.SimpleButton(); fillerPanel = new javax.swing.JPanel(); okButton = new org.wandora.application.gui.simple.SimpleButton(); cancelButton = new org.wandora.application.gui.simple.SimpleButton(); setLayout(new java.awt.GridBagLayout()); relationsPanel.setLayout(new java.awt.GridBagLayout()); relationsScrollPane.setViewportView(relationsPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(relationsScrollPane, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); addButton.setText("Add"); addButton.setMaximumSize(new java.awt.Dimension(70, 23)); addButton.setMinimumSize(new java.awt.Dimension(70, 23)); addButton.setPreferredSize(new java.awt.Dimension(70, 23)); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 26); buttonPanel.add(addButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(fillerPanel, gridBagConstraints); okButton.setText("OK"); okButton.setMaximumSize(new java.awt.Dimension(70, 23)); okButton.setMinimumSize(new java.awt.Dimension(70, 23)); okButton.setPreferredSize(new java.awt.Dimension(70, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 3, 5, 3); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(5, 3, 5, 3); buttonPanel.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.weightx = 1.0; add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed cancelled=true; parent.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed cancelled=false; writeAssociationTypes(getRelationTypes()); parent.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed public boolean wasCancelled(){ return cancelled; } private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed relationsPanel.remove(relationsPanel.getComponentCount()-1); GridBagConstraints gbc=new GridBagConstraints(); gbc.gridx=0; gbc.gridy=relationsPanel.getComponentCount(); gbc.weightx=1.0; gbc.fill=GridBagConstraints.HORIZONTAL; try { TopicTreeRelationEditorPanel tatep=new TopicTreeRelationEditorPanel("","","","","",this,wandora); relationsPanel.add(tatep,gbc); } catch(TopicMapException tme) { tme.printStackTrace(); // TODO EXCEPTION } addFillerPanel(); this.revalidate(); this.repaint(); }//GEN-LAST:event_addButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addButton; private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JPanel fillerPanel; private javax.swing.JButton okButton; private javax.swing.JPanel relationsPanel; private javax.swing.JScrollPane relationsScrollPane; // End of variables declaration//GEN-END:variables }
13,301
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTreeTabManager.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/tree/TopicTreeTabManager.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.tree; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.swing.JDialog; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import org.wandora.application.Wandora; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleMenuItem; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * * @author akivela */ public class TopicTreeTabManager { private JPopupMenu tabPopupMenu = null; // how many tabs before and after configurable topic trees private int fixedStartTabs; private int fixedEndTabs; private Wandora wandora = null; // this is to retain the ordering of tabs private ArrayList<String> tabTrees; // tree ,set of association names private HashMap<String,Set<String>> selectedTreeRelations; // tree ,root SI private HashMap<String,String> treeRoots; private HashMap<String,TopicTreePanel> treeTopicChoosers; JTabbedPane tabbedPane = null; Options options = null; public TopicTreeTabManager(Wandora w, JTabbedPane tPane) { wandora = w; tabbedPane = tPane; options = w.getOptions(); initializePopupMenu(); } public void initializePopupMenu() { tabPopupMenu = new javax.swing.JPopupMenu(); tabPopupMenu.setFont(UIConstants.menuFont); JMenuItem createTabMenuItem = new SimpleMenuItem(); JMenuItem deleteTabMenuItem = new SimpleMenuItem(); JSeparator jSeparator2 = new javax.swing.JSeparator(); JMenuItem configTabMenuItem = new SimpleMenuItem(); JMenuItem configTypesMenuItem = new SimpleMenuItem(); createTabMenuItem.setFont(UIConstants.menuFont); createTabMenuItem.setText("Create new tab..."); createTabMenuItem.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { createTabMenuItemActionPerformed(evt); } }); tabPopupMenu.add(createTabMenuItem); deleteTabMenuItem.setFont(UIConstants.menuFont); deleteTabMenuItem.setText("Delete tab..."); deleteTabMenuItem.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { deleteTabMenuItemActionPerformed(evt); } }); tabPopupMenu.add(deleteTabMenuItem); tabPopupMenu.add(jSeparator2); configTabMenuItem.setFont(UIConstants.menuFont); configTabMenuItem.setText("Configure topic tree tab..."); configTabMenuItem.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { configTopicTreeActionPerformed(evt); } }); tabPopupMenu.add(configTabMenuItem); configTypesMenuItem.setFont(UIConstants.menuFont); configTypesMenuItem.setText("Configure types..."); configTypesMenuItem.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { configTopicTreeRelationsActionPerformed(evt); } }); tabPopupMenu.add(configTypesMenuItem); } /** * Creates and initializes topic trees based on application options and adds them * in the tabbed pane along with the finder tab. */ public void initializeTopicTrees() { fixedStartTabs = 0; fixedEndTabs = 1; try { if(treeTopicChoosers!=null){ for(TopicTreePanel c : treeTopicChoosers.values()){ wandora.removeTopicMapListener(c); wandora.removeRefreshListener(c); } } for(int i=0; i<=tabbedPane.getTabCount(); i++) { tabbedPane.removeTabAt(0); } readTopicTreeRelations(); TopicTreeRelation[] associations=TopicTreeRelationsEditor.readRelationTypes(); treeTopicChoosers=new LinkedHashMap<String,TopicTreePanel>(); // tabbedPane.addTab("Layers", layersPanel); for(String tab : tabTrees) { TopicTreePanel treeTopicChooser = new TopicTreePanel(treeRoots.get(tab),wandora,selectedTreeRelations.get(tab),associations,tab); treeTopicChoosers.put(tab,treeTopicChooser); wandora.addTopicMapListener(treeTopicChooser); wandora.addRefreshListener(treeTopicChooser); // JPanel panel=new JPanel(); // panel.add(treeTopicChooser); tabbedPane.addTab(tab,null,treeTopicChooser,null); } } catch(Exception e) { wandora.handleError(e); } } /** * Gets all topic tree choosers. Returned map has tree names as keys and trees * themselves as values. */ public HashMap<String,TopicTreePanel> getTrees() { return treeTopicChoosers; } /** * Creates new tree choosers based on application options and returns them as a collection. */ public Collection<TopicTreePanel> getTreeChoosers() throws TopicMapException { ArrayList<TopicTreePanel> v=new ArrayList<TopicTreePanel>(); TopicTreeRelation[] associations=TopicTreeRelationsEditor.readRelationTypes(); for(String tab : selectedTreeRelations.keySet()){ TopicTreePanel treeTopicChooser = new TopicTreePanel(treeRoots.get(tab),wandora,selectedTreeRelations.get(tab),associations,tab); v.add(treeTopicChooser); } return v; } /** * Initializes treeRoots, tabTrees and selectedTreeAssociations with application options. */ public void readTopicTreeRelations() { treeRoots=new LinkedHashMap<String,String>(); tabTrees=new ArrayList<String>(); selectedTreeRelations=new LinkedHashMap<String,Set<String>>(); int counter=0; while(true) { String name=options.get("trees.tree["+counter+"].name"); if(name==null) break; String root=options.get("trees.tree["+counter+"].root"); tabTrees.add(name); treeRoots.put(name,root); int counter2=0; HashSet<String> as=new LinkedHashSet<String>(); while(true){ String a=options.get("trees.tree["+counter+"].relation["+counter2+"]"); if(a==null) break; as.add(a); counter2++; } selectedTreeRelations.put(name,as); counter++; } } /** * Writes the information in treeRoots, tabTrees and selectedTreeAssociations into * application options. Effectively saves information about topic tree choosers * and association types used in them. */ public void writeTopicTreeRelations() { int counter=0; options.removeAll("trees.tree"); for(String tab : tabTrees) { //for(Map.Entry<String,Set<String>> e : selectedTreeAssociations.entrySet()){ Set<String> as=selectedTreeRelations.get(tab); options.put("trees.tree["+counter+"].name",tab); options.put("trees.tree["+counter+"].root",treeRoots.get(tab)); int counter2=0; for(String a : as) { options.put("trees.tree["+counter+"].relation["+counter2+"]",a); counter2++; } counter++; } } public void createTabMenuItemActionPerformed(java.awt.event.ActionEvent evt) { try { TopicTreeRelation[] associations=TopicTreeRelationsEditor.readRelationTypes(); JDialog jd=new JDialog(wandora,true); jd.setTitle("New topic tree tab"); TopicTreeConfigPanel tap=new TopicTreeConfigPanel(associations,new LinkedHashSet<String>(),null,"",jd,wandora); jd.add(tap); jd.setSize(400,300); wandora.centerWindow(jd); while(true) { jd.setVisible(true); if(tap.wasCancelled()) return; String name=tap.getTreeName(); String rootSI = tap.getRoot(); if(selectedTreeRelations.get(name) != null) { WandoraOptionPane.showMessageDialog(wandora,"Tab '"+name+"' already exists! Please use another name for the tab.", null, WandoraOptionPane.WARNING_MESSAGE); } else if(name == null || name.trim().length() == 0) { WandoraOptionPane.showMessageDialog(wandora,"Tab name is not valid! It is null or zero length or contains only space characters. Please use another name for the tab.", null, WandoraOptionPane.WARNING_MESSAGE); } else if(rootSI == null || rootSI.trim().length() == 0) { WandoraOptionPane.showMessageDialog(wandora,"Root topic is not valid! Please select topic for the tree root.", null, WandoraOptionPane.WARNING_MESSAGE); } else break; } String name=tap.getTreeName(); selectedTreeRelations.put(name, tap.getSelectedRelations()); treeRoots.put(name, tap.getRoot()); tabTrees.add(name); TopicTreePanel treeTopicChooser = new TopicTreePanel(treeRoots.get(name),wandora,selectedTreeRelations.get(name),associations,name); treeTopicChoosers.put(name,treeTopicChooser); wandora.addTopicMapListener(treeTopicChooser); wandora.addRefreshListener(treeTopicChooser); tabbedPane.insertTab(name,null,treeTopicChooser,null,tabbedPane.getTabCount()-fixedEndTabs); writeTopicTreeRelations(); } catch(TopicMapException tme){ wandora.handleError(tme); // TODO EXCEPTION } } public void deleteTabMenuItemActionPerformed(java.awt.event.ActionEvent evt) { int tabIndex=tabbedPane.getSelectedIndex(); if(tabIndex<=fixedStartTabs || tabIndex>=tabbedPane.getTabCount()-fixedEndTabs) { WandoraOptionPane.showMessageDialog(wandora, "You are not allowed to delete original topic tree tab.", "Topic tree tab deletion not allowed"); return; } String name=tabbedPane.getTitleAt(tabIndex); int c=WandoraOptionPane.showConfirmDialog(wandora,"Do you really want to delete tab '"+name+"'?","Confirm delete",WandoraOptionPane.YES_NO_OPTION); if(c!=WandoraOptionPane.YES_OPTION) return; selectedTreeRelations.remove(name); treeRoots.remove(name); tabTrees.remove(name); tabbedPane.removeTabAt(tabIndex); writeTopicTreeRelations(); } public void configTopicTreeActionPerformed(java.awt.event.ActionEvent evt) { try { int tabIndex = tabbedPane.getSelectedIndex(); if(tabIndex<fixedStartTabs || tabIndex>=tabbedPane.getTabCount()-fixedEndTabs) return; String tab = tabbedPane.getTitleAt(tabIndex); Set<String> selected = selectedTreeRelations.get(tab); if(selected == null) selected = new LinkedHashSet<String>(); JDialog jd=new JDialog(wandora, true); jd.setTitle("Configure topic tree"); TopicTreeRelation[] associations = TopicTreeRelationsEditor.readRelationTypes(); TopicTreeConfigPanel tap = new TopicTreeConfigPanel(associations,selected,treeRoots.get(tab),tab,jd,wandora); jd.add(tap); jd.setSize(400,400); wandora.centerWindow(jd); jd.setVisible(true); if(tap.wasCancelled()) return; selectedTreeRelations.put(tab, tap.getSelectedRelations()); treeRoots.put(tab, tap.getRoot()); if(!tap.getTreeName().equals(tab)){ String newname = tap.getTreeName(); String rootSI = tap.getRoot(); if(selectedTreeRelations.get(newname) != null){ WandoraOptionPane.showMessageDialog(wandora,"Tab '"+newname+"' already exists! Please use another name for the tab.", null, WandoraOptionPane.WARNING_MESSAGE); } else if(newname == null || newname.trim().length() == 0) { WandoraOptionPane.showMessageDialog(wandora,"Tab name is not valid! It is null or zero length or contains only space characters. Please use another name for the tab.", null, WandoraOptionPane.WARNING_MESSAGE); } else if(rootSI == null || rootSI.trim().length() == 0) { WandoraOptionPane.showMessageDialog(wandora,"Root topic is not valid! Please select topic for the tree root.", null, WandoraOptionPane.WARNING_MESSAGE); } else { selectedTreeRelations.put(newname,selectedTreeRelations.get(tab)); treeRoots.put(newname,treeRoots.get(tab)); treeTopicChoosers.put(newname,treeTopicChoosers.get(tab)); selectedTreeRelations.remove(tab); treeRoots.remove(tab); treeTopicChoosers.remove(tab); // treeTopicChooser doesn't change, only it's name, so no need to update listeners for(int i=fixedStartTabs; i<tabbedPane.getTabCount()-fixedEndTabs; i++){ if(tabbedPane.getTitleAt(i).equals(tab)) { tabbedPane.setTitleAt(i,newname); break; } } for(int i=0; i<tabTrees.size(); i++) { if(tabTrees.get(i).equals(tab)) { tabTrees.set(i,newname); break; } } tab=newname; } } writeTopicTreeRelations(); treeTopicChoosers.get(tab).setModel(treeRoots.get(tab),selectedTreeRelations.get(tab),associations); } catch(TopicMapException tme) { wandora.handleError(tme); // TODO EXCEPTION } } public void configTopicTreeRelationsActionPerformed(java.awt.event.ActionEvent evt) { try { TopicTreeRelationsEditor editor = new TopicTreeRelationsEditor(); editor.open(Wandora.getWandora()); if(editor.wasCancelled()) return; TopicTreeRelation[] associations = editor.readRelationTypes(); for(Map.Entry<String,TopicTreePanel> e : treeTopicChoosers.entrySet()){ e.getValue().setModel(treeRoots.get(e.getKey()),selectedTreeRelations.get(e.getKey()),associations); } } catch(TopicMapException tme) { wandora.handleError(tme); // TODO EXCEPTION } } public void tabbedPaneMouseClicked(java.awt.event.MouseEvent evt) { try { if(evt.getButton()==MouseEvent.BUTTON3) { int tabIndex=tabbedPane.getSelectedIndex(); if(tabIndex<fixedStartTabs || tabIndex>=tabbedPane.getTabCount()-fixedEndTabs) return; tabPopupMenu.show(evt.getComponent(),evt.getX(),evt.getY()); } } catch(Exception e) { e.printStackTrace(); } } }
16,769
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTreeTopicRenderer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/tree/TopicTreeTopicRenderer.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicTreeTopicRenderer.java * * Created on 27. joulukuuta 2005, 23:00 * */ package org.wandora.application.gui.tree; import java.awt.Color; import java.awt.Component; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JTree; import javax.swing.tree.DefaultTreeCellRenderer; import org.wandora.application.Wandora; import org.wandora.application.gui.TopicGuiWrapper; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Topic; import org.wandora.utils.GripCollections; /** * @author akivela */ public class TopicTreeTopicRenderer extends DefaultTreeCellRenderer { private static final long serialVersionUID = 1L; private TopicTree topicTree; private Wandora wandora = Wandora.getWandora(); public Map<String,Icon> icons=GripCollections.addArrayToMap(new HashMap<String,Icon>(),new Object[]{ }); public TopicTreeTopicRenderer(TopicTree topicTree) { this.topicTree = topicTree; } @Override public java.awt.Component getTreeCellRendererComponent ( JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component c = super.getTreeCellRendererComponent( tree, value, sel, expanded, leaf, row, hasFocus); try { if(topicTree.isBroken()) return c; String res=((TopicGuiWrapper)value).icon; setIcon(solveIcon(res)); Topic topic = null; if(value == null || value instanceof Topic) { topic = (Topic) value; } else if(value instanceof TopicGuiWrapper) { TopicGuiWrapper topicWrapper = (TopicGuiWrapper) value; topic = topicWrapper.topic; } if(c instanceof JLabel) { JLabel label = (JLabel) c; try { String topicName = TopicToString.toString(topic); label.setText(topicName); Color color = null; if(wandora != null) { color = wandora.topicHilights.getLayerColor(topic); } if(topic == null) { color = Color.LIGHT_GRAY; } else if(topic.isRemoved()) { color = Color.RED; } if(color!=null) label.setForeground(color); else label.setForeground(Color.BLACK); } catch(Exception ex) {} } } catch(Exception e) { e.printStackTrace(); } return c; } public Icon solveIcon(String res) { Icon icon=icons.get( res ); if(res!=null && icon==null){ try { URL url=this.getClass().getClassLoader().getResource(res); icon=new ImageIcon(url); icons.put(url.toExternalForm(),icon); } catch(Exception e){ e.printStackTrace(); icon=null; } } return icon; } }
4,432
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTreeRelationEditorPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/tree/TopicTreeRelationEditorPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TreeAssociationTypePanel.java * * Created on 13. helmikuuta 2006, 12:03 */ package org.wandora.application.gui.tree; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.ImageIcon; import org.wandora.application.Wandora; import org.wandora.application.gui.GetTopicButton; import org.wandora.application.gui.simple.SimpleField; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.IObox; /** * * @author olli */ public class TopicTreeRelationEditorPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private TopicTreeRelationsEditor parent; private static List<IconWrapper> icons; private Map<String,Integer> iconIndex; private Wandora wandora; private static void readIcons(){ try{ icons=new ArrayList<IconWrapper>(); Enumeration<URL> toolResources = ClassLoader.getSystemResources("gui/icons/topictree"); while(toolResources.hasMoreElements()){ URL baseUrl=toolResources.nextElement(); if(baseUrl.toExternalForm().startsWith("file:")) { String baseDir = IObox.getFileFromURL(baseUrl); //String baseDir = URLDecoder.decode(baseUrl.toExternalForm().substring(6), "UTF-8"); //System.out.println("Basedir: " + baseDir); Set<String> fileNames = IObox.getFilesAsHash(baseDir, ".*\\.png", 10, 1000); for(String f : fileNames) { int ind=f.lastIndexOf("/"); int ind2=f.lastIndexOf("\\"); if(ind2>ind) ind=ind2; icons.add(new IconWrapper("gui/icons/topictree/"+f.substring(ind+1))); } } } } catch(java.io.IOException ioe) { ioe.printStackTrace(); } } /** Creates new form TreeAssociationTypePanel */ public TopicTreeRelationEditorPanel(String name,String subRole,String assocType,String superRole,String icon,TopicTreeRelationsEditor parent,Wandora wandora) throws TopicMapException { this.wandora=wandora; subButton = new GetTopicButton(wandora); assocTypeButton = new GetTopicButton(wandora); superButton = new GetTopicButton(wandora); initComponents(); if(icons==null) readIcons(); /* icons=GripCollections.newVector( new IconWrapper("gui/icons/testicon1.png"), new IconWrapper("gui/icons/testicon2.png"), new IconWrapper("gui/icons/testicon3.png"), new IconWrapper("gui/icons/testicon4.png") ); */ iconIndex=new HashMap<String,Integer>(); for(int i=0; i<icons.size(); i++){ iconIndex.put(icons.get(i).resource,i); iconComboBox.addItem(icons.get(i)); } this.parent=parent; nameTextField.setText(name); // subRoleTextField.setText(subRole); // associationTypeTextField.setText(assocType); // superRoleTextField.setText(superRole); ((GetTopicButton)subButton).setTopic(subRole); ((GetTopicButton)assocTypeButton).setTopic(assocType); ((GetTopicButton)superButton).setTopic(superRole); if(!icons.isEmpty()) { if(icon==null) icon=icons.get(0).resource; } if(!iconIndex.containsKey(icon)) { icons.add(new IconWrapper(icon)); iconComboBox.addItem(icons.get(icons.size()-1)); iconIndex.put(icon,icons.size()-1); } iconComboBox.setSelectedIndex(iconIndex.get(icon)); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; superRoleTextField = new org.wandora.application.gui.simple.SimpleField(); associationTypeTextField = new org.wandora.application.gui.simple.SimpleField(); subRoleTextField = new org.wandora.application.gui.simple.SimpleField(); iconComboBox = new org.wandora.application.gui.simple.SimpleComboBox();iconComboBox.setEditable(false); deleteButton = new org.wandora.application.gui.simple.SimpleButton(); nameTextField = new SimpleField(); subButton = subButton; // These buttons initialized in constructor because of possible TopicMapException; assocTypeButton = assocTypeButton; superButton = superButton; superRoleTextField.setPreferredSize(new java.awt.Dimension(100, 20)); associationTypeTextField.setPreferredSize(new java.awt.Dimension(100, 20)); subRoleTextField.setPreferredSize(new java.awt.Dimension(100, 20)); setLayout(new java.awt.GridBagLayout()); iconComboBox.setMinimumSize(new java.awt.Dimension(30, 20)); iconComboBox.setPreferredSize(new java.awt.Dimension(50, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 4; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5); add(iconComboBox, gridBagConstraints); deleteButton.setText("Delete"); deleteButton.setMargin(new java.awt.Insets(2, 6, 2, 6)); deleteButton.setMaximumSize(new java.awt.Dimension(65, 20)); deleteButton.setMinimumSize(new java.awt.Dimension(65, 20)); deleteButton.setPreferredSize(new java.awt.Dimension(50, 20)); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 5; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(deleteButton, gridBagConstraints); nameTextField.setPreferredSize(new java.awt.Dimension(60, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(nameTextField, gridBagConstraints); subButton.setMaximumSize(new java.awt.Dimension(300, 20)); subButton.setMinimumSize(new java.awt.Dimension(30, 20)); subButton.setPreferredSize(new java.awt.Dimension(30, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5); add(subButton, gridBagConstraints); assocTypeButton.setMaximumSize(new java.awt.Dimension(300, 20)); assocTypeButton.setMinimumSize(new java.awt.Dimension(30, 20)); assocTypeButton.setPreferredSize(new java.awt.Dimension(30, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5); add(assocTypeButton, gridBagConstraints); superButton.setMaximumSize(new java.awt.Dimension(300, 20)); superButton.setMinimumSize(new java.awt.Dimension(30, 20)); superButton.setPreferredSize(new java.awt.Dimension(30, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5); add(superButton, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed parent.deleted(this); }//GEN-LAST:event_deleteButtonActionPerformed public TopicTreeRelation getRelation() throws TopicMapException { return new TopicTreeRelation( nameTextField.getText(), ((GetTopicButton)subButton).getTopicSI(), ((GetTopicButton)assocTypeButton).getTopicSI(), ((GetTopicButton)superButton).getTopicSI(), icons.get(iconComboBox.getSelectedIndex()).resource); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton assocTypeButton; private javax.swing.JTextField associationTypeTextField; private javax.swing.JButton deleteButton; private javax.swing.JComboBox iconComboBox; private javax.swing.JTextField nameTextField; private javax.swing.JButton subButton; private javax.swing.JTextField subRoleTextField; private javax.swing.JButton superButton; private javax.swing.JTextField superRoleTextField; // End of variables declaration//GEN-END:variables public static class IconWrapper extends ImageIcon { private static final long serialVersionUID = 1L; public String resource; public IconWrapper(String resource){ super(TopicTreeConfigPanel.class.getClassLoader().getResource(resource)); this.resource=resource; } } }
10,767
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTreeTopicEditor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/tree/TopicTreeTopicEditor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicTreeTopicEditor.java * * Created on 4. elokuuta 2006, 16:55 */ package org.wandora.application.gui.tree; import java.awt.Component; import javax.swing.DefaultCellEditor; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.event.CellEditorListener; import javax.swing.event.ChangeEvent; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.TreeCellEditor; import org.wandora.application.Wandora; import org.wandora.application.gui.TopicGuiWrapper; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class TopicTreeTopicEditor extends DefaultTreeCellEditor implements TreeCellEditor, CellEditorListener { private TopicTree topicTree; private Component editor; private SimpleField field = null; private Wandora wandora; private Object originalValue = null; public TopicTreeTopicEditor(Wandora w, TopicTree topicTree, SimpleField field, TopicTreeTopicRenderer renderer) { super(topicTree, renderer, new DefaultCellEditor(field)); this.renderer = renderer; this.wandora = w; this.topicTree = topicTree; this.field = field; this.addCellEditorListener(this); } @Override public Component getTreeCellEditorComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row) { originalValue = value; /* Workaround for swing bug 'DefaultTreeCellEditor doesn't get Icon set in DefaultTreeCellRenderer' * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4663832 */ String res=((TopicGuiWrapper)value).icon; renderer.setIcon(((TopicTreeTopicRenderer)renderer).solveIcon(res)); editor = super.getTreeCellEditorComponent(tree, value, sel, expanded, leaf,row); return editor; } /* Workaround for swing bug 'DefaultTreeCellEditor doesn't get Icon set in DefaultTreeCellRenderer' * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4663832 */ @Override protected void determineOffset(JTree tree, Object value,boolean isSelected, boolean expanded,boolean leaf, int row) { if(renderer != null) { renderer.getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, row, true ); editingIcon = renderer.getIcon(); if(editingIcon != null) offset = renderer.getIconTextGap() + editingIcon.getIconWidth(); else offset = renderer.getIconTextGap(); } else { editingIcon = null; offset = 0; } } @Override public void editingCanceled(ChangeEvent e) { } @Override public void editingStopped(ChangeEvent e) { try { if(field instanceof JTextField) { String value = ((JTextField) field).getText(); if(value != null && value.length() > 0) { Topic topic = topicTree.getSelection(); if(topic != null && !topic.isRemoved()) { if(TopicToString.supportsStringIntoTopic()) { TopicToString.stringIntoTopic((String) originalValue.toString(), value, topic); if(wandora != null) wandora.doRefresh(); } } } } } catch (Exception ex) { wandora.handleError(ex); } } }
4,590
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTreeConfigPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/tree/TopicTreeConfigPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicTreeConfigPanel.java * * Created on 13. helmikuuta 2006, 10:54 */ package org.wandora.application.gui.tree; import java.awt.Component; import java.awt.GridBagConstraints; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import javax.swing.JCheckBox; import org.wandora.application.Wandora; import org.wandora.application.gui.GetTopicButton; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; import org.wandora.topicmap.TopicMapException; /** * * @author olli, akivela */ public class TopicTreeConfigPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private boolean cancelled=true; private TopicTreeRelation[] allRelations; private ArrayList<JCheckBox> checkboxes; private Component parent; private Wandora wandora; /** Creates new form TopicTreeConfigPanel */ public TopicTreeConfigPanel(TopicTreeRelation[] allRelations, Set<String> selectedRelations, String root, String name, Component parent, Wandora wandora) throws TopicMapException { this.wandora = wandora; rootButton = new GetTopicButton(wandora); initComponents(); this.parent=parent; nameTextField.setText(name); // rootTextField.setText(root); ((GetTopicButton)rootButton).setTopic(root); updateRelationsUI(allRelations, selectedRelations); } private void updateRelationsUI(TopicTreeRelation[] allRelations, Set<String> selectedRelations) { //relationsPanel.removeAll(); checkboxes = new ArrayList<JCheckBox>(); this.allRelations = allRelations; for(int i=0; i<allRelations.length; i++) { GridBagConstraints gbc=new GridBagConstraints(); gbc.gridx=0; gbc.gridy=1+i; gbc.anchor=GridBagConstraints.WEST; gbc.fill=GridBagConstraints.HORIZONTAL; gbc.weightx=1.0; String aname=allRelations[i].name; JCheckBox checkbox=new SimpleCheckBox(); checkbox.setText(aname); if(selectedRelations.contains(aname)) checkbox.setSelected(true); else checkbox.setSelected(false); checkboxes.add(checkbox); relationsPanel.add(checkbox,gbc); } } public Set<String> getSelectedRelations() { HashSet<String> selected=new HashSet<String>(); for(JCheckBox cb : checkboxes) { if(cb.isSelected()) selected.add(cb.getText()); } return selected; } public String getRoot() throws TopicMapException { return ((GetTopicButton)rootButton).getTopicSI(); } public String getTreeName() { return nameTextField.getText(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; rootTextField = new org.wandora.application.gui.simple.SimpleField(); nameLabel = new org.wandora.application.gui.simple.SimpleLabel(); nameTextField = new org.wandora.application.gui.simple.SimpleField(); rootLabel = new org.wandora.application.gui.simple.SimpleLabel(); rootButton = rootButton; relationsScrollPane = new javax.swing.JScrollPane(); relationsContainerPanel = new javax.swing.JPanel(); relationsPanel = new javax.swing.JPanel(); relationFillerPanel = new javax.swing.JPanel(); buttonPanel = new javax.swing.JPanel(); editRelationsButton = new SimpleButton(); jPanel2 = new javax.swing.JPanel(); okButton = new org.wandora.application.gui.simple.SimpleButton(); cancelButton = new org.wandora.application.gui.simple.SimpleButton(); setLayout(new java.awt.GridBagLayout()); nameLabel.setText("Name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(7, 5, 3, 5); add(nameLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(7, 5, 3, 5); add(nameTextField, gridBagConstraints); rootLabel.setText("Root"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); add(rootLabel, gridBagConstraints); rootButton.setMaximumSize(new java.awt.Dimension(35, 20)); rootButton.setMinimumSize(new java.awt.Dimension(35, 20)); rootButton.setPreferredSize(new java.awt.Dimension(35, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 3, 5); add(rootButton, gridBagConstraints); relationsContainerPanel.setLayout(new java.awt.GridBagLayout()); relationsPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; relationsContainerPanel.add(relationsPanel, gridBagConstraints); relationFillerPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; relationsContainerPanel.add(relationFillerPanel, gridBagConstraints); relationsScrollPane.setViewportView(relationsContainerPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); add(relationsScrollPane, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); editRelationsButton.setText("Edit relations"); editRelationsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editRelationsButtonActionPerformed(evt); } }); buttonPanel.add(editRelationsButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(jPanel2, gridBagConstraints); okButton.setText("OK"); okButton.setMaximumSize(new java.awt.Dimension(70, 23)); okButton.setMinimumSize(new java.awt.Dimension(70, 23)); okButton.setPreferredSize(new java.awt.Dimension(70, 23)); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3); buttonPanel.add(okButton, gridBagConstraints); cancelButton.setText("Cancel"); cancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); cancelButton.setMinimumSize(new java.awt.Dimension(70, 23)); cancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 0); buttonPanel.add(cancelButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5); add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed cancelled=true; parent.setVisible(false); }//GEN-LAST:event_cancelButtonActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed cancelled=false; parent.setVisible(false); }//GEN-LAST:event_okButtonActionPerformed private void editRelationsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editRelationsButtonActionPerformed TopicTreeRelationsEditor editor = new TopicTreeRelationsEditor(); editor.open(Wandora.getWandora()); if(editor.wasCancelled()) return; updateRelationsUI(editor.readRelationTypes(), getSelectedRelations()); if(parent != null) { parent.revalidate(); parent.repaint(); } }//GEN-LAST:event_editRelationsButtonActionPerformed public boolean wasCancelled() { return cancelled; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton cancelButton; private javax.swing.JButton editRelationsButton; private javax.swing.JPanel jPanel2; private javax.swing.JLabel nameLabel; private javax.swing.JTextField nameTextField; private javax.swing.JButton okButton; private javax.swing.JPanel relationFillerPanel; private javax.swing.JPanel relationsContainerPanel; private javax.swing.JPanel relationsPanel; private javax.swing.JScrollPane relationsScrollPane; private javax.swing.JButton rootButton; private javax.swing.JLabel rootLabel; private javax.swing.JTextField rootTextField; // End of variables declaration//GEN-END:variables }
12,237
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTreeModel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/tree/TopicTreeModel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicTreeModel.java * * Created on 27. joulukuuta 2005, 23:04 * */ package org.wandora.application.gui.tree; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import org.wandora.application.gui.TopicGuiWrapper; import org.wandora.topicmap.Locator; import org.wandora.topicmap.SchemaBox; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.GripCollections; /** * * @author olli, akivela */ public class TopicTreeModel implements TreeModel { private Map<TopicGuiWrapper, TopicGuiWrapper[]> children; private Set<TreeModelListener> listeners; private TopicGuiWrapper rootNode; private Set<Locator> visibleTopics; private int visibleTopicCount = 0; private List<TopicTreeRelation> associations; private TopicTree tree; public TopicTreeModel(Topic rootTopic, List<TopicTreeRelation> associations, TopicTree tree) { this.associations=associations; this.tree=tree; children=new ConcurrentHashMap<>(); listeners=new LinkedHashSet<>(); rootNode=new TopicGuiWrapper(rootTopic); visibleTopics=new LinkedHashSet<Locator>(); visibleTopicCount = 0; try { visibleTopics.addAll(rootTopic.getSubjectIdentifiers()); visibleTopicCount++; } catch(TopicMapException tme){ tme.printStackTrace(); } } private Object expansionWaiter=new Object(); public void waitExpansionDone(final TopicGuiWrapper node){ synchronized(expansionWaiter){ while(true){ TopicGuiWrapper[] c=(TopicGuiWrapper[])children.get(node); if(c==null || c.length!=1) return; if(c.length==1 && !c[0].associationType.equals(TopicGuiWrapper.PROCESSING_TYPE)) return; try { expansionWaiter.wait(); } catch(InterruptedException ie){ return; } } } } public Set<Locator> getVisibleTopics() { return visibleTopics; } public int getVisibleTopicCount() { return visibleTopicCount; } public void childrenModified(TopicGuiWrapper node){ Object debug=children.remove(node); childrenModifiedNoRemove(node); } private void childrenModifiedNoRemove(final TopicGuiWrapper node){ Iterator<TreeModelListener> iter=listeners.iterator(); while(iter.hasNext()){ javax.swing.event.TreeModelListener l=iter.next(); // l.treeStructureChanged(new javax.swing.event.TreeModelEvent(this,new Object[]{rootNode})); l.treeStructureChanged(new javax.swing.event.TreeModelEvent(this,node.path)); } tree.refreshSize(); } public Object getChildFor(TopicGuiWrapper node,Topic t){ TopicGuiWrapper[] cs=getChildren(node); for(int i=0;i<cs.length;i++){ // if(cs[i].topic==t) return cs[i]; if(cs[i].topic.equals(t)) return cs[i]; } return null; } private TopicGuiWrapper[] getChildren(Object node){ return getChildren((TopicGuiWrapper)node); } private TopicGuiWrapper[] getChildren(final TopicGuiWrapper node) { if(children.containsKey(node)) { return (TopicGuiWrapper[]) children.get(node); } final Object waitObject=new Object(); final int[] state=new int[1]; state[0]=0; // simple way to wrap a modifyable int in an object // 0 - not ready, original waiting // 1 - ready, original waiting // 2 - not ready, original not waiting // 3 - ready, original not waiting final Thread originalThread=Thread.currentThread(); Thread t = new Thread(){ @Override public void run(){ int i=0; ArrayList<TopicGuiWrapper> ts=new ArrayList<TopicGuiWrapper>(); String instancesIcon=null; for(TopicTreeRelation a : associations){ if("Instances".equalsIgnoreCase(a.name)){ instancesIcon=a.icon; continue; } Collection<Topic> s=null; try { i = 99999; s = SchemaBox.getSubClassesOf(node.topic,a.subSI,a.assocSI,a.superSI); if(s != null && s.size() > 0) { s = TMBox.sortTopics(s, null); Iterator<Topic> iter=s.iterator(); while(iter.hasNext() && --i > 0){ ts.add(new TopicGuiWrapper(iter.next(),a.icon,a.name,node.path)); } } } catch(Exception tme) { tme.printStackTrace(); } } if(instancesIcon!=null){ try { i=99999; Collection<Topic> c=node.topic.getTopicMap().getTopicsOfType(node.topic); if(c != null && c.size() > 0) { c=TMBox.sortTopics(c, null); Iterator<Topic> iter=c.iterator(); while(iter.hasNext() && --i > 0){ ts.add(new TopicGuiWrapper(iter.next(),instancesIcon,"Instances",node.path)); } } } catch(Exception tme) { tme.printStackTrace(); } } TopicGuiWrapper[] tsa=new TopicGuiWrapper[0]; try{ tsa = GripCollections.collectionToArray(ts, TopicGuiWrapper.class); synchronized(visibleTopics) { for(int j=0;j<tsa.length;j++) { if(tsa[j] != null && tsa[j].topic != null && !tsa[j].topic.isRemoved()) { visibleTopics.addAll(tsa[j].topic.getSubjectIdentifiers()); visibleTopicCount++; } } } //System.out.println("visible topics (locators): "+visibleTopics.size()); } catch(Exception tme) { tme.printStackTrace(); } synchronized(waitObject){ synchronized(expansionWaiter) { children.put(node,tsa); state[0]|=1; if((state[0]&2)==0 ){ waitObject.notify(); } else{ childrenModifiedNoRemove(node); } expansionWaiter.notifyAll(); } } } }; synchronized(waitObject){ //t.run(); t.start(); try{ waitObject.wait(2000); // waitObject.wait(); } catch(InterruptedException ie){ ie.printStackTrace(); } state[0]|=2; if((state[0]&1)>0) { return (TopicGuiWrapper[])children.get(node); } else { TopicGuiWrapper[] tsa=new TopicGuiWrapper[0]; // tsa[0]=new TopicGuiWrapper(null,"gui/icons/topictree/cycle01.png",TopicGuiWrapper.PROCESSING_TYPE,node.path); // tsa[0]=new TopicGuiWrapper(null,null,TopicGuiWrapper.PROCESSING_TYPE,node.path); // children.put(node,tsa); return tsa; } } } public void update() { TopicGuiWrapper node; for(Object n : children.keySet()) { try { node = (TopicGuiWrapper) n; getChildren(node); } catch(Exception ex) { ex.printStackTrace(); } } } @Override public void addTreeModelListener(javax.swing.event.TreeModelListener l) { listeners.add(l); } public TopicGuiWrapper getRootNode() { return this.rootNode; } @Override public Object getChild(Object parent, int index) { return getChildren(parent)[index]; } @Override public int getChildCount(Object parent) { return getChildren(parent).length; } @Override public int getIndexOfChild(Object parent, Object child) { if(parent==null || child==null) return -1; TopicGuiWrapper[] cs=getChildren(parent); for(int i=0;i<cs.length;i++){ // if(cs[i]==child) return i; if(cs[i].equals(child)) return i; } return -1; } @Override public Object getRoot() { return rootNode; } @Override public boolean isLeaf(Object node) { TopicGuiWrapper wrapper=(TopicGuiWrapper)node; if(wrapper.associationType.equals(TopicGuiWrapper.PROCESSING_TYPE)) return true; else return false; } @Override public void removeTreeModelListener(javax.swing.event.TreeModelListener l) { listeners.remove(l); } @Override public void valueForPathChanged(TreePath path, Object newValue) { } public TreePath getPathFor(Topic t) { if(t == null) return null; try { if(!visibleTopics.contains(t.getOneSubjectIdentifier())) { return null; } for(TopicGuiWrapper node : children.keySet()) { if(t.mergesWithTopic(node.topic)) { return node.path; } for(TopicGuiWrapper childNode : children.get(node)) { if(t.mergesWithTopic(childNode.topic)) { return childNode.path; } } } } catch(Exception e) { e.printStackTrace(); } return null; } }
11,521
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTree.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/tree/TopicTree.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicTree.java * * Created on 27. joulukuuta 2005, 23:26 * */ package org.wandora.application.gui.tree; import static org.wandora.utils.Tuples.t2; import java.awt.Point; import java.awt.Rectangle; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import javax.swing.DropMode; import javax.swing.JComponent; import javax.swing.JPopupMenu; import javax.swing.JTree; import javax.swing.JViewport; import javax.swing.TransferHandler; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.wandora.application.Wandora; import org.wandora.application.WandoraMenuManager; import org.wandora.application.gui.Clipboardable; import org.wandora.application.gui.DnDHelper; import org.wandora.application.gui.TopicGuiWrapper; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleTree; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.ClipboardBox; import org.wandora.utils.GripCollections; import org.wandora.utils.Tuples.T2; /** * TopicTree implements <code>JTree</code> type structure for topics. * Each tree node represents single topic. Node's children depend * on associations and instance-of relations of node topic. Associations * represented as a parent-child relation are user configurable. Also * TopicTree's root node is user configurable. * * @author olli, akivela */ public class TopicTree extends SimpleTree implements Clipboardable, MouseListener, TopicMapListener /*, DragSourceListener, DragGestureListener*/ { private static final long serialVersionUID = 1L; private boolean needsRefresh; private ArrayList<TopicTreeRelation> selectedAs; private HashSet<Locator> selectedAsLocators; protected String rootTopicSI; protected Topic rootTopic; protected TopicTreeModel model; protected Wandora wandora; private MouseEvent mouseEvent; private TopicTreeRelation[] associations; private boolean openWithDoubleClick; private TopicTreePanel chooser; /** Creates a new instance of TopicTree */ public TopicTree(String rootTopicSI, Wandora wandora) throws TopicMapException { this(rootTopicSI, wandora, null); } public TopicTree(String rootTopicSI, Wandora wandora, TopicTreePanel chooser) throws TopicMapException { this(rootTopicSI,wandora,GripCollections.newHashSet("Instances","Subclasses"),new TopicTreeRelation[]{ new TopicTreeRelation("Instances","","","","gui/icons/topictree/instanceof.png"), new TopicTreeRelation("Subclasses",XTMPSI.SUBCLASS,XTMPSI.SUPERCLASS_SUBCLASS,XTMPSI.SUPERCLASS,"gui/icons/topictree/supersubclass.png") },chooser); } public TopicTree(String rootTopicSI, Wandora wandora, Set<String> selectedAssociations, TopicTreeRelation[] associations) throws TopicMapException { this(rootTopicSI,wandora,selectedAssociations,associations,null); } public TopicTree(String rootTopicSI, Wandora wandora, Set<String> selectedAssociations, TopicTreeRelation[] associations,TopicTreePanel chooser) throws TopicMapException { this.rootTopicSI = rootTopicSI; this.wandora = wandora; this.associations = associations; this.chooser = chooser; this.openWithDoubleClick = true; setToggleClickCount(4); //initMenuStructure(); // this.model = new TopicTreeModel(rootTopic,associations); // setModel(model); updateModel(rootTopicSI,selectedAssociations,associations); getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); TopicTreeTopicRenderer topicTreeCellRenderer = new TopicTreeTopicRenderer(this); setCellRenderer(topicTreeCellRenderer); TopicTreeTopicEditor topicEditor = new TopicTreeTopicEditor(wandora, this, new SimpleField(), topicTreeCellRenderer); setCellEditor(topicEditor); this.setDragEnabled(true); this.setDropMode(DropMode.ON); this.setTransferHandler(new TopicTreeTransferHandler()); setExpandsSelectedPaths(true); this.addMouseListener(this); setEditable(true); this.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener(){ @Override public void treeCollapsed(javax.swing.event.TreeExpansionEvent event){ refreshSize(); } @Override public void treeExpanded(javax.swing.event.TreeExpansionEvent event){ refreshSize(); } }); } private <T> boolean collectionsOverlap(Collection<T> a,Collection<T> b){ if(a.size()>b.size()){ Collection<T> c=a; a=b; b=c; } for(T o : a){ if(b.contains(o)) return true; } return false; } public boolean isBroken(){ return model==null; } public void setNeedsRefresh(boolean value){ needsRefresh=value; } public boolean getNeedsRefresh(){ return needsRefresh; } // ---------------------------------------------------- TopicMapListener --- @Override public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { if(needsRefresh) return; if( (added!=null && rootTopicSI != null && rootTopicSI.equals(added.toExternalForm())) || (removed!=null && rootTopicSI.equals(removed.toExternalForm())) ){ setNeedsRefresh(true); } if(model==null) return; if(t == null) return; if(collectionsOverlap(t.getSubjectIdentifiers(),model.getVisibleTopics()) || (added!=null && model.getVisibleTopics().contains(added)) || (removed!=null && model.getVisibleTopics().contains(removed)) ) setNeedsRefresh(true); } @Override public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { if(needsRefresh || model==null) return; if(t == null) return; if(collectionsOverlap(t.getSubjectIdentifiers(),model.getVisibleTopics())) setNeedsRefresh(true); } @Override public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { if(needsRefresh || model==null) return; if(added!=null && collectionsOverlap(added.getSubjectIdentifiers(),model.getVisibleTopics())) setNeedsRefresh(true); else if(removed!=null && collectionsOverlap(removed.getSubjectIdentifiers(),model.getVisibleTopics())) setNeedsRefresh(true); } @Override public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { if(needsRefresh || model==null) return; if(t == null) return; if(collectionsOverlap(t.getSubjectIdentifiers(),model.getVisibleTopics())) setNeedsRefresh(true); } @Override public void topicDataChanged(Topic t,Topic type,Topic version,String newValue,String oldValue) throws TopicMapException { } @Override public void topicSubjectLocatorChanged(Topic t,Locator newLocator,Locator oldLocator) throws TopicMapException { } @Override public void topicRemoved(Topic t) throws TopicMapException { if(needsRefresh || model==null) return; if(t == null) return; if(collectionsOverlap(t.getSubjectIdentifiers(),model.getVisibleTopics())) setNeedsRefresh(true); } @Override public void topicChanged(Topic t) throws TopicMapException { if(needsRefresh || model==null) return; if(t == null) return; if(collectionsOverlap(t.getSubjectIdentifiers(),model.getVisibleTopics())) setNeedsRefresh(true); } @Override public void associationTypeChanged(Association a,Topic newType,Topic oldType) throws TopicMapException { if(needsRefresh || model==null) return; if( (oldType!=null && collectionsOverlap(oldType.getSubjectIdentifiers(),model.getVisibleTopics())) || (newType!=null && collectionsOverlap(newType.getSubjectIdentifiers(),model.getVisibleTopics())) ){ for(Topic r : a.getRoles()){ if(collectionsOverlap(a.getPlayer(r).getSubjectIdentifiers(),model.getVisibleTopics())){ setNeedsRefresh(true); break; } } } } @Override public void associationPlayerChanged(Association a,Topic role,Topic newPlayer,Topic oldPlayer) throws TopicMapException { if(needsRefresh || model==null) return; if(a == null) return; boolean cont=false; for(int i=0;i<associations.length;i++) { if(associations[i].assocSI != null) { Locator l=a.getTopicMap().createLocator(associations[i].assocSI); if(a.getType().getSubjectIdentifiers().contains(l)){ cont=true; break; } } } if(!cont) return; if(newPlayer!=null && collectionsOverlap(newPlayer.getSubjectIdentifiers(),model.getVisibleTopics())) setNeedsRefresh(true); else if(newPlayer!=null && collectionsOverlap(newPlayer.getSubjectIdentifiers(),model.getVisibleTopics())) setNeedsRefresh(true); } @Override public void associationRemoved(Association a) throws TopicMapException { if(needsRefresh || model==null) return; if(a == null) return; boolean cont=false; for(int i=0;i<associations.length;i++) { if(associations[i].assocSI != null) { Locator l=a.getTopicMap().createLocator(associations[i].assocSI); if(a.getType().getSubjectIdentifiers().contains(l)){ cont=true; break; } } } if(!cont) return; for(Topic r : a.getRoles()) { if(collectionsOverlap(a.getPlayer(r).getSubjectIdentifiers(),model.getVisibleTopics())) { setNeedsRefresh(true); break; } } } @Override public void associationChanged(Association a) throws TopicMapException { needsRefresh=true; } // --------------------------------------------------- /TopicMapListener --- public void setOpenWithDoubleClick(boolean value){ openWithDoubleClick=value; } public void refreshSize(){ int maxx=0; int maxy=0; for(int i=0;i<getRowCount();i++){ java.awt.Rectangle rect=getRowBounds(i); if(rect==null) continue; if(rect.getMaxX()>maxx) maxx=(int)rect.getMaxX(); if(rect.getMaxY()>maxy) maxy=(int)rect.getMaxY(); } this.setPreferredSize(new java.awt.Dimension(maxx,maxy)); this.setMinimumSize(new java.awt.Dimension(maxx,maxy)); this.setMaximumSize(new java.awt.Dimension(maxx,maxy)); getParent().invalidate(); getParent().getParent().validate(); } private void recreateModel() throws TopicMapException { TopicMap topicMap = wandora.getTopicMap(); if(rootTopicSI != null) { rootTopic=topicMap.getTopic(rootTopicSI); if(rootTopic==null){ System.out.println("Topic tree root topic not found ("+rootTopicSI+")"); /* System.out.println("Root topic not found in topic map. Trying default root '"+WandoraManager.WANDORACLASS_SI+"'."); rootTopic=topicMap.getTopic(WandoraManager.WANDORACLASS_SI); if(rootTopic == null) { System.out.println("Default root not found. Trying XTM base '"+XTMPSI.XTM1_BASE+"'."); rootTopic=topicMap.getTopic(XTMPSI.XTM1_BASE); if(rootTopic == null) { // TODO: WHAT NOW! THERE IS NO SUFFICIENT ROOT FOR THE TREE!!! } }*/ } } if(rootTopic!=null){ TopicTreeModel newModel=new TopicTreeModel(rootTopic,selectedAs,this); this.model=newModel; // System.out.println("Resetting tree model "+selectedAs.size()); setModel(newModel); needsRefresh=false; if(chooser!=null) chooser.setTreeEnabled(true); } else{ System.out.println("Root topic not found for topic tree. Disabling tree."); if(chooser!=null) chooser.setTreeEnabled(false); this.model=null; // setModel(null); needsRefresh=false; } } /** * @param rootSI Subject identifier of the topic that is used as root for the tree * @param selectedAssociations Names of the associations in associations array that * are used in this topic tree chooser. * @param associations A list of tree association types. Not all of them are * necessarily used in this topic tree chooser. selectedAssociations * contains the names of the used association types. */ public void updateModel(String rootSI, Set<String> selectedAssociations, TopicTreeRelation[] associations ) throws TopicMapException{ selectedAs=new ArrayList<TopicTreeRelation>(); selectedAsLocators=new HashSet<Locator>(); for(String selected : selectedAssociations) { for(int i=0;i<associations.length;i++) { if(associations[i].name.equals(selected)) { selectedAs.add(associations[i]); if(associations[i].assocSI != null && associations[i].assocSI.length() != 0) { selectedAsLocators.add(new Locator(associations[i].assocSI)); } break; } } } this.rootTopicSI=rootSI; recreateModel(); this.revalidate(); this.repaint(); } public boolean selectTopic(Topic t) { TreePath path = model.getPathFor(t); if(path != null) { // System.out.println(path.toString()); // Able to get the exact node here setExpandsSelectedPaths(true); setSelectionPath(path); scrollPathToVisible(path); requestFocus(); return true; } return false; } public Topic getSelection() { TreePath path = getSelectionPath(); if(path != null) { return ((TopicGuiWrapper)path.getLastPathComponent()).topic; } else { if(mouseEvent != null) return getTopicAt(mouseEvent); else return null; } } public void update() { } public ArrayList<T2<Locator,String>> getLocatorPath(TreePath tp) throws TopicMapException { Object[] path=tp.getPath(); ArrayList<T2<Locator,String>> lpath=new ArrayList<T2<Locator,String>>(); for(int i=0;i<path.length;i++){ TopicGuiWrapper wrapper=((TopicGuiWrapper)path[i]); lpath.add(t2(wrapper.topic.getOneSubjectIdentifier(),wrapper.associationType)); } return lpath; } public TreePath getTreePath(ArrayList<T2<Locator,String>> path) throws TopicMapException { if(model==null) return null; Object parent=model.getRootNode(); TreePath treePath=new TreePath(parent); ILoop: for(int i=1;i<path.size();i++){ int count=model.getChildCount(parent); T2<Locator,String> p=path.get(i); for(int j=0;j<count;j++){ TopicGuiWrapper child=(TopicGuiWrapper)model.getChild(parent,j); if(child.topic.getSubjectIdentifiers().contains(p.e1) && child.associationType.equals(p.e2)){ parent=child; treePath=treePath.pathByAddingChild(child); continue ILoop; } } return null; } return treePath; } public ArrayList<ArrayList<T2<Locator,String>>> getAllExpandedPaths(TreePath root) throws TopicMapException { ArrayList<ArrayList<T2<Locator,String>>> expandedPaths=new ArrayList<ArrayList<T2<Locator,String>>>(); Enumeration<TreePath> e=this.getExpandedDescendants(root); if(e==null) return expandedPaths; while(e.hasMoreElements()){ TreePath tp=e.nextElement(); expandedPaths.add(getLocatorPath(tp)); expandedPaths.addAll(getAllExpandedPaths(tp)); } return expandedPaths; } public void expandPath(ArrayList<T2<Locator,String>> path) throws TopicMapException { TreePath treePath=getTreePath(path); if(treePath!=null) expandPath(treePath); } public synchronized void refresh() throws TopicMapException { ArrayList<ArrayList<T2<Locator,String>>> expandedPaths=null; if(model!=null) expandedPaths=getAllExpandedPaths(getPathForRow(0)); ArrayList<T2<Locator,String>> selected=null; ArrayList<T2<Locator,String>> scrollPath=null; JViewport vp=org.wandora.utils.swing.GuiTools.getViewport(this); if(vp!=null && model!=null) { int viewPos=(int)vp.getViewPosition().getY(); TreePath path=getClosestPathForLocation(0,viewPos); scrollPath=getLocatorPath(path); } if(model!=null && getSelectionPath()!=null) { selected=getLocatorPath(getSelectionPath()); } // if(model != null) model.childrenModified(model.getRootNode()); recreateModel(); if(expandedPaths!=null){ for(ArrayList<T2<Locator,String>> tp : expandedPaths){ TreePath path=getTreePath(tp); if(path==null) continue; expandPath(path); model.waitExpansionDone((TopicGuiWrapper)path.getLastPathComponent()); } } if(model!=null && selected!=null) setSelectionPath(getTreePath(selected)); if(model!=null && scrollPath!=null){ TreePath tp = getTreePath(scrollPath); vp.revalidate(); if(tp != null) { Rectangle rect=getPathBounds(tp); if(rect != null) { vp.setViewPosition(new Point(0,rect.y)); } } } /* TreeSelectionModel sm=getSelectionModel(); TreePath path=getSelectionPath(); try { this.model = new TopicTreeModel(this.rootTopic); setModel(this.model); expandPath(path); setSelectionPath(path); //this.setSelectionModel(sm); } catch(Exception e) { e.printStackTrace(); } **/ } // ------------------------------------------------------------------------- @Override public void cut() { copy(); } private boolean autoCreateTopicsInPaste = false; @Override public void paste() { String tabText = ClipboardBox.getClipboard(); StringTokenizer tabLines = new StringTokenizer(tabText, "\n"); autoCreateTopicsInPaste = false; while(tabLines.hasMoreTokens()) { String tabLine = tabLines.nextToken(); StringTokenizer topicIdentifiers = new StringTokenizer(tabLine, "\t"); try { String topicIdentifier = null; while(topicIdentifiers.hasMoreTokens()) { topicIdentifier = topicIdentifiers.nextToken(); if(topicIdentifier != null && topicIdentifier.length() > 0) { Topic pastedTopic = getTopicForIdentifier(topicIdentifier); if(pastedTopic == null) { boolean createTopicInPaste = false; if(!autoCreateTopicsInPaste) { int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Can't find a topic for identifier '"+topicIdentifier+"'. Would you like to create a topic for '"+topicIdentifier+"'?", "Create new topic?", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION); if(a == WandoraOptionPane.YES_OPTION) { createTopicInPaste = true; } else if(a == WandoraOptionPane.YES_TO_ALL_OPTION) { autoCreateTopicsInPaste = true; } else if(a == WandoraOptionPane.CANCEL_OPTION) { return; } } if(autoCreateTopicsInPaste || createTopicInPaste) { TopicMap tm = Wandora.getWandora().getTopicMap(); if(tm != null) { boolean identifierIsURL = false; try { URL u = new URL(topicIdentifier); identifierIsURL = true; } catch(Exception e) {} pastedTopic = tm.createTopic(); if(identifierIsURL) { pastedTopic.addSubjectIdentifier(new Locator(topicIdentifier)); } else { pastedTopic.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); pastedTopic.setBaseName(topicIdentifier); } } } } if(pastedTopic != null) { Topic t = getSelection(); if(t != null) { pastedTopic.addType(t); } } } } } catch(Exception e) { } } } @Override public void copy() { ClipboardBox.setClipboard(getCopyString()); } public String getCopyString() { StringBuilder sb = new StringBuilder(""); Topic selectedTopic = getSelection(); if(selectedTopic != null) { sb.append(TopicToString.toString(selectedTopic)); } else {} return sb.toString(); } protected Topic getTopicForIdentifier(String id) { TopicMap tm = wandora.getTopicMap(); Topic t = null; try { t = tm.getTopicWithBaseName(id); if(t == null) { t = tm.getTopic(id); if(t == null) { t = tm.getTopicBySubjectLocator(new Locator(id)); } } } catch(Exception e) { } return t; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- protected void handlePopupMouseEvent(java.awt.event.MouseEvent e) { try { if(e.isPopupTrigger()) { JPopupMenu popupMenu = UIBox.makePopupMenu(WandoraMenuManager.getTreeMenu(wandora, this), wandora); setSelectionRow(getClosestRowForLocation(e.getX(),e.getY())); popupMenu.show(e.getComponent(),e.getX(),e.getY()); } } catch(Exception ex) { ex.printStackTrace(); } } @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { if(mouseEvent != null) { try { this.mouseEvent = mouseEvent; if(openWithDoubleClick && mouseEvent.getClickCount() == 2) { if(getSelection() != null && wandora != null) { wandora.applyChangesAndOpen(getSelection()); } } } catch(Exception e) { e.printStackTrace(); } handlePopupMouseEvent(mouseEvent); } } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { handlePopupMouseEvent(mouseEvent); } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { handlePopupMouseEvent(mouseEvent); } public Object getValueAt(MouseEvent e) { return getTopicAt(e.getX(), e.getY()); } public Object getValueAt(Point p) { return getValueAt(p.x, p.y); } public Object getValueAt(int x, int y) { try { int selRow = getRowForLocation(x, y); TreePath selPath = getPathForLocation(x, y); if(selRow != -1) { return (TopicGuiWrapper) selPath.getLastPathComponent(); } } catch(Exception e) { wandora.handleError(e); } return null; } public Topic getTopicAt(MouseEvent e) { return getTopicAt(e.getX(), e.getY()); } public Topic getTopicAt(Point point) { return getTopicAt(point.x, point.y); } public Topic getTopicAt(int x, int y) { Object object = getValueAt(x, y); if(object != null) { if(object instanceof TopicGuiWrapper) { TopicGuiWrapper wrapper = (TopicGuiWrapper) object; return wrapper.topic; } } return null; } // ------------------------------------------------------------------------- // ----------------------------------------------------------------- DND --- // ------------------------------------------------------------------------- public static class TopicTreeTransferable extends DnDHelper.WandoraTransferable { public static final DataFlavor treeDataFlavor=new DataFlavor(TopicGuiWrapper.class,"TopicTree node"); protected TopicGuiWrapper wrapper; public TopicTreeTransferable(TopicGuiWrapper wrapper){ this.wrapper=wrapper; if(this.wrapper!=null) setTopic(this.wrapper.topic); } @Override public void updateFlavors(){ super.updateFlavors(); if(this.wrapper==null) return; DataFlavor[] old=supportedFlavors; supportedFlavors=new DataFlavor[old.length+1]; supportedFlavors[0]=treeDataFlavor; System.arraycopy(old, 0, supportedFlavors, 1, old.length); } @Override public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { if(wrapper!=null && flavor.equals(treeDataFlavor)) return wrapper; else return super.getTransferData(flavor); } } private class TopicTreeTransferHandler extends TransferHandler { @Override public boolean canImport(TransferSupport support) { if(!support.isDrop()) return false; return support.isDataFlavorSupported(TopicTreeTransferable.treeDataFlavor) || support.isDataFlavorSupported(DataFlavor.stringFlavor); } @Override protected Transferable createTransferable(JComponent c) { TreePath path=getSelectionPath(); if(path==null) return new TopicTreeTransferable(null); else return new TopicTreeTransferable((TopicGuiWrapper)path.getLastPathComponent()); } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY_OR_MOVE; } @Override public boolean importData(TransferSupport support) { if(!support.isDrop()) return false; try{ if(support.isDataFlavorSupported(TopicTreeTransferable.treeDataFlavor)) { TopicGuiWrapper node=(TopicGuiWrapper)support.getTransferable().getTransferData(TopicTreeTransferable.treeDataFlavor); if(node.path.getPathCount()<2) { WandoraOptionPane.showMessageDialog(TopicTree.this.wandora,"Can't move root, drop cancelled.", "Drop cancelled"); return false; } TopicGuiWrapper parent=(TopicGuiWrapper)node.path.getParentPath().getLastPathComponent(); int action=support.getDropAction(); String typeName=node.associationType; TopicTreeRelation type=null; for(int i=0;i<associations.length;i++){ if(associations[i].name.equals(typeName)){ type=associations[i]; break; } } if(type==null){ WandoraOptionPane.showMessageDialog(TopicTree.this.wandora,"Couldn't find tree association type, drop cancelled.", "Drop cancelled"); return false; } JTree.DropLocation location=(JTree.DropLocation)support.getDropLocation(); TreePath dropPath=location.getPath(); if(dropPath==null){ WandoraOptionPane.showMessageDialog(TopicTree.this.wandora,"Invalid drop location, drop cancelled.", "Drop cancelled"); return false; } TopicGuiWrapper locationNode=(TopicGuiWrapper)dropPath.getLastPathComponent(); try{ if(parent.topic.mergesWithTopic(locationNode.topic)){ WandoraOptionPane.showMessageDialog(TopicTree.this.wandora, "Drop location is same as current parent, drop cancelled.", "Drop cancelled"); return false; } if(action==TransferHandler.MOVE && locationNode.topic.mergesWithTopic(node.topic)){ int c=WandoraOptionPane.showConfirmDialog(TopicTree.this.wandora, "Are you sure you want to move the item on itself?"); if(c!=WandoraOptionPane.YES_OPTION) return false; } if(type.name.equals("Instances")){ if(action==TransferHandler.MOVE){ node.topic.removeType(parent.topic); } node.topic.addType(locationNode.topic); } else{ TopicMap tm=TopicTree.this.wandora.getTopicMap(); Topic atype=tm.getTopic(type.assocSI); Topic superTopic=tm.getTopic(type.superSI); Topic subTopic=tm.getTopic(type.subSI); if(atype==null || superTopic==null || subTopic==null){ WandoraOptionPane.showMessageDialog(TopicTree.this.wandora,"Couldn't find tree association topics, drop cancelled."); return false; } if(action==TransferHandler.MOVE){ Collection<Association> as=node.topic.getAssociations(atype,subTopic); for(Association a : as){ Topic p=a.getPlayer(superTopic); if(p==null) continue; if(p.mergesWithTopic(parent.topic)){ a.remove(); break; } } } Association a=tm.createAssociation(atype); a.addPlayer(locationNode.topic, superTopic); a.addPlayer(node.topic,subTopic); } } catch(TopicMapException tme){ tme.printStackTrace(); return false; } doRefresh(); return true; } else { try{ TopicMap tm=TopicTree.this.wandora.getTopicMap(); List<Topic> topics=DnDHelper.getTopicList(support, tm, true); if(topics==null) return false; JTree.DropLocation location=(JTree.DropLocation)support.getDropLocation(); TreePath dropPath=location.getPath(); if(dropPath==null){ WandoraOptionPane.showMessageDialog(TopicTree.this.wandora,"Invalid drop location, drop cancelled."); return false; } TopicGuiWrapper locationNode=(TopicGuiWrapper)dropPath.getLastPathComponent(); for(Topic t :topics){ t.addType(locationNode.topic); } doRefresh(); return true; } catch(TopicMapException tme){ tme.printStackTrace(); return false; } } } catch(UnsupportedFlavorException ufe){ufe.printStackTrace();} catch(IOException ioe){ioe.printStackTrace();} return false; } public void doRefresh(){ TopicTree.this.wandora.doRefresh(); } } }
36,495
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTreeRelation.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/tree/TopicTreeRelation.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.tree; /** * TopicTreeRelation specifies a relation i.e. association viewed in TopicTree. * * @author akivela */ public class TopicTreeRelation { public String name; public String subSI,assocSI,superSI; public String icon; public TopicTreeRelation() {} public TopicTreeRelation(String name,String subSI,String assocSI,String superSI,String icon) { this.name=name; this.subSI=subSI; this.assocSI=assocSI; this.superSI=superSI; this.icon=icon; } public TopicTreeRelation(String subSI,String assocSI,String superSI,String icon) { this(null,subSI,assocSI,superSI,icon); } }
1,515
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicMapFileView.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/filechooser/TopicMapFileView.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicMapFileView.java * * Created on 11. huhtikuuta 2006, 18:16 * */ package org.wandora.application.gui.filechooser; import java.io.File; import javax.swing.Icon; import javax.swing.filechooser.FileView; import org.wandora.application.gui.UIBox; /** * * @author akivela */ public class TopicMapFileView extends FileView { Icon xtmFileIcon = null; Icon ltmFileIcon = null; Icon jtmFileIcon = null; /** Creates a new instance of TopicMapFileView */ public TopicMapFileView() { try { xtmFileIcon = UIBox.getIcon("gui/icons/xtm_topicmap_file.png"); } catch(Exception e) {} try { ltmFileIcon = UIBox.getIcon("gui/icons/ltm_topicmap_file.png"); } catch(Exception e) {} try { jtmFileIcon = UIBox.getIcon("gui/icons/jtm_topicmap_file.png"); } catch(Exception e) {} } @Override public String getTypeDescription(File f) { if(f != null) { String uppercaseName = f.getName().toUpperCase(); if(uppercaseName.endsWith(".XTM")) return "XML topic map file"; if(uppercaseName.endsWith(".XTM1")) return "XML 1.0 topic map file"; if(uppercaseName.endsWith(".XTM10")) return "XML 1.0 topic map file"; if(uppercaseName.endsWith(".XTM2")) return "XML 2.0 topic map file"; if(uppercaseName.endsWith(".XTM20")) return "XML 2.0 topic map file"; if(uppercaseName.endsWith(".LTM")) return "Linear topic map file"; if(uppercaseName.endsWith(".JTM")) return "JSON topic map file"; } return null; } @Override public Icon getIcon(File f) { if(f != null) { String uppercaseName = f.getName().toUpperCase(); if(uppercaseName.endsWith(".XTM")) return xtmFileIcon; if(uppercaseName.endsWith(".XTM1")) return xtmFileIcon; if(uppercaseName.endsWith(".XTM10")) return xtmFileIcon; if(uppercaseName.endsWith(".XTM2")) return xtmFileIcon; if(uppercaseName.endsWith(".XTM20")) return xtmFileIcon; if(uppercaseName.endsWith(".LTM")) return ltmFileIcon; if(uppercaseName.endsWith(".JTM")) return jtmFileIcon; } return null; } }
3,061
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WPRFileView.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/filechooser/WPRFileView.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicMapFileView.java * * Created on 11. huhtikuuta 2006, 18:16 * */ package org.wandora.application.gui.filechooser; import java.io.File; import javax.swing.Icon; import javax.swing.filechooser.FileView; import org.wandora.application.gui.UIBox; /** * * @author akivela */ public class WPRFileView extends FileView { Icon wprFileIcon = null; /** Creates a new instance of WPRFileView */ public WPRFileView() { try { wprFileIcon = UIBox.getIcon("gui/icons/wpr_file.png"); } catch(Exception e) {} } @Override public String getTypeDescription(File f) { if(f != null) { String uppercaseName = f.getName().toUpperCase(); if(uppercaseName.endsWith(".WPR")) return "Wandora project file"; } return null; } @Override public Icon getIcon(File f) { if(f != null) { String uppercaseName = f.getName().toUpperCase(); if(uppercaseName.endsWith(".WPR")) return wprFileIcon; } return null; } }
1,888
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
XTM2FileFilter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/filechooser/XTM2FileFilter.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * XTM2FileFilter.java * * */ package org.wandora.application.gui.filechooser; import java.io.File; /** * * @author akivela */ public class XTM2FileFilter extends javax.swing.filechooser.FileFilter { /** Creates a new instance of XTM2FileFilter */ public XTM2FileFilter() { } @Override public boolean accept(File f) { if(f != null) { if (f.isDirectory()) { return true; } String uppercaseName = f.getName().toUpperCase(); if(uppercaseName.endsWith(".XTM20") || uppercaseName.endsWith(".XTM2") || uppercaseName.endsWith(".XTM")) { return true; } } return false; } //The description of this filter @Override public String getDescription() { return "XTM 2.0 topic map"; } }
1,705
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WPRFileChooser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/filechooser/WPRFileChooser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * WPRFileChooser.java * * Created on 9. huhtikuuta 2006, 19:17 */ package org.wandora.application.gui.filechooser; import org.wandora.application.gui.simple.SimpleFileChooser; /** * * @author akivela */ public class WPRFileChooser extends SimpleFileChooser { private static final long serialVersionUID = 1L; public WPRFileChooser() { initialize(); } public WPRFileChooser(String currentPath) { super(currentPath); initialize(); } private void initialize() { setFileFilter(new WPRFileFilter()); setFileView(new WPRFileView()); setFileSelectionMode(WPRFileChooser.FILES_AND_DIRECTORIES); } }
1,505
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AnyTopiMapFileFilter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/filechooser/AnyTopiMapFileFilter.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * AnyTopiMapFileFilter.java * * Created on 11. huhtikuuta 2006, 18:01 * */ package org.wandora.application.gui.filechooser; import java.io.File; /** * * @author akivela */ public class AnyTopiMapFileFilter extends javax.swing.filechooser.FileFilter { /** Creates a new instance of AnyTopiMapFileFilter */ public AnyTopiMapFileFilter() { } @Override public boolean accept(File f) { if(f != null) { if(f.isDirectory()) { return true; } String uppercaseName = f.getName().toUpperCase(); if(uppercaseName.endsWith(".XTM10") || uppercaseName.endsWith(".XTM1") || uppercaseName.endsWith(".XTM20") || uppercaseName.endsWith(".XTM2") || uppercaseName.endsWith(".XTM") || uppercaseName.endsWith(".LTM") || uppercaseName.endsWith(".JTM")) { return true; } } return false; } //The description of this filter @Override public String getDescription() { return "Any topic map"; } }
1,963
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WPRFileFilter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/filechooser/WPRFileFilter.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * WPRFileFilter.java * * */ package org.wandora.application.gui.filechooser; import java.io.File; /** * * @author akivela */ public class WPRFileFilter extends javax.swing.filechooser.FileFilter { /** Creates a new instance of WPRFileFilter */ public WPRFileFilter() { } @Override public boolean accept(File f) { if(f != null) { if (f.isDirectory()) { return true; } String uppercaseName = f.getName().toUpperCase(); if(uppercaseName.endsWith(".WPR")) { return true; } } return false; } //The description of this filter @Override public String getDescription() { return "Wandora project file"; } }
1,602
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
XTM1FileFilter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/filechooser/XTM1FileFilter.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * XTM1FileFilter.java * * */ package org.wandora.application.gui.filechooser; import java.io.File; /** * * @author akivela */ public class XTM1FileFilter extends javax.swing.filechooser.FileFilter { /** Creates a new instance of XTM1FileFilter */ public XTM1FileFilter() { } @Override public boolean accept(File f) { if( f != null) { if (f.isDirectory()) { return true; } String uppercaseName = f.getName().toUpperCase(); if(uppercaseName.endsWith(".XTM10") || uppercaseName.endsWith(".XTM1")) { return true; } } return false; } //The description of this filter @Override public String getDescription() { return "XTM 1.0 topic map"; } }
1,657
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LTMFileFilter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/filechooser/LTMFileFilter.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * LTMFileFilter.java * * */ package org.wandora.application.gui.filechooser; import java.io.File; /** * * @author akivela */ public class LTMFileFilter extends javax.swing.filechooser.FileFilter { /** Creates a new instance of LTMFileFilter */ public LTMFileFilter() { } @Override public boolean accept(File f) { if(f != null) { if (f.isDirectory()) { return true; } String uppercaseName = f.getName().toUpperCase(); if(uppercaseName.endsWith(".LTM")) { return true; } } return false; } //The description of this filter @Override public String getDescription() { return "LTM topic map"; } }
1,591
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
JTMFileFilter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/filechooser/JTMFileFilter.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * JTMFileFilter.java * * */ package org.wandora.application.gui.filechooser; import java.io.File; /** * * @author akivela */ public class JTMFileFilter extends javax.swing.filechooser.FileFilter { /** Creates a new instance of JTMFileFilter */ public JTMFileFilter() { } @Override public boolean accept(File f) { if(f != null) { if (f.isDirectory()) { return true; } String uppercaseName = f.getName().toUpperCase(); if(uppercaseName.endsWith(".JTM")) { return true; } } return false; } //The description of this filter @Override public String getDescription() { return "JTM topic map"; } }
1,595
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicMapFileChooser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/filechooser/TopicMapFileChooser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicMapFileChooser.java * * Created on 9. huhtikuuta 2006, 19:17 */ package org.wandora.application.gui.filechooser; import org.wandora.application.gui.simple.SimpleFileChooser; /** * * @author akivela */ public class TopicMapFileChooser extends SimpleFileChooser { private static final long serialVersionUID = 1L; public TopicMapFileChooser() { initialize(); } public TopicMapFileChooser(String currentPath) { super(currentPath); initialize(); } private void initialize() { setFileFilter(new LTMFileFilter()); setFileFilter(new JTMFileFilter()); setFileFilter(new XTM1FileFilter()); setFileFilter(new XTM2FileFilter()); setFileFilter(new AnyTopiMapFileFilter()); setFileView(new TopicMapFileView()); } }
1,659
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicStringifier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicstringify/TopicStringifier.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.topicstringify; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * TopicStringifier interface specifies all methods required in a Java * class that creates string representations out of topics. String representations * are used in Wandora anytime a topic is viewed. * * @author akivela */ public interface TopicStringifier { /** * Initialization method is called before a TopicStringifier is actually used. * If initialization returns false, the TopicStringifier should not be used. */ public boolean initialize(Wandora wandora, Context context); /** * toString method is the actual endpoint used to create a string out of a * topic. */ public String toString(Topic t); /** * Description is a text that describes the TopicStringifier. Text is * shown in Wandora's UI whenever user wants more information about the * TopicStringifier, for example, as a tooltip text. */ public String getDescription(); /** * Method returns an icon shown in Wandora UI as a mark of the * TopicStringifier. Current Wandora views the icon in the infobar near * topic's name. */ public Icon getIcon(); /** * Sometimes topic viewer may support string editing feature. * This method is used to push string back into a topic. String * is stored into the topic. */ public void stringIntoTopic(String oldString, String newString, Topic topic) throws TopicMapException; /** * If topic viewer supports string editing feature and Wandora can push the * string back into the topic, this method should return true. If TopicStringifier * can't push a string back into the topic, method should return false. The * push is implemented in method stringIntoTopic. */ public boolean supportsStringIntoTopic(); }
2,905
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicStringifierToVariant.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicstringify/TopicStringifierToVariant.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.topicstringify; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.UIBox; import org.wandora.application.tools.GenericOptionsDialog; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class TopicStringifierToVariant implements TopicStringifier { private Set<Topic> scope = null; public TopicStringifierToVariant() { scope = null; } public TopicStringifierToVariant(Set<Topic> s) { scope = s; } @Override public boolean initialize(Wandora wandora, Context context) { try { GenericOptionsDialog god=new GenericOptionsDialog(wandora, "Select variant name scope to be viewed", "Select variant name scope to be viewed.",true,new String[][]{ new String[]{"Type of variant name","topic","","Variant name type (display name for example)"}, new String[]{"Scope of variant name","topic","","Variant name scope i.e. language (English for example)"}, },wandora); god.setVisible(true); if(god.wasCancelled()) return false; Map<String,String> values=god.getValues(); TopicMap tm = wandora.getTopicMap(); Topic typeTopic = tm.getTopic(values.get("Type of variant name")); Topic scopeTopic = tm.getTopic(values.get("Scope of variant name")); scope = new LinkedHashSet<>(); if(typeTopic != null) scope.add(typeTopic); if(scopeTopic != null) scope.add(scopeTopic); return true; } catch(Exception e) { e.printStackTrace(); } return false; } @Override public String getDescription() { return "Views topic as a variant name"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/view_topic_as_variant.png"); } @Override public String toString(Topic t) { String n = null; try { n = t.getVariant(scope); if(n != null) return n; } catch(Exception e) { } try { if(t.getBaseName() == null) { return "["+t.getOneSubjectIdentifier().toExternalForm()+"]"; } else { return "["+t.getBaseName()+"]"; } } catch(Exception e) { } return "[unable to solve name for a topic]"; } // ------------------------------------------------------------------------- @Override public boolean supportsStringIntoTopic() { return true; } @Override public void stringIntoTopic(String oldString, String newString, Topic t) throws TopicMapException { if(t != null && !t.isRemoved()) { if(scope != null && !scope.isEmpty()) { t.setVariant(scope, newString); } } } }
4,123
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DefaultTopicStringifier.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicstringify/DefaultTopicStringifier.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.topicstringify; import java.net.URL; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.application.contexts.Context; import org.wandora.application.gui.ConfirmResult; import org.wandora.application.gui.UIBox; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class DefaultTopicStringifier implements TopicStringifier { public static final int TOPIC_RENDERS_SL = 100; public static final int TOPIC_RENDERS_SI = 110; public static final int TOPIC_RENDERS_SI_WITHOUT_DOMAIN = 120; public static final int TOPIC_RENDERS_BASENAME = 130; public static final int TOPIC_RENDERS_BASENAME_WITH_SL_ICON = 140; public static final int TOPIC_RENDERS_BASENAME_WITH_INFO = 150; public static final int TOPIC_RENDERS_ENGLISH_DISPLAY_NAME = 200; private int stringType = TOPIC_RENDERS_BASENAME; private Wandora wandora = null; public DefaultTopicStringifier() { } public DefaultTopicStringifier(int type) { stringType = type; } @Override public boolean initialize(Wandora wandora, Context context) { this.wandora = wandora; return true; } @Override public String getDescription() { String prefix = "View topic as a "; switch(stringType) { case TOPIC_RENDERS_SL: return prefix + "subject locator"; case TOPIC_RENDERS_SI: return prefix + "subject identifier"; case TOPIC_RENDERS_SI_WITHOUT_DOMAIN: return prefix + "subject identifier without domain"; case TOPIC_RENDERS_BASENAME: return prefix + "base name"; case TOPIC_RENDERS_BASENAME_WITH_INFO: return prefix + "base name with topic info"; case TOPIC_RENDERS_ENGLISH_DISPLAY_NAME: return prefix + "english display name"; } return "Default topic renderer"; } @Override public Icon getIcon() { switch(stringType) { case TOPIC_RENDERS_SL: return UIBox.getIcon("gui/icons/view_topic_as_sl.png"); case TOPIC_RENDERS_SI: return UIBox.getIcon("gui/icons/view_topic_as_si.png"); case TOPIC_RENDERS_SI_WITHOUT_DOMAIN: return UIBox.getIcon("gui/icons/view_topic_as_si_wo_domain.png"); case TOPIC_RENDERS_BASENAME: return UIBox.getIcon("gui/icons/view_topic_as_basename.png"); case TOPIC_RENDERS_BASENAME_WITH_INFO: return UIBox.getIcon("gui/icons/view_topic_as_basename.png"); case TOPIC_RENDERS_ENGLISH_DISPLAY_NAME: return UIBox.getIcon("gui/icons/view_topic_as_english_display.png"); } return UIBox.getIcon("gui/icons/view_topic_as_basename.png"); } @Override public String toString(Topic t) { return _toString(t, stringType); } public static String _toString(Topic t, int stringType) { try { if(t == null) return "[null]"; else if(t.isRemoved()) return "[removed]"; else { switch(stringType) { case TOPIC_RENDERS_BASENAME: { if(t.getBaseName() == null) { return t.getOneSubjectIdentifier().toExternalForm(); } else { return t.getBaseName(); } } case TOPIC_RENDERS_BASENAME_WITH_INFO: { String info = getTopicInfo(t); if(t.getBaseName() == null) { return t.getOneSubjectIdentifier().toExternalForm() + " " + info; } else { return t.getBaseName() + " " + info; } } case TOPIC_RENDERS_SI: { return t.getOneSubjectIdentifier().toExternalForm(); } case TOPIC_RENDERS_SI_WITHOUT_DOMAIN: { String urlString = t.getOneSubjectIdentifier().toExternalForm(); URL url = new URL(urlString); urlString = url.getFile(); if(url.getRef() != null) urlString += "#" + url.getRef(); return urlString; } case TOPIC_RENDERS_SL: { if(t.getSubjectLocator() == null) { if(t.getBaseName() == null) { return "["+t.getOneSubjectIdentifier().toExternalForm()+"]"; } else { return "["+t.getBaseName()+"]"; } } else { return t.getSubjectLocator().toExternalForm(); } } case TOPIC_RENDERS_ENGLISH_DISPLAY_NAME: { try { String englishDisplayName = TMBox.getTopicDisplayName(t, "en"); if(englishDisplayName != null) return englishDisplayName; } catch(Exception e) {} if(t.getBaseName() == null) { return "["+t.getOneSubjectIdentifier().toExternalForm()+"]"; } else { return "["+t.getBaseName()+"]"; } } // BY DEFAULT TOPIC RENDERS AS THE BASE NAME default: { if(t.getBaseName() == null) { return t.getOneSubjectIdentifier().toExternalForm(); } else { return t.getBaseName(); } } } } } catch(Exception e) { } return "[error retrieving topic string]"; } public static String getTopicInfo(Topic t) { StringBuilder s = new StringBuilder(""); try { s.append("SI").append(t.getSubjectIdentifiers().size()); s.append(" SL").append(t.getSubjectLocator() == null ? "0" : "1"); s.append(" CL").append(t.getTypes().size()); s.append(" IN").append(t.getTopicMap().getTopicsOfType(t).size()); s.append(" AS").append(t.getAssociations().size()); s.append(" VN").append(t.getVariantScopes().size()); s.append(" OC").append(t.getDataTypes().size()); } catch(Exception e) {} return s.toString(); } // ------------------------------------------------------------------------- @Override public boolean supportsStringIntoTopic() { switch(stringType) { case TOPIC_RENDERS_ENGLISH_DISPLAY_NAME: case TOPIC_RENDERS_SL: case TOPIC_RENDERS_BASENAME: case TOPIC_RENDERS_BASENAME_WITH_INFO: case TOPIC_RENDERS_SI: { return true; } } return false; } @Override public void stringIntoTopic(String oldString, String newString, Topic t) throws TopicMapException { switch(stringType) { case TOPIC_RENDERS_ENGLISH_DISPLAY_NAME: { t.setDisplayName("en", newString); return; } case TOPIC_RENDERS_BASENAME_WITH_INFO: case TOPIC_RENDERS_BASENAME: { ConfirmResult cr = TMBox.checkBaseNameChange(wandora, t, newString); if(cr.equals(ConfirmResult.yes) || cr.equals(ConfirmResult.yestoall)) { t.setBaseName(newString); } break; } case TOPIC_RENDERS_SI: { Locator subjectIdentifier = new Locator(newString); ConfirmResult cr = TMBox.checkSubjectIdentifierChange(wandora, t, subjectIdentifier, true); if(cr.equals(ConfirmResult.yes) || cr.equals(ConfirmResult.yestoall)) { t.addSubjectIdentifier(subjectIdentifier); if(oldString != null) { t.removeSubjectIdentifier(new Locator(oldString)); } } break; } case TOPIC_RENDERS_SL: { ConfirmResult cr = TMBox.checkSubjectLocatorChange(wandora, t, newString); if(cr.equals(ConfirmResult.yes) || cr.equals(ConfirmResult.yestoall)) { t.setSubjectLocator(new Locator(newString)); } break; } } } }
10,132
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicToString.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicstringify/TopicToString.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.topicstringify; import javax.swing.Icon; import org.wandora.application.Wandora; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * This is a static class to make string representations out of topics. String * representation is created with a user given stringifier * (any class implementing the TopicStringifierInterface). * An UI element viewing topics as strings should use the static * toString(topic) method of this class to transform topics to string. * * @author akivela */ public class TopicToString { private static TopicStringifier topicStringifier = null; private static TopicStringifier defaultTopicStringifier = new DefaultTopicStringifier(); public static void initialize(Wandora wandora) { try { // TODO: Read used stringifier class from options. // TODO: Save current stringifier name and parameters to options. } catch(Exception e) { // NOTHING } } public static TopicStringifier getStringifier() { return topicStringifier; } public static void setStringifier(TopicStringifier r) { topicStringifier = r; } public static Icon getIcon() { if(topicStringifier != null) { return topicStringifier.getIcon(); } else { return defaultTopicStringifier.getIcon(); } } /** * Method is used to create string representation out of a topic. Method * uses given TopicStringifier to create a string. If no TopicStringifier is * given, method passes the call to defaultTopicStringifier. */ public static String toString(Topic t) { if(topicStringifier != null) { return topicStringifier.toString(t); } else { return defaultTopicStringifier.toString(t); } } /** * Returns true if current TopicStringifier can push a string back into * the topic. If current TopicStringifier can't push any string back into * the topic, method returns false. */ public static boolean supportsStringIntoTopic() { if(topicStringifier != null) { return topicStringifier.supportsStringIntoTopic(); } else { return defaultTopicStringifier.supportsStringIntoTopic(); } } /** * Store string into the topic if possible. Return true if storing was * successful. Otherwise return false. */ public static void stringIntoTopic(String oldString, String newString, Topic t) throws TopicMapException { if(topicStringifier != null) { topicStringifier.stringIntoTopic(oldString, newString, t); } else { defaultTopicStringifier.stringIntoTopic(oldString, newString, t); } } }
3,790
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleTree.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleTree.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleTree.java * * Created on 29. joulukuuta 2005, 20:14 * */ package org.wandora.application.gui.simple; import java.awt.Cursor; import java.awt.Graphics; import javax.swing.JTree; import org.wandora.application.Wandora; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleTree extends JTree implements SimpleComponent { private static final long serialVersionUID = 1L; /** Creates a new instance of SimpleTree */ public SimpleTree() { this.putClientProperty("JTree.lineStyle", "None"); this.setFocusable(true); this.addFocusListener(this); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } @Override public void focusGained(java.awt.event.FocusEvent focusEvent) { Wandora w = Wandora.getWandora(this); if(w != null) { w.gainFocus(this); } } @Override public void focusLost(java.awt.event.FocusEvent focusEvent) { } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
1,975
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicLink.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/TopicLink.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicLink.java * * Created on June 14, 2004, 9:32 AM */ package org.wandora.application.gui.simple; import org.wandora.application.Wandora; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Topic; /** * * @author olli, ak */ public class TopicLink extends TopicLinkBasename { private static final long serialVersionUID = 1L; private boolean limitLength = true; private String lname = ""; private String sname = ""; /** Creates a new instance of TopicLink */ public TopicLink(Topic t, Wandora wandora) { super(t, wandora); setText(t); } public void setLimitLength(boolean limit) { limitLength = limit; if(limitLength) this.setText(sname); else this.setText(lname); this.setVisible(true); } public void setText(Topic t) { lname = TopicToString.toString(t); if(lname.length() > 30) sname = lname.substring(0,13)+"..."+lname.substring(lname.length()-13); else sname = lname; if(limitLength) this.setText(sname); else this.setText(lname); this.setVisible(true); } }
2,098
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleToggleButton.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleToggleButton.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * WandoraToggleIcon.java * * Created on 25. marraskuuta 2005, 12:59 * */ package org.wandora.application.gui.simple; import java.awt.Cursor; import java.awt.Graphics; import java.awt.event.MouseAdapter; import javax.swing.Icon; import javax.swing.JToggleButton; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleToggleButton extends JToggleButton { private static final long serialVersionUID = 1L; Icon onIcon = null; Icon offIcon = null; public SimpleToggleButton(String label) { this(); this.setText(label); } public SimpleToggleButton() { this.setFocusPainted(false); this.setFont(UIConstants.buttonLabelFont); UIConstants.setFancyFont(this); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); this.setOpaque(true); this.setBackground(UIConstants.defaultActiveBackground); this.offIcon = UIBox.getIcon("gui/icons/checkbox.png"); this.onIcon = UIBox.getIcon("gui/icons/checkbox_selected.png"); this.addMouseListener( new MouseAdapter() { @Override public void mouseEntered(java.awt.event.MouseEvent evt) { if(evt.getComponent().isEnabled()) evt.getComponent().setBackground(UIConstants.defaultActiveBackground); } @Override public void mouseExited(java.awt.event.MouseEvent evt) { if(evt.getComponent().isEnabled()) evt.getComponent().setBackground(UIConstants.defaultActiveBackground); } } ); } public SimpleToggleButton(String onIconResource, String offIconResource) { this(onIconResource, offIconResource, false); } public SimpleToggleButton(String onIconResource, String offIconResource, boolean isSelected) { this.onIcon = UIBox.getIcon(onIconResource); this.offIcon = UIBox.getIcon(offIconResource); this.setBackground(null); this.setForeground(null); setSelected(isSelected); setBorderPainted(false); setFocusPainted(false); setContentAreaFilled(false); setMargin(null); setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } public SimpleToggleButton(Icon onIcon, Icon offIcon, boolean isSelected) { this.onIcon = onIcon; this.offIcon = offIcon; setSelected(isSelected); } @Override public void setSelected(boolean state) { super.setSelected(state); if(state) setIcon(onIcon); else setIcon(offIcon); } @Override public void paint(Graphics graphics) { if(isSelected()) setIcon(onIcon); else setIcon(offIcon); UIConstants.preparePaint(graphics); super.paint(graphics); } }
3,875
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleList.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleList.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.simple; import java.awt.Graphics; import javax.swing.JList; import javax.swing.ListModel; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleList extends JList { private static final long serialVersionUID = 1L; public SimpleList() { super(); } public SimpleList(ListModel m) { super(m); } public SimpleList(Object[] a) { super(a); } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
1,421
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ComponentThumbnail.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/ComponentThumbnail.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * ComponentThumbnail.java * * Created on 29. lokakuuta 2007, 14:49 * */ package org.wandora.application.gui.simple; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import javax.swing.JPanel; /** * * @author akivela */ public class ComponentThumbnail extends JPanel implements Runnable { private static final long serialVersionUID = 1L; Component original = null; int thumbWidth = 50; int thumbHeight = 50; Image thumbnailImage = null; /** Creates a new instance of ComponentThumbnail */ public ComponentThumbnail(Component original) { this.original = original; this.add(original); Thread runner = new Thread(this); runner.start(); } public void run() { /* This is problematic as the thread runs for ever and consumes resources. The thread should end when ever the original component becomes redundant. */ while(true) { if(original.getWidth() > 0 && original.getHeight() > 0) { int w = original.getWidth(); int h = original.getHeight(); w = ( w > 2000 ? 2000 : w ); h = ( h > 2000 ? 2000 : h ); thumbWidth = 200*w/h; thumbHeight = 200; BufferedImage tempImage = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR ); original.paint(tempImage.getGraphics()); Graphics2D g2 = tempImage.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY ); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY ); thumbnailImage = tempImage.getScaledInstance( thumbWidth, thumbHeight, BufferedImage.SCALE_SMOOTH ); repaint(); revalidate(); if(getParent() != null) { getParent().invalidate(); } } try { Thread.currentThread().sleep(1000); } catch(Exception e) {} } } public void paint(Graphics g) { //super.paint(g); if(getParent() != null) g.setColor(getParent().getBackground()); g.fillRect(0,0,g.getClipBounds().width, g.getClipBounds().height); g.drawImage(thumbnailImage,0,0,this); g.setColor(Color.GRAY); g.drawRect(0,0,thumbWidth-1,thumbHeight-1); } public Dimension getPreferredSize() { Dimension thumbDimensions = new Dimension(thumbWidth, thumbHeight); return thumbDimensions; } }
4,008
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleURILabel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleURILabel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.simple; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.net.URI; import org.wandora.application.gui.UIBox; import org.wandora.utils.DataURL; /** * * @author akivela */ public class SimpleURILabel extends SimpleLabel { private static final long serialVersionUID = 1L; private static BufferedImage invalidURIImage = UIBox.getImage("gui/icons/invalid_uri.png"); private String completeLabelString = null; @Override public void setText(String str) { if(DataURL.isDataURL(str)) { completeLabelString = str; String strFragment = str.substring(0, Math.min(str.length(), 64)) + "... ("+str.length()+")"; System.out.println("strFragment=="+strFragment); super.setText(strFragment); } else { completeLabelString = null; super.setText(str); } } @Override public String getText() { try { if(completeLabelString != null) { return completeLabelString; } else { return super.getText(); } } catch(Exception e) { e.printStackTrace(); } return ""; } public boolean isValidURI() { String u = getText(); if(u != null && u.length() > 0) { try { if(DataURL.isDataURL(u)) { return true; } new URI(u); } catch(Exception e) { return false; } } return true; } @Override public void paint(Graphics gfx) { super.paint(gfx); if(!isValidURI()) { gfx.drawImage(invalidURIImage, this.getWidth()-18, 0, this); } } }
2,711
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicLinkBasename.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/TopicLinkBasename.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicLinkBasename.java * * Created on 14. joulukuuta 2004, 19:20 */ package org.wandora.application.gui.simple; import java.awt.event.MouseEvent; import org.wandora.application.Wandora; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class TopicLinkBasename extends SimpleLabel { private static final long serialVersionUID = 1L; protected Wandora parent; protected Locator locator; protected Topic topic; /** Creates a new instance of TopicLink */ public TopicLinkBasename(Topic t, Wandora wandora) { super(); try { this.topic = t; this.locator=(Locator)topic.getOneSubjectIdentifier(); this.parent=wandora; String basename = topic.getBaseName(); if(basename != null) { this.setText(basename); } else { if(!topic.isRemoved()) { this.setText(locator.toExternalForm()); } else { this.setText("[removed]"); } } } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION this.setText("[Exception retrieving name]"); } java.awt.Color c=parent.topicHilights.get(t); if(c==null) c=parent.topicHilights.getLayerColor(t); if(c!=null){ this.setForeground(c); // this.setBackground(c); // this.setOpaque(true); } this.setVisible(true); } public Topic getTopic() { return topic; } // ------------------------------------------------------------------------- @Override public void mouseClicked(java.awt.event.MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1 && e.getClickCount()>=2) { //System.out.println("link pressed"); parent.applyChangesAndOpen(locator); } } }
2,949
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ScrollableSimplePanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/ScrollableSimplePanel.java
package org.wandora.application.gui.simple; import java.awt.Container; import java.awt.Dimension; import java.awt.Rectangle; import javax.swing.Scrollable; import javax.swing.SwingConstants; /** * * @author akivela */ public class ScrollableSimplePanel extends SimplePanel implements Scrollable { private static final long serialVersionUID = 1L; /** Creates a new instance of ScrollableSimplePanel */ public ScrollableSimplePanel() { } @Override public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 10; } @Override public boolean getScrollableTracksViewportWidth() { Container c=this.getParent(); if(c==null) return true; if(c.getWidth()>300) return true; else return false; } @Override public boolean getScrollableTracksViewportHeight() { return false; } @Override public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { if(orientation==SwingConstants.VERTICAL) return visibleRect.height; else return visibleRect.width; } @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } }
1,274
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleTextConsoleListener.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleTextConsoleListener.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleTextConsoleListener.java */ package org.wandora.application.gui.simple; /** * * @author akivela */ public interface SimpleTextConsoleListener { public String handleInput(String input); }
1,021
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AssociationTypeLinkBasename.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/AssociationTypeLinkBasename.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * AssociationTypeLinkBasename.java * * Created on 17.7.2007, 13:15 * */ package org.wandora.application.gui.simple; import org.wandora.application.Wandora; import org.wandora.application.gui.table.AssociationTable; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class AssociationTypeLinkBasename extends TopicLinkBasename { private static final long serialVersionUID = 1L; private AssociationTable associationTable = null; /** Creates a new instance of AssociationTypeLinkBasename */ public AssociationTypeLinkBasename(AssociationTable at, Topic t, Wandora wandora) { super(t, wandora); associationTable = at; } public AssociationTable getAssociationTable() { return associationTable; } }
1,611
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleRadioButton.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleRadioButton.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleRadioButton.java * * Created on 15. helmikuuta 2006, 18:18 * */ package org.wandora.application.gui.simple; import java.awt.Cursor; import java.awt.Graphics; import javax.swing.JRadioButton; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleRadioButton extends JRadioButton { private static final long serialVersionUID = 1L; /** Creates a new instance of SimpleRadioButton */ public SimpleRadioButton() { this.setFont(UIConstants.buttonLabelFont); UIConstants.setFancyFont(this); this.setIcon(UIBox.getIcon("gui/icons/radiobox.png")); this.setSelectedIcon(UIBox.getIcon("gui/icons/radiobox_selected.png")); this.setFocusPainted(false); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
1,811
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleAWTMenu.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleAWTMenu.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleAWTMenu.java * */ package org.wandora.application.gui.simple; import java.awt.Menu; import org.wandora.application.gui.UIConstants; /** * * @author anttirt */ public class SimpleAWTMenu extends Menu { private static final long serialVersionUID = 1L; public SimpleAWTMenu() { } public SimpleAWTMenu(String menuName) { if(menuName.startsWith("[") && menuName.endsWith("]")) { setEnabled(false); menuName = menuName.substring(1, menuName.length()-1); } setFont(UIConstants.menuFont); setLabel(menuName); setName(menuName); } }
1,465
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleTextConsole.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleTextConsole.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleTextConsole.java * * Created on November 16, 2004, 5:07 PM */ package org.wandora.application.gui.simple; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.io.File; import java.util.ArrayList; import javax.swing.text.Document; import org.wandora.application.Wandora; import org.wandora.application.gui.UIConstants; import org.wandora.utils.ClipboardBox; import org.wandora.utils.IObox; /** * @author akivela */ public class SimpleTextConsole extends SimpleTextPane { private static final long serialVersionUID = 1L; private static final int DEFAULT_FONT_SIZE = 12; private static final Color DEFAULT_FOREGROUND_COLOR = Color.BLACK; private static final Color DEFAULT_BACKGROUND_COLOR = Color.WHITE; private Color foregroundColor = DEFAULT_FOREGROUND_COLOR; private Color backgroundColor = DEFAULT_BACKGROUND_COLOR; private StringBuilder input = null; private int inputPos = 0; private SimpleTextConsoleListener consoleListener = null; private ArrayList<String> history; private int historyMaxSize = 999; private int historyPtr=0; private String tempHistory = null; public SimpleTextConsole(SimpleTextConsoleListener cl) { input = new StringBuilder(""); inputPos = 0; consoleListener = cl; Font font = new Font(Font.MONOSPACED, Font.PLAIN, DEFAULT_FONT_SIZE); setFont(font); setForeground(foregroundColor); setBackground(backgroundColor); setCaretColor(foregroundColor); history = new ArrayList<String>(); } public void setFontSize(int s) { Font font = new Font(Font.MONOSPACED, Font.PLAIN, s); setFont(font); } protected boolean onKeyPressed(KeyEvent e) { boolean consumed = false; if(e.getKeyCode() == KeyEvent.VK_ENTER) { Document d = this.getDocument(); this.setCaretPosition(d.getLength()-1); eraseInputInConsole(); inputPos=0; String output = handleInput(); //output("\n"+output); historyPtr=0; consumed = true; } else if(e.getKeyCode() == KeyEvent.VK_LEFT) { if(inputPos < input.length()) { inputPos++; Document d = this.getDocument(); this.setCaretPosition(d.getLength()-inputPos); } consumed = true; } else if(e.getKeyCode() == KeyEvent.VK_RIGHT) { if(inputPos > 0) { inputPos--; Document d = this.getDocument(); this.setCaretPosition(d.getLength()-inputPos); } consumed = true; } else if(e.getKeyCode() == KeyEvent.VK_UP) { if(historyPtr == 0) tempHistory = input.toString(); if(historyPtr < history.size()) { inputPos=0; historyPtr++; changeInput(history.get(history.size() - historyPtr)); } consumed = true; } else if(e.getKeyCode() == KeyEvent.VK_DOWN) { if(historyPtr > 0) { inputPos=0; historyPtr--; if(historyPtr == 0) { changeInput(tempHistory); } else { changeInput(history.get(history.size() - historyPtr)); } } consumed = true; } else if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { backspace(); consumed = true; } else if(e.getKeyCode() == KeyEvent.VK_DELETE) { del(); consumed = true; } else if(e.getKeyCode() == KeyEvent.VK_HOME) { inputPos=input.length(); Document d = this.getDocument(); this.setCaretPosition(d.getLength()-inputPos); consumed = true; } else if(e.getKeyCode() == KeyEvent.VK_END) { inputPos=0; Document d = this.getDocument(); this.setCaretPosition(d.getLength()-inputPos); consumed = true; } else if(isValidCharacter(e.getKeyChar())) { output(e.getKeyChar()); input.insert(input.length()-inputPos, e.getKeyChar()); consumed = true; } if(consumed) { refresh(); } return consumed; } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { int cpos = getCaretPosition(); Document d = this.getDocument(); if(d.getLength()-cpos <= input.length()) { inputPos = d.getLength()-cpos; this.setCaretPosition(d.getLength()-inputPos); } } private boolean isValidCharacter(int c) { if("1234567890qwertyuiopåasdfghjklöäzxcvbnmQWERTYUIOPÅASDFGHJKLÖÄZXCVBNM,.:;-+_'*!\"#¤%&/()=?`@$€{[]}\\ <>|".indexOf(c) != -1) return true; return false; } @Override public void cut() { super.cut(); } @Override public void copy() { super.copy(); } @Override public void paste() { String t = ClipboardBox.getClipboard(); output(t); input.insert(input.length()-inputPos, t); refresh(); } public void paste(String t) { if(t != null) { output(t); input.insert(input.length()-inputPos, t); } refresh(); } public void changeInput(String newInput) { backspace(input.length()); output(newInput); input = new StringBuilder(newInput); inputPos = 0; } public String handleInput(String in) { input = new StringBuilder(in); String output = handleInput(); historyPtr=0; inputPos=0; return output; } public String handleInput() { String output = null; String inputStr = input.toString(); if(inputStr.length() > 0) { history.add(inputStr); if(history.size() > historyMaxSize) { history.remove(0); } } if(consoleListener != null) { output = consoleListener.handleInput(inputStr); } input = new StringBuilder(""); inputPos = 0; return output; } public void output(String o) { try { if(o != null) { Document d = this.getDocument(); d.insertString(d.getLength()-inputPos, o, null); this.setCaretPosition(d.getLength()-inputPos); } } catch(Exception e) { e.printStackTrace(); } } public void output(char c) { try { Document d = this.getDocument(); d.insertString(d.getLength()-inputPos, ""+c, null); this.setCaretPosition(d.getLength()-inputPos); } catch(Exception e) { e.printStackTrace(); } } public void del() { if(inputPos > 0) { try { Document d = this.getDocument(); d.remove(d.getLength()-inputPos, 1); input.deleteCharAt(input.length()-inputPos); inputPos--; this.setCaretPosition(d.getLength()-inputPos); } catch(Exception e) { e.printStackTrace(); } } } public void backspace() { if(inputPos < input.length()) { try { Document d = this.getDocument(); d.remove(d.getLength()-inputPos-1, 1); this.setCaretPosition(d.getLength()-inputPos); input.deleteCharAt(input.length()-inputPos-1); } catch(Exception e) { e.printStackTrace(); } } } public void backspace(int n) { if(inputPos < n) { try { Document d = this.getDocument(); d.remove(d.getLength()-inputPos-n, n); this.setCaretPosition(d.getLength()-inputPos); input = new StringBuilder(input.subSequence(0, input.length()-inputPos-1)); } catch(Exception e) { e.printStackTrace(); } } } private void eraseInputInConsole() { try { Document d = this.getDocument(); int inputLen = input.length(); d.remove(d.getLength()-inputLen, inputLen); } catch(Exception e) { e.printStackTrace(); } } // ------------------------------------------------------------------------- @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } @Override protected void processKeyEvent(KeyEvent e) { if(e.getID() != KeyEvent.KEY_PRESSED) { return; } boolean consumed = onKeyPressed(e); if(!consumed) { super.processKeyEvent(e); } } public void refresh() { } public void clear() { setText(""); this.input = new StringBuilder(""); inputPos = 0; refresh(); } // ------------------------------------------------------------------------- public void save() { SimpleFileChooser chooser=UIConstants.getFileChooser(); if(chooser.open(Wandora.getWandora(), "Export")==SimpleFileChooser.APPROVE_OPTION){ File file = chooser.getSelectedFile(); try { IObox.saveFile(file, this.getText()); } catch(Exception e){ e.printStackTrace(); } } } public void saveInput() { SimpleFileChooser chooser=UIConstants.getFileChooser(); if(chooser.open(Wandora.getWandora(), "Export")==SimpleFileChooser.APPROVE_OPTION){ File file = chooser.getSelectedFile(); try { StringBuilder data = new StringBuilder(""); for( String o : history ) { data.append(o); data.append(System.getProperty("line.separator")); } data.append(input); IObox.saveFile(file, data.toString()); } catch(Exception e){ e.printStackTrace(); } } } }
11,780
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleMenuItem.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleMenuItem.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleMenuItem.java * * Created on 2. marraskuuta 2005, 15:28 * */ package org.wandora.application.gui.simple; import java.awt.Graphics; import java.awt.event.ActionListener; import javax.swing.JMenuItem; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleMenuItem extends JMenuItem { private static final long serialVersionUID = 1L; public SimpleMenuItem() { } public SimpleMenuItem(String menuName) { this(menuName, null); } public SimpleMenuItem(String menuName, ActionListener defaultListener) { boolean enabled = true; String iconResource = "gui/icons/empty.png"; if(menuName.startsWith("[") && menuName.endsWith("]")) { enabled = false; menuName = menuName.substring(1, menuName.length()-1); } if(menuName.startsWith("X ") || menuName.startsWith("O ")) { String name = menuName.substring(2); if(menuName.startsWith("X ")) { //menuItem=new javax.swing.JCheckBoxMenuItem(name, true); iconResource = "gui/icons/checked.png"; } else { //menuItem=new javax.swing.JCheckBoxMenuItem(name, false); iconResource = "gui/icons/unchecked.png"; } menuName = name; } if(iconResource != null) setIcon(UIBox.getIcon(iconResource)); setFont(UIConstants.menuFont); UIConstants.setFancyFont(this); setForeground(UIConstants.menuColor); setText(menuName); setName(menuName); setActionCommand(menuName); if(defaultListener != null) addActionListener(defaultListener); setEnabled(enabled); } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
2,778
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimplePasswordField.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimplePasswordField.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.simple; import java.awt.AWTKeyStroke; import java.awt.Insets; import java.awt.KeyboardFocusManager; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.HashSet; import javax.swing.JPasswordField; import org.wandora.utils.EasyVector; /** * * @author akikivela */ public class SimplePasswordField extends JPasswordField { private static final long serialVersionUID = 1L; protected Insets defaultMargins = new Insets(3,3,3,3); public SimplePasswordField() { initialize(); } public void initialize() { this.setFocusTraversalKeysEnabled(true); this.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,new HashSet(new EasyVector(new Object[]{AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,0)}))); this.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,new HashSet(new EasyVector(new Object[]{AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,InputEvent.SHIFT_DOWN_MASK)}))); this.setMargin(defaultMargins); } }
1,906
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleCheckBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleCheckBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleCheckBox.java * * Created on 29. joulukuuta 2005, 19:22 * */ package org.wandora.application.gui.simple; import java.awt.Cursor; import java.awt.Graphics; import javax.swing.JCheckBox; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleCheckBox extends JCheckBox { private static final long serialVersionUID = 1L; public SimpleCheckBox() { this.setFont(UIConstants.buttonLabelFont); UIConstants.setFancyFont(this); this.setIcon(UIBox.getIcon("gui/icons/checkbox.png")); this.setSelectedIcon(UIBox.getIcon("gui/icons/checkbox_selected.png")); this.setFocusPainted(false); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); // this.setUI(new SimpleCheckBoxUI()); // this.setBackground(UIConstants.checkBoxBackgroundColor); } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
1,850
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleCheckBoxUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleCheckBoxUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleCheckBoxUI.java * * */ package org.wandora.application.gui.simple; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import javax.swing.AbstractButton; import javax.swing.JComponent; import javax.swing.plaf.basic.BasicCheckBoxUI; /** * * @author akivela */ class SimpleCheckBoxUI extends BasicCheckBoxUI implements java.io.Serializable { private static final long serialVersionUID = 1L; public SimpleCheckBoxUI() { } @Override public void installUI(JComponent c) { super.installUI(c); } @Override public void uninstallUI(JComponent c) { super.uninstallUI(c); } @Override public void paint(Graphics g, JComponent c) { super.paint(g, c); } @Override protected void paintIcon(Graphics g, JComponent c, Rectangle iconRect) { } @Override protected void paintFocus(Graphics g, AbstractButton b, Rectangle viewRect, Rectangle textRect, Rectangle iconRect) { } protected Color getSelectColor() { return Color.BLACK; } }
1,922
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleLabel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleLabel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * Created on November 12, 2004, 3:21 PM */ package org.wandora.application.gui.simple; import java.awt.Graphics; import java.awt.event.MouseListener; import javax.swing.JLabel; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleLabel extends JLabel implements MouseListener { private static final long serialVersionUID = 1L; /** Creates a new instance of SimpleLabel */ public SimpleLabel() { initialize(); } public SimpleLabel(String text){ super(text); initialize(); } public void initialize() { this.addMouseListener(this); this.setFont(UIConstants.labelFont); UIConstants.setFancyFont(this); this.setBorder(UIConstants.defaultLabelBorder); } @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
2,246
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleLabelField.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleLabelField.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleLabelField.java * * Created on 16. helmikuuta 2006, 12:23 * */ package org.wandora.application.gui.simple; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Iterator; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.wandora.application.Wandora; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleLabelField extends JPanel implements MouseListener, KeyListener, ActionListener, SimpleComponent { private static final long serialVersionUID = 1L; public final static int LABEL = 1; public final static int FIELD = 2; private SimpleField field; private SimpleLabel label; private ArrayList<ChangeListener> changeListeners; private int mode = LABEL; private String previousText = ""; private boolean initialized = false; public SimpleLabelField(String name) { changeListeners = new ArrayList(); field = new SimpleField(name); label = new SimpleLabel(name); initialize(); initialized = true; } /** Creates a new instance of WandoraTextField */ public SimpleLabelField() { this(""); } // ------------------------------------------------------------------------- public void initialize() { label.removeMouseListener(label); label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); field.addKeyListener(this); this.setLayout(new BorderLayout()); this.setInheritsPopupMenu(true); //this.addMouseListener(this); this.addKeyListener(this); //this.setFocusTraversalKeysEnabled(false); this.setFocusable(true); this.addFocusListener(this); setUpGui(mode); } public void setUpGui(int mode) { this.mode = mode; if(mode == FIELD) { previousText = field.getText(); this.removeAll(); this.add(field, BorderLayout.CENTER); field.setCaretPosition(previousText.length()); field.requestFocus(); } else if(mode == LABEL) { label.setText(field.getText()); this.removeAll(); this.add(label, BorderLayout.CENTER); } if(initialized) { this.setVisible(false); this.setVisible(true); } } public String getText() { return field.getText(); } public void setText(String newText) { label.setText(newText); field.setText(newText); } public void addChangeListener(ChangeListener listener) { changeListeners.add(listener); } public void removeChangeListener(ChangeListener listener) { changeListeners.remove(listener); } public void removeAllChangeListeners() { changeListeners = new ArrayList(); } private void sendChangeEvent(ChangeEvent e) { if(changeListeners == null || changeListeners.size() == 0) return; ChangeListener listener; for(Iterator<ChangeListener> listeners = changeListeners.iterator(); listeners.hasNext(); ) { try { listener = listeners.next(); listener.stateChanged(e); } catch(Exception ex) { ex.printStackTrace(); } } } public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { if(mouseEvent.getClickCount() > 1 && mode == LABEL) { setUpGui(FIELD); } } public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } public void mousePressed(java.awt.event.MouseEvent mouseEvent) { } public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { } public void keyPressed(java.awt.event.KeyEvent keyEvent) { } public void keyReleased(java.awt.event.KeyEvent e) { if(e.getKeyCode() == e.VK_ENTER) { setUpGui(LABEL); e.consume(); if(! this.getText().equals(previousText)) { sendChangeEvent(new ChangeEvent(this)); } } } public void keyTyped(java.awt.event.KeyEvent e) { /* if(listWindow!=null){ e.setSource(listWindow.l); listWindow.l.dispatchEvent(e); }*/ } public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c.equals("Copy")) { field.copy(); } else if(c.equals("Cut")) { field.cut(); } else if(c.equals("Paste")) { field.paste(); } else if(c.equals("Edit")) { setUpGui(FIELD); } } public void focusGained(java.awt.event.FocusEvent focusEvent) { Wandora w = Wandora.getWandora(this); if(w != null) { w.gainFocus(this); } } public void focusLost(java.awt.event.FocusEvent focusEvent) { // DO NOTHING... } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
6,471
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleComponent.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleComponent.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleComponent.java * * Created on 27. marraskuuta 2004, 13:14 */ package org.wandora.application.gui.simple; import java.awt.event.FocusListener; /** * * @author Wandora group */ public interface SimpleComponent extends FocusListener { }
1,073
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleTextPaneResizeable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleTextPaneResizeable.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleTextPaneResizeable.java * * Created on Jan 5th, 2015, 21:38 */ package org.wandora.application.gui.simple; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.event.AdjustmentEvent; import java.awt.event.AdjustmentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JViewport; /** * Based on owatkins's example at * http://blue-walrus.com/2011/02/expandable-text-area-in-swing/ * * @author akivela */ public class SimpleTextPaneResizeable extends SimpleTextPane implements MouseMotionListener { private static final long serialVersionUID = 1L; protected boolean onlyVerticalResize = false; protected boolean mousePressedInTriangle = false; protected Point mousePressedPoint = null; protected Dimension sizeAtPress = null; protected Dimension newSize = null; // Reference to the underlying scrollpane protected JScrollPane scrollPane = null; // Height and width.. not hypotenuse protected int triangleSize = 15; // Is the mouse in the triangle protected boolean inTheTriangleZone = false; public SimpleTextPaneResizeable(JPanel parent) { super(parent); addMouseMotionListener(this); } public SimpleTextPaneResizeable() { this(null); } /** * Paint the text area */ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D graphics = (Graphics2D)g; if(inTheTriangleZone) { graphics.setColor(new Color(0.5f,0.5f,0.5f,0.75f)); } else { graphics.setColor(new Color(0.5f,0.5f,0.5f,0.2f)); } graphics.fillPolygon(getTriangle()); } protected JScrollPane getScrollPane() { // Get scrollpane, if first time calling this method then add an addjustment listener // to the scroll pane if(this.getParent() instanceof JViewport) { if(scrollPane == null) { JViewport p = (JViewport)this.getParent(); scrollPane = (JScrollPane)p.getParent(); scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener(){ @Override public void adjustmentValueChanged(AdjustmentEvent e) { //need to repaint the triangle when scroll bar moves repaint(); } }); } } return scrollPane; } @Override public void mouseMoved(MouseEvent e) { Point p = e.getPoint(); Polygon polygon = getTriangle(); if(polygon.contains(p)) { inTheTriangleZone = true; this.setCursor(new Cursor(Cursor.SE_RESIZE_CURSOR)); this.repaint(); } else { inTheTriangleZone = false; this.setCursor(new Cursor(Cursor.TEXT_CURSOR)); this.repaint(); } } @Override public void mouseDragged(MouseEvent e) { Point p = e.getPoint(); if(mousePressedInTriangle) { // Mouse was pressed in triangle so we can resize inTheTriangleZone = true; int xDiff = (mousePressedPoint.x - p.x); int yDiff = (mousePressedPoint.y - p.y); if(onlyVerticalResize) { newSize = new Dimension(sizeAtPress.width, sizeAtPress.height - yDiff); } else { newSize = new Dimension(sizeAtPress.width - xDiff, sizeAtPress.height - yDiff); } JScrollPane sp = getScrollPane(); this.revalidate(); this.repaint(); if(sp != null) { sp.getViewport().setSize(newSize); sp.getViewport().setPreferredSize(newSize); sp.getViewport().setMinimumSize(newSize); sp.setSize(newSize); sp.setPreferredSize(newSize); sp.setMinimumSize(newSize); sp.getParent().revalidate(); sp.revalidate(); sp.repaint(); } } } public void setHorizontallyResizeable(boolean rh) { onlyVerticalResize = !rh; } @Override public void mousePressed(MouseEvent e) { Point p = e.getPoint(); if(getTriangle().contains(p)) { mousePressedInTriangle = true; mousePressedPoint = p; sizeAtPress = getScrollPane().getSize(); } } @Override public void mouseReleased(MouseEvent e) { mousePressedInTriangle = false; mousePressedPoint = null; } @Override public void mouseExited(MouseEvent e) { inTheTriangleZone=false; repaint(); } private Polygon getTriangle() { JViewport viewport = getScrollPane().getViewport(); // Get bounds of viewport Rectangle bounds = viewport.getBounds(); // Position of viewport relative to text area. Point viewportPosition = viewport.getViewPosition(); int w = viewportPosition.x + bounds.width; int h = viewportPosition.y + bounds.height; int[] xs = {w,w,w-triangleSize}; int[] ys = {h-triangleSize,h,h}; Polygon polygon = new Polygon(xs, ys, 3); return polygon; } }
6,555
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleTabbedPaneUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleTabbedPaneUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleTabbedPaneUI.java * */ package org.wandora.application.gui.simple; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Insets; import java.awt.Rectangle; import javax.swing.plaf.basic.BasicTabbedPaneUI; /** * * @author akivela */ public class SimpleTabbedPaneUI extends BasicTabbedPaneUI { @Override protected Insets getContentBorderInsets(int tabPlacement) { //return super.getContentBorderInsets(tabPlacement); return new Insets(2,2,2,2); } @Override protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) { int w = super.calculateTabWidth(tabPlacement, tabIndex, metrics); return w+8; } @Override protected int calculateTabHeight(int tabPlacement, int tabIndex, int fontHeight) { int h = super.calculateTabHeight(tabPlacement, tabIndex, fontHeight); return h+2; } @Override protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) { // NO FOCUS INDICATOR } }
1,997
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleFileChooser.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleFileChooser.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleFileChooser.java * * Created on 9. huhtikuuta 2006, 19:15 * */ package org.wandora.application.gui.simple; import java.awt.Component; import java.awt.Graphics; import java.io.File; import javax.swing.JFileChooser; import org.wandora.application.Wandora; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleFileChooser extends JFileChooser { private static final long serialVersionUID = 1L; public SimpleFileChooser() { setLookAndFeel(); } public SimpleFileChooser(String currentPath) { setLookAndFeel(); File f = new File(currentPath); if(f.exists()) { this.setCurrentDirectory(f); } } public void setLookAndFeel() { /* * FileChooser.listFont * com.sun.java.plaf.windows.WindowsFileChooserUI */ try { //this.setUI(new SimpleFileChooserUI(this)); //System.out.println("SET UI: "+this.getUI()); } catch(Exception e) { e.printStackTrace(); } catch(Error er) { er.printStackTrace(); } } public int open(Component parent, String buttonLabel) { return open(parent, this.OPEN_DIALOG, buttonLabel); } public int open(Component parent) { return open(parent, this.OPEN_DIALOG, null); } public int open(Component parent, int type) { return open(parent, type, null); } public int open(Component parent, int type, String buttonLabel) { /* LookAndFeel originalLookAndFeel = null; try { originalLookAndFeel = UIManager.getLookAndFeel(); UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); SwingUtilities.updateComponentTreeUI(this); this.validate(); } catch (UnsupportedLookAndFeelException e) { // handle exception } catch (ClassNotFoundException e) { // handle exception } catch (InstantiationException e) { // handle exception } catch (IllegalAccessException e) { // handle exception } */ // ***** RESTORE PREVIOUS DIRECTORY ****** if(parent instanceof Wandora && parent != null) { String currentDirectory = ((Wandora) parent).options.get("current.directory"); if(currentDirectory != null) { File f = new File(currentDirectory); if(f.exists()) { this.setCurrentDirectory(f); } } } int answer = JFileChooser.CANCEL_OPTION; if(buttonLabel == null) { if(type == this.OPEN_DIALOG) { answer = this.showOpenDialog(parent); } else { answer = this.showSaveDialog(parent); } } else { answer = this.showDialog(parent, buttonLabel); } // ***** SAVE CURRENT DIRECTORY ****** if(answer == JFileChooser.APPROVE_OPTION) { if(parent instanceof Wandora && parent != null) { ((Wandora) parent).options.put("current.directory", this.getCurrentDirectory().getPath()); } } /* try { if(originalLookAndFeel != null) { UIManager.setLookAndFeel(originalLookAndFeel); } } catch (UnsupportedLookAndFeelException e) { // handle exception } */ return answer; } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
4,626
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleScrollPane.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleScrollPane.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleScrollPane.java * * Created on 20. lokakuuta 2005, 20:21 */ package org.wandora.application.gui.simple; import java.awt.Component; import java.awt.Graphics; import javax.swing.JScrollPane; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleScrollPane extends JScrollPane { private static final long serialVersionUID = 1L; /** * Creates a new instance of SimpleScrollPane */ public SimpleScrollPane() { getVerticalScrollBar().setUnitIncrement(20); } public SimpleScrollPane(Component c) { super(c); getVerticalScrollBar().setUnitIncrement(20); } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
1,609
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleURIField.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleURIField.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleURIField.java * * Created on November 12, 2004, 3:22 PM */ package org.wandora.application.gui.simple; import java.awt.AWTException; import java.awt.Color; import java.awt.Robot; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.net.URI; import javax.swing.JPopupMenu; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.utils.Base64; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; /** * * @author akivela */ public class SimpleURIField extends SimpleField { private static final long serialVersionUID = 1L; private static Color BROKEN_URI_COLOR = new Color(255, 240, 240); private static Color DATA_URI_COLOR = Color.WHITE; private static Color UNSET_URI_COLOR = new Color(246, 246, 246); private String completeFieldText = null; private Object[] popupStruct = new Object[] { "Cut", UIBox.getIcon("gui/icons/cut.png"), "Copy", UIBox.getIcon("gui/icons/copy.png"), "Paste", UIBox.getIcon("gui/icons/paste.png"), "Clear", UIBox.getIcon("gui/icons/clear.png"), }; public SimpleURIField() { initialize(); } public boolean isValidURI(String uriString) { if(uriString != null && uriString.length() > 0) { try { new URI(uriString); } catch(Exception e) { return DataURL.isDataURL(uriString); } } return true; } private Color getBackgroundColorFor(String uriString) { if(uriString == null || uriString.length() == 0) { return UNSET_URI_COLOR; } if(DataURL.isDataURL(uriString)) { return DATA_URI_COLOR; } try { new URI(uriString); } catch(Exception e) { return BROKEN_URI_COLOR; } return Color.WHITE; } @Override public void setText(String text) { setBackground(getBackgroundColorFor(text)); try { if(DataURL.isDataURL(text)) { String textFragment = text.substring(0, Math.min(text.length(), 64))+"... ("+text.length()+")"; completeFieldText = text; super.setText(textFragment); setEditable(false); } else { completeFieldText = null; super.setText(text); setEditable(true); } } catch(Exception e) { e.printStackTrace(); } } @Override public String getText() { try { if(completeFieldText != null) { return completeFieldText; } else { return super.getText(); } } catch(Exception e) { e.printStackTrace(); } return ""; } @Override public void setPopupMenu() { JPopupMenu popup = UIBox.makePopupMenu(popupStruct, this); setComponentPopupMenu(popup); } @Override public void drop(final java.awt.dnd.DropTargetDropEvent e) { try { DataFlavor fileListFlavor = DataFlavor.javaFileListFlavor; DataFlavor stringFlavor = DataFlavor.stringFlavor; Transferable tr = e.getTransferable(); if(e.isDataFlavorSupported(fileListFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); final SimpleURIField uriField = this; final java.util.List<File> files = (java.util.List<File>) tr.getTransferData(fileListFlavor); Thread dropThread = new Thread() { public void run() { try { int ret=WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Make DataURI out of given file content? Answering no uses filename as an URI.","Make DataURI?", WandoraOptionPane.YES_NO_OPTION); if(ret==WandoraOptionPane.YES_OPTION) { for( File file : files ) { DataURL dataURL = new DataURL(file); uriField.setText(dataURL.toExternalForm(Base64.DONT_BREAK_LINES)); break; // CAN'T HANDLE MULTIPLE FILES. ONLY FIRST IS USED. } } else if(ret==WandoraOptionPane.NO_OPTION) { String text=""; for( File file : files ) { if(text.length()>0) text+=";"; text+=file.toURI().toString(); } uriField.setText(text); } triggerChangeAction(); e.dropComplete(true); } catch(Exception e) { e.printStackTrace(); } } }; dropThread.start(); } else if(e.isDataFlavorSupported(stringFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); String data = (String)tr.getTransferData(stringFlavor); this.setText(data); e.dropComplete(true); } else { System.out.println("Drop rejected! Unsupported data flavor!"); e.rejectDrop(); } } catch(IOException ioe) { ioe.printStackTrace(); } catch(UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } this.setBorder(defaultBorder); } // ------------------------------------------------- copy, cut and paste --- @Override public void copy() { if(completeFieldText != null) { if(getSelectionStart() == 0 && getSelectionEnd() == super.getText().length()) { ClipboardBox.setClipboard(completeFieldText); return; } } super.copy(); } @Override public void cut() { if(completeFieldText != null) { if(getSelectionStart() == 0 && getSelectionStart() == super.getText().length()) { ClipboardBox.setClipboard(completeFieldText); setText(""); return; } } super.cut(); } @Override public void paste() { if(completeFieldText != null) { String newText = ClipboardBox.getClipboard(); setText(newText); return; } super.paste(); } // ------------------------------------------------------------------------- protected void triggerChangeAction() { this.requestFocusInWindow(); try { Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_ENTER); } catch (AWTException e) { e.printStackTrace(); } } }
8,784
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleSlider.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleSlider.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleSlider.java * */ package org.wandora.application.gui.simple; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.swing.JSlider; /** * * @author akivela */ public class SimpleSlider extends JSlider implements MouseWheelListener { private static final long serialVersionUID = 1L; public SimpleSlider(int orientation, int min, int max, int value) { super(orientation, min, max, value); this.addMouseWheelListener(this); } // ------------------------------------------------------------------------- @Override public void mouseWheelMoved(MouseWheelEvent e) { if(e.getWheelRotation() > 0) this.setValue(this.getValue() - 1); else this.setValue(this.getValue() + 1); } }
1,643
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleFileChooserUI.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleFileChooserUI.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.simple; import javax.swing.JFileChooser; import javax.swing.plaf.metal.MetalFileChooserUI; /** * * @author akivela */ public class SimpleFileChooserUI extends MetalFileChooserUI { /* protected String cancelButtonText; protected String cancelButtonToolTipText; protected Icon computerIcon; protected Icon detailsViewIcon; protected Icon directoryIcon; protected Icon fileIcon; protected Icon floppyDriveIcon; protected Icon hardDriveIcon; protected int helpButtonMnemonic; protected String helpButtonText; protected String helpButtonToolTipText; protected Icon homeFolderIcon; protected Icon listViewIcon; protected Icon newFolderIcon; protected int openButtonMnemonic; protected String openButtonText; protected String openButtonToolTipText; protected int saveButtonMnemonic; protected String saveButtonText; protected String saveButtonToolTipText; protected int updateButtonMnemonic; protected String updateButtonText; protected String updateButtonToolTipText; protected Icon upFolderIcon; */ public SimpleFileChooserUI(JFileChooser b) { super(b); } }
2,065
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleTimeSlider.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleTimeSlider.java
/* * Copyright (C) 2015 akivela * * 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 org.wandora.application.gui.simple; import static java.lang.Math.floor; import static java.lang.String.format; import java.awt.Cursor; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JProgressBar; /** * SimpleTimeSlider is a modified progress bar used to preview progress of an * audio and video clips. * * @author akivela */ public class SimpleTimeSlider extends JProgressBar { private static final long serialVersionUID = 1L; private final static int MULTIPLIER = 100; public SimpleTimeSlider() { super(); setStringPainted(true); setBorderPainted(false); } @Override public void setString(String txt) { if(txt == null) txt = ""; if(txt.length() > 100) txt = txt.substring(0, 100) + "..."; super.setString(txt); } public void setMaximum(double value) { super.setMaximum((int) floor(value*MULTIPLIER)); } public void setMinimum(double value) { super.setMinimum((int) floor(value*MULTIPLIER)); } @Override public void setMaximum(int value) { super.setMaximum(value*MULTIPLIER); } @Override public void setMinimum(int value) { super.setMinimum(value*MULTIPLIER); } public void setValue(double value) { super.setValue((int) floor(value*MULTIPLIER)); setString(getFormatTime((int) floor(value*MULTIPLIER), this.getMaximum())); setToolTipText(getString()); } @Override public void setValue(int value) { super.setValue(value*MULTIPLIER); setString(getFormatTime(value*MULTIPLIER, this.getMaximum())); setToolTipText(getString()); } @Override public int getValue() { int v = super.getValue(); return v/MULTIPLIER; } public int getValueFor(MouseEvent mouseEvent) { if(mouseEvent == null) return getValue(); else { int newValue = (( (MULTIPLIER*(mouseEvent.getX()-getX())) / getWidth()) * getMaximum()) / (MULTIPLIER*MULTIPLIER); newValue = Math.max(0, newValue); newValue = Math.min(super.getMaximum(), newValue); return newValue; } } public void setProgress(String text, int minValue, int value, int maxValue) { super.setMinimum(minValue*MULTIPLIER); super.setMaximum(maxValue*MULTIPLIER); super.setValue(value*MULTIPLIER); this.setString(text); } // ------------------------------------------------------------------------- @Override public void addMouseMotionListener(MouseMotionListener listener) { setCursor(Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR)); super.addMouseMotionListener(listener); } @Override public void addMouseListener(MouseListener listener) { if(getCursor().getType() != Cursor.W_RESIZE_CURSOR) { setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } super.addMouseListener(listener); } // ------------------------------------------------------------------------- private String getFormatTime(int elapsed, int duration) { elapsed = elapsed/MULTIPLIER; duration = duration/MULTIPLIER; int elapsedHours = elapsed / (60 * 60); if (elapsedHours > 0) { elapsed -= elapsedHours * 60 * 60; } int elapsedMinutes = elapsed / 60; int elapsedSeconds = elapsed - elapsedMinutes * 60; if (duration > 0) { int durationHours = duration / (60 * 60); if (durationHours > 0) { duration -= durationHours * 60 * 60; } int durationMinutes = duration / 60; int durationSeconds = duration - durationMinutes * 60; if (durationHours > 0) { return format("%d:%02d:%02d/%d:%02d:%02d", elapsedHours, elapsedMinutes, elapsedSeconds, durationHours, durationMinutes, durationSeconds); } else { return format("%02d:%02d/%02d:%02d", elapsedMinutes, elapsedSeconds, durationMinutes, durationSeconds); } } else { if (elapsedHours > 0) { return format("%d:%02d:%02d", elapsedHours, elapsedMinutes, elapsedSeconds); } else { return format("%02d:%02d", elapsedMinutes, elapsedSeconds); } } } }
5,498
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleTabbedPane.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleTabbedPane.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleTabbedPane.java * * Created on 19. lokakuuta 2005, 19:42 * */ package org.wandora.application.gui.simple; import java.awt.Graphics; import javax.swing.JTabbedPane; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleTabbedPane extends JTabbedPane { private static final long serialVersionUID = 1L; /** Creates a new instance of SimpleTabbedPane */ public SimpleTabbedPane() { this.setUI(new SimpleTabbedPaneUI()); this.setFont(UIConstants.tabFont); UIConstants.setFancyFont(this); this.setOpaque(false); } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
1,554
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleButton.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleButton.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleButton.java * * Created on 17. lokakuuta 2005, 19:23 * */ package org.wandora.application.gui.simple; import java.awt.Cursor; import java.awt.Graphics; import java.awt.event.MouseAdapter; import javax.swing.Icon; import javax.swing.JButton; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleButton extends JButton { private static final long serialVersionUID = 1L; /** Creates a new instance of SimpleButton */ public SimpleButton() { initialize(); } public SimpleButton(String label) { initialize(); setText(label); } public SimpleButton(Icon icon) { initialize(); this.setIcon(icon); } protected void initialize() { this.setFocusPainted(false); this.setFont(UIConstants.buttonLabelFont); UIConstants.setFancyFont(this); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); this.setOpaque(true); this.setBackground(UIConstants.defaultActiveBackground); this.addMouseListener( new MouseAdapter() { @Override public void mouseEntered(java.awt.event.MouseEvent evt) { if(evt.getComponent().isEnabled()) evt.getComponent().setBackground(UIConstants.defaultActiveBackground); } @Override public void mouseExited(java.awt.event.MouseEvent evt) { if(evt.getComponent().isEnabled()) evt.getComponent().setBackground(UIConstants.defaultActiveBackground); } } ); } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
2,667
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleTextArea.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleTextArea.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.simple; import java.awt.Graphics; import javax.swing.JTextArea; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleTextArea extends JTextArea { private static final long serialVersionUID = 1L; @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
1,214
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleMenu.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleMenu.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleMenu.java * * Created on 2. marraskuuta 2005, 15:27 * */ package org.wandora.application.gui.simple; import java.awt.Graphics; import javax.swing.Icon; import javax.swing.JMenu; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleMenu extends JMenu { private static final long serialVersionUID = 1L; /** Creates a new instance of SimpleMenu */ public SimpleMenu() { super(); } public SimpleMenu(String menuName) { this(menuName, UIBox.getIcon("gui/icons/empty.png")); } public SimpleMenu(String menuName, Icon icon) { if(menuName.startsWith("[") && menuName.endsWith("]")) { setEnabled(false); menuName = menuName.substring(1, menuName.length()-1); } setFont(UIConstants.menuFont); UIConstants.setFancyFont(this); setForeground(UIConstants.menuColor); setText(menuName); setName(menuName); setIcon(icon); } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } }
2,006
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleField.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleField.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleField.java * * Created on November 12, 2004, 3:22 PM */ package org.wandora.application.gui.simple; import java.awt.AWTKeyStroke; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Insets; import java.awt.KeyboardFocusManager; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseListener; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.border.Border; import javax.swing.undo.UndoManager; import org.wandora.application.Wandora; import org.wandora.application.gui.Clipboardable; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.utils.ClipboardBox; import org.wandora.utils.EasyVector; /** * * @author akivela */ public class SimpleField extends JTextField implements MouseListener, KeyListener, ActionListener, SimpleComponent, Clipboardable, DropTargetListener, DragGestureListener { private static final long serialVersionUID = 1L; protected Border defaultBorder = null; protected DropTarget dt; protected Wandora wandora = null; protected UndoManager undoManager = null; protected Insets defaultMargins = new Insets(3,3,3,3); protected String[] options = new String[] {}; private Object[] popupStruct = new Object[] { "Cut", UIBox.getIcon("gui/icons/cut.png"), "Copy", UIBox.getIcon("gui/icons/copy.png"), "Paste", UIBox.getIcon("gui/icons/paste.png"), "Clear", UIBox.getIcon("gui/icons/clear.png") }; public SimpleField(String name) { super(name); initialize(); } /** Creates a new instance of SimpleField */ public SimpleField() { initialize(); } // ------------------------------------------------------------------------- public void initialize() { this.addMouseListener(this); // this.setFocusTraversalKeysEnabled(false); this.addKeyListener(this); this.setFocusable(true); this.addFocusListener(this); this.setFocusTraversalKeysEnabled(true); this.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,new HashSet(new EasyVector(new Object[]{AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,0)}))); this.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,new HashSet(new EasyVector(new Object[]{AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,InputEvent.SHIFT_DOWN_MASK)}))); this.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); // undoManager = new UndoManager(); // Document document = this.getDocument(); // document.addUndoableEditListener(undoManager); this.setMargin(defaultMargins); this.setDragEnabled(true); dt = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this); setPopupMenu(); } public void setPopupMenu() { JPopupMenu popup = UIBox.makePopupMenu(popupStruct, this); setComponentPopupMenu(popup); } public void setOptions(String[] ops) { this.options = ops; } // ------------------------------------------------------------------------- public void setCurrentPart(String partText) { setPart(currentPartNumber(), partText); } public void setPart(int partNumber, String partText) { String[] fields = text2Parts(this.getText()); String oldPart = fields[partNumber]; fields[partNumber] = partText; setText(parts2Text(fields)); moveCaretToPart(partNumber+1); } public int currentPartNumber() { String s = getText().substring(0, getCaretPosition()); String[] fields = text2Parts(s); return fields.length-1; } public String currentPartString() { String s = getText().substring(0, getCaretPosition()); String[] fields = text2Parts(s); return fields[fields.length-1]; } public String parts2Text(String[] fields) { StringBuilder sb = new StringBuilder(); int size = fields.length; for(int i=0; i<size; i++) { sb.append(fields[i]); if(i<size-1) sb.append(" ; "); } return sb.toString(); } public String[] text2Parts(String text) { String[] parts = text.split(" ; "); try { if(Pattern.compile(" ; " + "$").matcher(text).find()) { String[] parts2 = new String[parts.length + 1]; for(int i=0; i<parts.length; i++) { parts2[i] = parts[i]; } parts2[parts.length] = ""; parts = parts2; } } catch(Exception e) { e.printStackTrace(); } return parts; } public void moveCaretToPart(int partNumber) { Pattern p = Pattern.compile("^" + " ; "); String text = getText(); int i = 0; int c = 0; for(; i<text.length(); i++) { Matcher m = p.matcher(text.substring(i)); if(m.find()) { c++; i = i+m.end(); } if(c == partNumber) break; } setCaretPosition(i); } // ------------------------------------------------------------------------- @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { } @Override public void keyPressed(java.awt.event.KeyEvent keyEvent) { } @Override public void keyReleased(java.awt.event.KeyEvent e) { /* if(listWindow==null && e.getKeyCode()==e.VK_TAB){ e.consume(); showList(); }*/ } @Override public void keyTyped(java.awt.event.KeyEvent e) { /* if(listWindow!=null){ e.setSource(listWindow.l); listWindow.l.dispatchEvent(e); }*/ } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c.equals("Copy")) { this.copy(); } else if(c.equals("Cut")) { this.cut(); } else if(c.equals("Paste")) { this.paste(); } else if(c.equals("Clear")) { this.setText(""); } else if(c.equals("Undo")) { if(undoManager != null) { if(undoManager.canUndo()) { undoManager.undo(); } } } else if(c.equals("Redo")) { if(undoManager != null) { if(undoManager.canRedo()) { undoManager.redo(); } } } } // ------------------------------------------------------------------------- // --------------------------------------------------------------- FOCUS --- // ------------------------------------------------------------------------- @Override public void focusGained(java.awt.event.FocusEvent focusEvent) { if(wandora == null) wandora = Wandora.getWandora(this); if(wandora != null) { wandora.gainFocus(this); } } @Override public void focusLost(java.awt.event.FocusEvent focusEvent) { // DO NOTHING... } // ------------------------------------------------------------------------- // --------------------------------------------------------- DRAG & DROP --- // ------------------------------------------------------------------------- @Override public void dragEnter(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { if(! UIConstants.dragBorder.equals( this.getBorder())) { defaultBorder = this.getBorder(); this.setBorder(UIConstants.dragBorder); } } @Override public void dragExit(java.awt.dnd.DropTargetEvent dropTargetEvent) { this.setBorder(defaultBorder); } @Override public void dragOver(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { if(! UIConstants.dragBorder.equals( this.getBorder())) { defaultBorder = this.getBorder(); this.setBorder(UIConstants.dragBorder); } } @Override public void drop(java.awt.dnd.DropTargetDropEvent e) { try { DataFlavor fileListFlavor = DataFlavor.javaFileListFlavor; DataFlavor stringFlavor = DataFlavor.stringFlavor; Transferable tr = e.getTransferable(); if(e.isDataFlavorSupported(fileListFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); java.util.List<File> files = (java.util.List<File>) tr.getTransferData(fileListFlavor); String text=""; for( File file : files ) { if(text.length()>0) text+=";"; text+=file.getPath(); } this.setText(text); e.dropComplete(true); } else if(e.isDataFlavorSupported(stringFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); String data = (String)tr.getTransferData(stringFlavor); this.setText(data); e.dropComplete(true); } else { System.out.println("Drop rejected! Wrong data flavor!"); e.rejectDrop(); } } catch(IOException ioe) { ioe.printStackTrace(); } catch(UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } catch(Error err) { err.printStackTrace(); } this.setBorder(defaultBorder); } @Override public void dropActionChanged(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { } @Override public void dragGestureRecognized(java.awt.dnd.DragGestureEvent dragGestureEvent) { } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } // ----------------------------------------------------------- CLIPBOARD --- @Override public void copy() { String text = getSelectedText(); if(text == null || text.length() == 0) { text = getText(); } ClipboardBox.setClipboard(text); } @Override public void cut() { String text = getSelectedText(); if(text == null || text.length() == 0) { ClipboardBox.setClipboard(getText()); setText(""); } else { ClipboardBox.setClipboard(text); removeSelectedText(); } } @Override public void paste() { String text = ClipboardBox.getClipboard(); replaceSelectedText(text); } // ------------------------------------------------------------------------- public void removeSelectedText() { try { int selectionStartLoc = this.getSelectionStart(); int selectionEndLoc = this.getSelectionEnd(); if(selectionStartLoc != selectionEndLoc) { int d = selectionEndLoc-selectionStartLoc; this.getDocument().remove(selectionStartLoc, d); } } catch(Exception e) { e.printStackTrace(); } } public void replaceSelectedText(String txt) { try { int selectionStartLoc = this.getSelectionStart(); int selectionEndLoc = this.getSelectionEnd(); if(selectionStartLoc != selectionEndLoc) { int d = selectionEndLoc-selectionStartLoc; this.getDocument().remove(selectionStartLoc, d); } this.getDocument().insertString(selectionStartLoc, txt, null); } catch(Exception e) { e.printStackTrace(); } } }
14,599
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleTextPane.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleTextPane.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleTextPane.java * * Created on November 16, 2004, 5:07 PM */ package org.wandora.application.gui.simple; import java.awt.AWTKeyStroke; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.KeyboardFocusManager; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseListener; import java.awt.print.Printable; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URI; import java.util.ArrayList; import java.util.HashSet; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.border.Border; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.text.AttributeSet; import javax.swing.text.Document; import javax.swing.undo.UndoManager; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.text.PDFTextStripper; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import org.wandora.utils.EasyVector; import org.wandora.utils.MSOfficeBox; import org.wandora.utils.Textbox; /** * * @author akivela */ public class SimpleTextPane extends javax.swing.JTextPane implements MouseListener, ActionListener, SimpleComponent, Printable, UndoableEditListener, DropTargetListener, DragGestureListener { private static final long serialVersionUID = 1L; private boolean DROP_FILE_NAMES_INSTEAD_FILE_CONTENT = false; public static final int MAX_TEXT_SIZE = 999999; private Border defaultBorder = null; private DropTarget dropTarget; private Wandora wandora = null; private Document document = null; private AttributeSet characterAttributes; // NOTE: THIS CLASS USES SAME OPTION DOMAIN AS TEXTEDITOR CLASS!!! public static final String OPTIONS_PREFIX = "textEditor."; protected JPopupMenu popup; protected Object[] popupStruct = new Object[] { "Undo", UIBox.getIcon("gui/icons/undo_undo.png"), "Redo", UIBox.getIcon("gui/icons/undo_redo.png"), "---", "Cut", UIBox.getIcon("gui/icons/cut.png"), "Copy", UIBox.getIcon("gui/icons/copy.png"), "Paste", UIBox.getIcon("gui/icons/paste.png"), "Clear", UIBox.getIcon("gui/icons/clear.png"), "---", "Select all", UIBox.getIcon("gui/icons/select_all.png"), "---", "Load...", UIBox.getIcon("gui/icons/file_open.png"), "Save...", UIBox.getIcon("gui/icons/file_save.png"), "---", "Print...", UIBox.getIcon("gui/icons/print.png"), }; private boolean shouldWrapLines = true; public UndoManager undo = new UndoManager(); /** Creates a new instance of SimpleTextPane */ public SimpleTextPane(JPanel parent) { wandora = Wandora.getWandora(); if(parent != null && parent instanceof MouseListener) this.addMouseListener((MouseListener) parent); //this.addFocusListener(this); this.addMouseListener(this); this.setFocusable(true); this.setFocusTraversalKeysEnabled(true); this.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,new HashSet(new EasyVector(new Object[]{AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,0)}))); this.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,new HashSet(new EasyVector(new Object[]{AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,InputEvent.SHIFT_DOWN_MASK)}))); getDocument().addUndoableEditListener(this); document = getDocument(); characterAttributes = getCharacterAttributes(); dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this); this.setDragEnabled(true); popup = UIBox.makePopupMenu(popupStruct, this); setComponentPopupMenu(popup); setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); } public SimpleTextPane() { this(null); } // ----------------------------------------------------- WRAP LONG LINES --- public void setLineWrap(boolean shouldWrap) { shouldWrapLines = shouldWrap; setSize(getSize().width+1, getSize().height); this.requestFocus(); } public boolean getLineWrap() { return shouldWrapLines; } @Override public void setSize(Dimension d) { if(!shouldWrapLines) { if (d.width < getParent().getSize().width) d.width = getParent().getSize().width; } super.setSize(d); } @Override public boolean getScrollableTracksViewportWidth() { if(!shouldWrapLines) return false; else return super.getScrollableTracksViewportWidth(); } public void dropFileNames(boolean flag) { DROP_FILE_NAMES_INSTEAD_FILE_CONTENT = flag; } public void setSuperText(String str) { super.setText(str); } @Override public void setText(String str) { try { document.remove(0, document.getLength()); document.insertString(0, str, characterAttributes); } catch(Exception e) { e.printStackTrace(); } } @Override public String getSelectedText() { String text = null; try { int selectionStartLoc = this.getSelectionStart(); int selectionEndLoc = this.getSelectionEnd(); if(selectionStartLoc < selectionEndLoc) { int d = selectionEndLoc-selectionStartLoc; text = document.getText(selectionStartLoc, d); } } catch(Exception e) { e.printStackTrace(); } return text; } public String getSelectedOrAllText() { String text = null; try { int selectionStartLoc = this.getSelectionStart(); int selectionEndLoc = this.getSelectionEnd(); if(selectionStartLoc == selectionEndLoc) { selectionStartLoc = 0; selectionEndLoc = document.getLength(); } int d = selectionEndLoc-selectionStartLoc; text = document.getText(selectionStartLoc, d); } catch(Exception e) { e.printStackTrace(); } return text; } public void replaceSelectedText(String txt) { try { int selectionStartLoc = this.getSelectionStart(); int selectionEndLoc = this.getSelectionEnd(); if(selectionStartLoc != selectionEndLoc) { int d = selectionEndLoc-selectionStartLoc; document.remove(selectionStartLoc, d); } document.insertString(selectionStartLoc, txt, characterAttributes); } catch(Exception e) { e.printStackTrace(); } } public void replaceSelectedOrAllText(String txt) { try { int selectionStartLoc = this.getSelectionStart(); int selectionEndLoc = this.getSelectionEnd(); if(selectionStartLoc == selectionEndLoc) { selectionStartLoc = 0; selectionEndLoc = document.getLength(); } int d = selectionEndLoc-selectionStartLoc; document.remove(selectionStartLoc, d); document.insertString(selectionStartLoc, txt, characterAttributes); } catch(Exception e) { e.printStackTrace(); } } public void insertText(String txt) { try { int selectionStartLoc = this.getSelectionStart(); int selectionEndLoc = this.getSelectionEnd(); if(selectionStartLoc == selectionEndLoc) { selectionStartLoc = 0; selectionEndLoc = document.getLength(); } int d = selectionEndLoc-selectionStartLoc; document.remove(selectionStartLoc, d); document.insertString(selectionStartLoc, txt, characterAttributes); } catch(Exception e) { e.printStackTrace(); } } public void removeSelectedText() { try { int selectionStartLoc = this.getSelectionStart(); int selectionEndLoc = this.getSelectionEnd(); if(selectionStartLoc != selectionEndLoc) { int d = selectionEndLoc-selectionStartLoc; document.remove(selectionStartLoc, d); } } catch(Exception e) { e.printStackTrace(); } } // ------------------------------------------------------------ PRINTING --- @Override public int print(java.awt.Graphics graphics, java.awt.print.PageFormat pageFormat, int param) throws java.awt.print.PrinterException { if (param > 0) { return(NO_SUCH_PAGE); } else { Graphics2D g2d = (Graphics2D)graphics; g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); // Turn off double buffering this.paint(g2d); // Turn double buffering back on return(PAGE_EXISTS); } } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } // ----------------------------------------------- FIND AND REPLACE TEXT --- public boolean findAndSelectNext(String findThis) { return findAndSelectNext(findThis,false); } public boolean findAndSelectNext(String findThis, boolean caseSensitive) { boolean success = false; this.requestFocus(); try { Document doc = getDocument(); String findHere = doc.getText(0, doc.getLength()); int caretLoc = getCaretPosition(); int selectionEndLoc = getSelectionEnd(); int startLoc = Math.max(caretLoc, selectionEndLoc); int loc = caseIndexOf(findHere, findThis, startLoc, caseSensitive); if(loc == -1) { caseIndexOf(findHere, findThis, 0, caseSensitive); } if(loc > -1) { select(loc, loc+findThis.length()); success = true; } } catch(Exception e) { e.printStackTrace(); } return success; } public boolean findAndReplaceNext(String findThis, String replaceWith) { return findAndReplaceNext(findThis, replaceWith, false); } public boolean findAndReplaceNext(String findThis, String replacementString, boolean caseSensitive) { boolean success = false; this.requestFocus(); try { Document doc = getDocument(); int caretLoc = getCaretPosition(); int selectionStartLoc = getSelectionStart(); int startLoc = Math.min(caretLoc, selectionStartLoc); String findHere = doc.getText(0, doc.getLength()); int loc = caseIndexOf(findHere, findThis, startLoc, caseSensitive); if(loc > -1) { setCaretPosition(loc); // where loc = position of first character of the string to replace AttributeSet ca = this.getCharacterAttributes(); AttributeSet pa = this.getParagraphAttributes(); doc.remove(loc, findThis.length()); doc.insertString(loc, replacementString, ca); getStyledDocument().setParagraphAttributes(loc, replacementString.length(), pa, false); success = true; } findAndSelectNext(findThis, caseSensitive); } catch (Exception e) { e.printStackTrace(); } return success; } public int findAndReplaceAll(String findThis, String replacementString) { return findAndReplaceAll(findThis, replacementString, false); } public int findAndReplaceAll(String findThis, String replacementString, boolean caseSensitive) { int maxCount = 9999; int count = 0; while(findAndReplaceNext(findThis, replacementString, caseSensitive) && ++count < maxCount); return count; } private int caseIndexOf(String findHere, String findThis, int startLoc, boolean caseSensitive) { if(caseSensitive) { return findHere.indexOf(findThis, startLoc); } else { String lowerCasedFindHere = findHere.toLowerCase(); String lowerCasedFindThis = findThis.toLowerCase(); return lowerCasedFindHere.indexOf(lowerCasedFindThis, startLoc); } } // ---------------------------------------------------------------- UNDO --- @Override public void undoableEditHappened(UndoableEditEvent e) { //Remember the edit and update the menus undo.addEdit(e.getEdit()); //undoAction.updateUndoState(); //redoAction.updateRedoState(); } // --------------------------------------------------------------- MOUSE --- @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { } // ------------------------------------------------------------------------- @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { if(actionEvent == null) return; String c = actionEvent.getActionCommand(); if(c == null) return; if(c.equals("Undo")) { if(undo != null) undo.undo(); } else if(c.equals("Redo")) { if(undo != null) undo.redo(); } else if(c.equals("Copy")) { this.copy(); } else if(c.equals("Cut")) { this.cut(); } else if(c.equals("Paste")) { this.paste(); } else if(c.equals("Clear")) { this.setText(""); } else if(c.equals("Select all")) { this.selectAll(); } else if(c.startsWith("Load")) { load(); } else if(c.startsWith("Save")) { save(); } else if(c.startsWith("Print")) { try { print(); } catch(java.awt.print.PrinterException pe){ pe.printStackTrace(); wandora.handleError(pe); } } } // ------------------------------------------------------------------------- // --------------------------------------------------------- LOAD & SAVE --- // ------------------------------------------------------------------------- public void load() { SimpleFileChooser chooser=UIConstants.getFileChooser(); chooser.setDialogTitle("Open file"); if(chooser.open(Wandora.getWandora(), SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { load(chooser.getSelectedFile()); } } public void load(File file) { if(file != null) { if(file.length() > MAX_TEXT_SIZE) { WandoraOptionPane.showMessageDialog(wandora, "File size is too big.", "File size is too big", WandoraOptionPane.WARNING_MESSAGE); } else { try { int a = WandoraOptionPane.showConfirmDialog(wandora, "Store the file content as a data URI?", "Make data URI?", WandoraOptionPane.QUESTION_MESSAGE); if(a == WandoraOptionPane.YES_OPTION) { DataURL url = new DataURL(file); setText(url.toExternalForm()); } else { Object desc = getStyledDocument(); Reader inputReader = null; String content = ""; String filename = file.getPath().toLowerCase(); String extension = filename.substring(Math.max(filename.lastIndexOf(".")+1, 0)); // --- handle rtf files --- if("rtf".equals(extension)) { content=Textbox.RTF2PlainText(new FileInputStream(file)); inputReader = new StringReader(content); } // --- handle pdf files --- if("pdf".equals(extension)) { try { PDDocument doc = PDDocument.load(file); PDFTextStripper stripper = new PDFTextStripper(); content = stripper.getText(doc); doc.close(); inputReader = new StringReader(content); } catch(Exception e) { System.out.println("No PDF support!"); } } // --- handle MS office files --- if("doc".equals(extension) || "ppt".equals(extension) || "xls".equals(extension) || "vsd".equals(extension) || "odt".equals(extension)) { content = MSOfficeBox.getText(new FileInputStream(file)); if(content != null) { inputReader = new StringReader(content); } } if("docx".equals(extension)) { content = MSOfficeBox.getDocxText(file); if(content != null) { inputReader = new StringReader(content); } } // --- handle everything else --- if(inputReader == null) { inputReader = new FileReader(file); } read(inputReader, desc); inputReader.close(); setCaretPosition(0); } } catch(MalformedURLException mfue) { mfue.printStackTrace(); wandora.handleError(mfue); } catch(IOException ioe) { ioe.printStackTrace(); wandora.handleError(ioe); } catch(Exception e) { e.printStackTrace(); wandora.handleError(e); } } } } public void save() { SimpleFileChooser chooser = UIConstants.getFileChooser(); chooser.setDialogTitle("Save file"); if(chooser.open(Wandora.getWandora(), SimpleFileChooser.SAVE_DIALOG) == SimpleFileChooser.APPROVE_OPTION) { save(chooser.getSelectedFile()); } } public void save(File file) { if(file != null) { try { String text = getText(); if(DataURL.isDataURL(text)) { DataURL.saveToFile(text, file); } else { FileWriter writer = new FileWriter(file); write(writer); writer.close(); } } catch(MalformedURLException mfue) { mfue.printStackTrace(); wandora.handleError(mfue); } catch(IOException ioe) { ioe.printStackTrace(); wandora.handleError(ioe); } catch(Exception e) { e.printStackTrace(); wandora.handleError(e); } } } // ------------------------------------------------------------------------- // --------------------------------------------------------- TRANSLATION --- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // --------------------------------------------------------- DRAG & DROP --- // ------------------------------------------------------------------------- @Override public void dragEnter(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { if(! UIConstants.dragBorder.equals( this.getBorder())) { defaultBorder = this.getBorder(); this.setBorder(UIConstants.dragBorder); } } @Override public void dragExit(java.awt.dnd.DropTargetEvent dropTargetEvent) { this.setBorder(defaultBorder); } @Override public void dragOver(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { if(! UIConstants.dragBorder.equals( this.getBorder())) { defaultBorder = this.getBorder(); this.setBorder(UIConstants.dragBorder); } } @Override public void drop(java.awt.dnd.DropTargetDropEvent e) { try { DataFlavor fileListFlavor = DataFlavor.javaFileListFlavor; DataFlavor stringFlavor = DataFlavor.stringFlavor; DataFlavor uriListFlavor = new DataFlavor("text/uri-list;class=java.lang.String"); Transferable tr = e.getTransferable(); if(tr.isDataFlavorSupported(fileListFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); final java.util.List<File> files = (java.util.List<File>) tr.getTransferData(fileListFlavor); String fileName = null; boolean CTRLPressed = ((e.getDropAction() & DnDConstants.ACTION_COPY) != 0); if(DROP_FILE_NAMES_INSTEAD_FILE_CONTENT && !CTRLPressed || (!DROP_FILE_NAMES_INSTEAD_FILE_CONTENT && CTRLPressed)) { StringBuilder sb = new StringBuilder(""); for( File file : files ) { fileName = file.getAbsolutePath(); sb.append(fileName); sb.append('\n'); } String text = getText(); if(text == null) text = ""; if(text.length() > 0 && !text.endsWith("\n")) text = text + "\n" + sb.toString(); else text = text + sb.toString(); setText(text); } else { Thread dropThread = new Thread() { public void run() { try { for( File file : files ) { load(file); } } catch(Exception e) { e.printStackTrace(); } catch(Error err) { err.printStackTrace(); } } }; dropThread.start(); } e.dropComplete(true); } else if(tr.isDataFlavorSupported(stringFlavor) || tr.isDataFlavorSupported(uriListFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); String data = null; if(tr.isDataFlavorSupported(uriListFlavor)) data=(String)tr.getTransferData(uriListFlavor); else data=(String)tr.getTransferData(stringFlavor); boolean handled=false; String[] split=data.split("\n"); boolean allFiles=true; final ArrayList<URI> uris=new ArrayList<>(); for(int i=0;i<split.length;i++) { try { URI u=new URI(split[i].trim()); if(u.getScheme()==null) continue; if(!u.getScheme().toLowerCase().equals("file")) allFiles=false; uris.add(u); } catch(java.net.URISyntaxException ue){} } if(!uris.isEmpty()) { if(allFiles) { boolean CTRLPressed = ((e.getDropAction() & DnDConstants.ACTION_COPY) != 0); if(DROP_FILE_NAMES_INSTEAD_FILE_CONTENT && !CTRLPressed || (!DROP_FILE_NAMES_INSTEAD_FILE_CONTENT && CTRLPressed)) { StringBuilder sb = new StringBuilder(""); for(URI u : uris) { sb.append(u.toString()); sb.append('\n'); } String text = getText(); if(text == null) text = ""; if(text.length() > 0 && !text.endsWith("\n")) text = text + "\n" + sb.toString(); else text = text + sb.toString(); setText(text); } else { Thread dropThread = new Thread() { public void run() { for(URI u : uris){ try { load(new File(u)); } catch(IllegalArgumentException iae){ iae.printStackTrace(); } catch(Error err) { err.printStackTrace(); } } } }; dropThread.start(); } } else { String text=""; for(URI u : uris){ if(text.length()>0) text+="\n"; text+=u.toString(); } this.setText(text); } handled=true; } if(!handled){ this.setText(data); handled=true; } e.dropComplete(true); } else { System.out.println("Unknown data flavor. Drop rejected."); e.rejectDrop(); } } catch(IOException ioe) { ioe.printStackTrace(); } catch(UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } catch(Error err) { err.printStackTrace(); } this.setBorder(defaultBorder); } @Override public void dropActionChanged(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { } @Override public void dragGestureRecognized(java.awt.dnd.DragGestureEvent dragGestureEvent) { } // ------------------------------------------------------------------------- @Override public void focusGained(java.awt.event.FocusEvent focusEvent) { if(wandora != null) { wandora.gainFocus(this); } } @Override public void focusLost(java.awt.event.FocusEvent focusEvent) { // DO NOTHING... } // ----------------------------------------------------------- CLIPBOARD --- @Override public void copy() { String text = getSelectedText(); ClipboardBox.setClipboard(text); } @Override public void cut() { String text = getSelectedText(); ClipboardBox.setClipboard(text); removeSelectedText(); } @Override public void paste() { String text = ClipboardBox.getClipboard(); replaceSelectedText(text); } }
31,470
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleTable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleTable.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleTable.java * * Created on 14. lokakuuta 2005, 11:00 */ package org.wandora.application.gui.simple; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Rectangle; import javax.swing.event.RowSorterEvent; import javax.swing.event.TableModelEvent; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.utils.swing.anyselectiontable.AnySelectionTable; /** * * @author akivela */ public class SimpleTable extends AnySelectionTable implements SimpleComponent { private static final long serialVersionUID = 1L; public static final int DEFAULT_ROW_HEIGHT = 21; /** Creates a new instance of SimpleTable */ public SimpleTable() { this.setFocusable(true); this.addFocusListener(this); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); this.setRowHeight(DEFAULT_ROW_HEIGHT); UIBox.registerClipboardableKeyStrokes(this); } @Override public void focusGained(java.awt.event.FocusEvent focusEvent) { Wandora w = Wandora.getWandora(); if(w != null) { w.gainFocus(this); } } @Override public void focusLost(java.awt.event.FocusEvent focusEvent) { } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } // ------------------------------------------------------------------------- // http://stackoverflow.com/questions/996948/live-sorting-of-jtable // ------------------------------------------------------------------------- private UpdateHandler beforeSort; @Override public void sorterChanged(RowSorterEvent e) { super.sorterChanged(e); maybeRepaintOnSorterChanged(e); } private void beforeUpdate(TableModelEvent e) { if (!isSorted()) return; beforeSort = new UpdateHandler(e); } private void afterUpdate() { beforeSort = null; } private void maybeRepaintOnSorterChanged(RowSorterEvent e) { if (beforeSort == null) return; if ((e == null) || (e.getType() != RowSorterEvent.Type.SORTED)) return; UpdateHandler afterSort = new UpdateHandler(beforeSort); if (afterSort.allHidden(beforeSort)) { return; } else if (afterSort.complex(beforeSort)) { repaint(); return; } int firstRow = afterSort.getFirstCombined(beforeSort); int lastRow = afterSort.getLastCombined(beforeSort); Rectangle first = getCellRect(firstRow, 0, false); first.width = getWidth(); Rectangle last = getCellRect(lastRow, 0, false); repaint(first.union(last)); } private class UpdateHandler { private int firstModelRow; private int lastModelRow; private int viewRow; private boolean allHidden; public UpdateHandler(TableModelEvent e) { firstModelRow = e.getFirstRow(); lastModelRow = e.getLastRow(); convert(); } public UpdateHandler(UpdateHandler e) { firstModelRow = e.firstModelRow; lastModelRow = e.lastModelRow; convert(); } public boolean allHidden(UpdateHandler e) { return this.allHidden && e.allHidden; } public boolean complex(UpdateHandler e) { return (firstModelRow != lastModelRow); } public int getFirstCombined(UpdateHandler e) { if (allHidden) return e.viewRow; if (e.allHidden) return viewRow; return Math.min(viewRow, e.viewRow); } public int getLastCombined(UpdateHandler e) { if (allHidden || e.allHidden) return getRowCount() - 1; return Math.max(viewRow, e.viewRow); } private void convert() { // multiple updates if (firstModelRow != lastModelRow) { // don't bother too much - calculation not guaranteed to do anything good // just check if the all changed indices are hidden allHidden = true; for (int i = firstModelRow; i <= lastModelRow; i++) { if (convertRowIndexToView(i) >= 0) { allHidden = false; break; } } viewRow = -1; return; } // single update viewRow = convertRowIndexToView(firstModelRow); allHidden = viewRow < 0; } } private boolean isSorted() { // JW: not good enough - need a way to decide if there are any sortkeys which // constitute a sort or any effective filters return getRowSorter() != null; } @Override public void tableChanged(TableModelEvent e) { if (isUpdate(e)) { beforeUpdate(e); } try { super.tableChanged(e); } finally { afterUpdate(); } } /** * Convenience method to detect dataChanged table event type. * * @param e the event to examine. * @return true if the event is of type dataChanged, false else. */ protected boolean isDataChanged(TableModelEvent e) { if (e == null) return false; return e.getType() == TableModelEvent.UPDATE && e.getFirstRow() == 0 && e.getLastRow() == Integer.MAX_VALUE; } /** * Convenience method to detect update table event type. * * @param e the event to examine. * @return true if the event is of type update and not dataChanged, false else. */ protected boolean isUpdate(TableModelEvent e) { if (isStructureChanged(e)) return false; return e.getType() == TableModelEvent.UPDATE && e.getLastRow() < Integer.MAX_VALUE; } /** * Convenience method to detect a structureChanged table event type. * @param e the event to examine. * @return true if the event is of type structureChanged or null, false else. */ protected boolean isStructureChanged(TableModelEvent e) { return e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW; } }
7,233
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleAWTMenuItem.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleAWTMenuItem.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleAWTMenuItem.java * */ package org.wandora.application.gui.simple; import java.awt.MenuItem; import java.awt.event.ActionListener; import org.wandora.application.gui.UIConstants; /** * * @author anttirt */ public class SimpleAWTMenuItem extends MenuItem { private static final long serialVersionUID = 1L; public SimpleAWTMenuItem() { } public SimpleAWTMenuItem(String menuName) { this(menuName, null); } public SimpleAWTMenuItem(String menuName, ActionListener defaultListener) { boolean enabled = true; //String iconResource = "gui/icons/empty.png"; if(menuName.startsWith("[") && menuName.endsWith("]")) { enabled = false; menuName = menuName.substring(1, menuName.length()-1); } if(menuName.startsWith("X ") || menuName.startsWith("O ")) { String name = menuName.substring(2); if(menuName.startsWith("X ")) { //menuItem=new javax.swing.JCheckBoxMenuItem(name, true); //iconResource = "gui/icons/checked.png"; } else { //menuItem=new javax.swing.JCheckBoxMenuItem(name, false); //iconResource = "gui/icons/unchecked.png"; } menuName = name; } //if(iconResource != null) setIcon(UIBox.getIcon(iconResource)); setFont(UIConstants.menuFont); setLabel(menuName); setName(menuName); setActionCommand(menuName); if(defaultListener != null) addActionListener(defaultListener); setEnabled(enabled); } }
2,473
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OccurrenceTypeLink.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/OccurrenceTypeLink.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * AssociationTypeLink.java * */ package org.wandora.application.gui.simple; import org.wandora.application.Wandora; import org.wandora.application.gui.OccurrenceTable; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class OccurrenceTypeLink extends TopicLink { private static final long serialVersionUID = 1L; private OccurrenceTable occurrenceTable = null; /** Creates a new instance of AssociationTypeLink */ public OccurrenceTypeLink(OccurrenceTable ot, Topic t, Wandora wandora) { super(t, wandora); occurrenceTable = ot; } public OccurrenceTable getOccurrenceTable() { return occurrenceTable; } }
1,522
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AssociationTypeLink.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/AssociationTypeLink.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * AssociationTypeLink.java * */ package org.wandora.application.gui.simple; import org.wandora.application.Wandora; import org.wandora.application.gui.table.AssociationTable; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class AssociationTypeLink extends TopicLink { private static final long serialVersionUID = 1L; private AssociationTable associationTable = null; /** Creates a new instance of AssociationTypeLink */ public AssociationTypeLink(AssociationTable at, Topic t, Wandora wandora) { super(t, wandora); associationTable = at; } public AssociationTable getAssociationTable() { return associationTable; } }
1,538
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimplePanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimplePanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimplePanel.java * * Created on 7. lokakuuta 2005, 16:50 */ package org.wandora.application.gui.simple; import java.awt.Graphics; import javax.swing.JPanel; import javax.swing.border.Border; import javax.swing.border.TitledBorder; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimplePanel extends JPanel { private static final long serialVersionUID = 1L; /** Creates a new instance of SimplePanel */ public SimplePanel() { } @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } @Override public void setBorder(Border border) { if(border instanceof TitledBorder) { TitledBorder titledBorder = (TitledBorder) border; titledBorder.setTitleFont(UIConstants.panelTitleFont); } super.setBorder(border); } }
1,752
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimpleComboBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/simple/SimpleComboBox.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * SimpleComboBox.java * * Created on November 16, 2004, 5:15 PM */ package org.wandora.application.gui.simple; import java.awt.Component; import java.awt.Cursor; import java.awt.event.MouseListener; import java.util.Collection; import java.util.Enumeration; import java.util.Set; import java.util.Vector; import javax.swing.ComboBoxEditor; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class SimpleComboBox extends JComboBox implements MouseListener, SimpleComponent { private static final long serialVersionUID = 1L; /** Creates a new instance of SimpleComboBox */ public SimpleComboBox() { initialize(); } public SimpleComboBox(Vector v) { super(v); initialize(); } public SimpleComboBox(String[] content) { super(); initialize(); setOptions(content); } public SimpleComboBox(Set content) { super(); initialize(); setOptions(content); } public SimpleComboBox(Collection content) { super(); initialize(); setOptions(content); } private void initialize() { this.addMouseListener(this); this.setFont(UIConstants.comboBoxFont); UIConstants.setFancyFont(this); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); ComboBoxEditor e = this.getEditor(); Component ec = e.getEditorComponent(); this.setRenderer(new BorderListCellRenderer()); this.setEditable(true); } @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } @Override public void mousePressed(java.awt.event.MouseEvent mouseEvent) { } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { } public void setOptions(String[] content) { removeAllItems(); for (String item : content) { addItem(item); } } public void setOptions(Enumeration content) { removeAllItems(); while(content.hasMoreElements()) { try { addItem(content.nextElement()); } catch (Exception e) {} } } public void setOptions(Set content) { removeAllItems(); for(Object o : content) { try { addItem(o); } catch (Exception e) {} } } public void setOptions(Collection content) { removeAllItems(); for(Object o : content) { try { addItem(o); } catch (Exception e) {} } } @Override public void focusGained(java.awt.event.FocusEvent focusEvent) { // DO NOTHING... } @Override public void focusLost(java.awt.event.FocusEvent focusEvent) { // DO NOTHING... } /* @Override public void paint(Graphics g) { UIConstants.preparePaint(g); super.paint(g); } */ // ------------------------------------------------------------------------- public class BorderListCellRenderer implements ListCellRenderer { private Border insetBorder; private DefaultListCellRenderer defaultRenderer; public BorderListCellRenderer() { this.insetBorder = new EmptyBorder(0, 4, 0, 4); this.defaultRenderer = new DefaultListCellRenderer(); } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus ); renderer.setBorder(insetBorder); return renderer; } } }
5,316
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WebViewTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/WebViewTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.topicpanels; import java.awt.BorderLayout; import java.awt.Color; import java.util.Collection; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.border.LineBorder; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.topicpanels.webview.WebViewPanel; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import javafx.scene.web.WebEngine; /** * * @author akivela */ public class WebViewTopicPanel implements TopicPanel { private Topic currentTopic = null; private WebViewPanel webPanel = null; public WebViewTopicPanel() { } @Override public void init() { } @Override public boolean supportsOpenTopic() { return true; } @Override public void open(Topic topic) throws TopicMapException { currentTopic = topic; if(webPanel != null) webPanel.open(topic); } @Override public void stop() { if(webPanel != null) webPanel.stop(); } @Override public void refresh() throws TopicMapException { if(webPanel != null) webPanel.refresh(); } // ------------------------------------------------------------------------- @Override public boolean applyChanges() throws CancelledException, TopicMapException { if(webPanel != null) return webPanel.applyChanges(); return false; } @Override public JPanel getGui() { if(webPanel == null) { try { Class.forName("javafx.embed.swing.JFXPanel"); webPanel = new WebViewPanel(); if(currentTopic != null) { try { webPanel.open(currentTopic); } catch(Exception e) {} } } catch(NoClassDefFoundError e) { return getErrorPanel(); } catch (ClassNotFoundException ex) { return getErrorPanel(); } } return webPanel; } private JPanel getErrorPanel() { JPanel p = new JPanel(); p.setLayout(new BorderLayout()); SimpleLabel sl = new SimpleLabel(); sl.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); sl.setBorder(new LineBorder(Color.BLACK, 1)); sl.setText("Can't find JavaFX. Webview has been disabled."); p.add(sl, BorderLayout.CENTER); p.setBackground(Color.WHITE); return p; } @Override public Topic getTopic() throws TopicMapException { if(webPanel != null) return webPanel.getTopic(); return currentTopic; } @Override public String getName() { return "Webview"; } @Override public String getTitle() { if(webPanel != null) return webPanel.getTitle(); else if(currentTopic == null) return getName(); else return TopicToString.toString(currentTopic); } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_panel_webview.png"); } @Override public int getOrder() { return 2000; } @Override public Object[] getViewMenuStruct() { return null; } @Override public JMenu getViewMenu() { return null; } @Override public JPopupMenu getViewPopupMenu() { return null; } @Override public LocatorHistory getTopicHistory() { return null; } @Override public boolean noScroll(){ return false; } // ------------------------------------------------------------------------- public WebEngine getWebEngine() { if(webPanel != null) return webPanel.getWebEngine(); return null; } public String getWebLocation() { if(webPanel != null) return webPanel.getWebLocation(); return null; } public String getSource() { if(webPanel != null) return webPanel.getSource(); return null; } public String getSelectedText() { if(webPanel != null) return webPanel.getSelectedText(); return null; } public String getWebTitle() { if(webPanel != null) return webPanel.getWebTitle(); return null; } public Object executeJavascript(String script) { if(webPanel != null) return webPanel.executeSynchronizedScript(script); return null; } // ------------------------------------------------------------------------- @Override public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { if(webPanel != null) webPanel.topicSubjectIdentifierChanged(t, added, removed); } @Override public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { if(webPanel != null) webPanel.topicBaseNameChanged(t, newName, oldName); } @Override public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { if(webPanel != null) webPanel.topicTypeChanged(t, added, removed); } @Override public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { if(webPanel != null) webPanel.topicVariantChanged(t, scope, newName, oldName); } @Override public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { if(webPanel != null) webPanel.topicDataChanged(t, type, version, newValue, oldValue); } @Override public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { if(webPanel != null) webPanel.topicSubjectLocatorChanged(t, newLocator, oldLocator); } @Override public void topicRemoved(Topic t) throws TopicMapException { if(webPanel != null) webPanel.topicRemoved(t); } @Override public void topicChanged(Topic t) throws TopicMapException { if(webPanel != null) webPanel.topicChanged(t); } @Override public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { if(webPanel != null) webPanel.associationTypeChanged(a, newType, oldType); } @Override public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { if(webPanel != null) webPanel.associationPlayerChanged(a, role, newPlayer, oldPlayer); } @Override public void associationRemoved(Association a) throws TopicMapException { if(webPanel != null) webPanel.associationRemoved(a); } @Override public void associationChanged(Association a) throws TopicMapException { if(webPanel != null) webPanel.associationChanged(a); } }
8,256
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicPanelManager.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/TopicPanelManager.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicPanelManager.java * * Created on 19. lokakuuta 2005, 19:23 * */ package org.wandora.application.gui.topicpanels; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.KeyStroke; import org.wandora.application.CancelledException; import org.wandora.application.RefreshListener; import org.wandora.application.Wandora; import org.wandora.application.gui.EditorPanel; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleMenu; import org.wandora.application.gui.simple.SimpleMenuItem; import org.wandora.exceptions.OpenTopicNotSupportedException; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.topicmap.TopicMapReadOnlyException; import org.wandora.topicmap.TopicTools; import org.wandora.utils.Options; import bibliothek.gui.Dockable; /** * @author akivela */ public class TopicPanelManager implements ActionListener { private Set<String> topicPanelsSupportingOpenTopic = new LinkedHashSet<>(); private Map<String,String> topicPanelMap = new LinkedHashMap<>(); private Map<String,Integer> topicPanelOrder = new LinkedHashMap<>(); private Map<String,Icon> topicPanelIcon = new LinkedHashMap<>(); private Wandora wandora; private TopicPanel oldTopicPanel = null; private TopicPanel baseTopicPanel; private String baseTopicPanelClassName; private Options options; private KeyStroke[] accelerators = new KeyStroke[] { KeyStroke.getKeyStroke(KeyEvent.VK_1, InputEvent.ALT_DOWN_MASK ), KeyStroke.getKeyStroke(KeyEvent.VK_2, InputEvent.ALT_DOWN_MASK ), KeyStroke.getKeyStroke(KeyEvent.VK_3, InputEvent.ALT_DOWN_MASK ), KeyStroke.getKeyStroke(KeyEvent.VK_4, InputEvent.ALT_DOWN_MASK ), KeyStroke.getKeyStroke(KeyEvent.VK_5, InputEvent.ALT_DOWN_MASK ), KeyStroke.getKeyStroke(KeyEvent.VK_6, InputEvent.ALT_DOWN_MASK ), KeyStroke.getKeyStroke(KeyEvent.VK_7, InputEvent.ALT_DOWN_MASK ), KeyStroke.getKeyStroke(KeyEvent.VK_8, InputEvent.ALT_DOWN_MASK ), KeyStroke.getKeyStroke(KeyEvent.VK_9, InputEvent.ALT_DOWN_MASK ), }; public TopicPanelManager(Wandora w) { this.wandora = w; this.options = w.options; try { baseTopicPanelClassName = options.get("gui.topicPanels.base"); initialize(); } catch (Exception e) { } } // ------------------------------------------------------------------------- public void reset() { deactivateTopicPanel(); TopicPanel tp = getTopicPanel(); activateTopicPanel(); wandora.topicPanelsChanged(); } public void setTopicPanel(String topicPanelName) throws TopicMapException { if(topicPanelName != null) { String topicPanelClassName = topicPanelMap.get(topicPanelName); if(topicPanelClassName != null && !topicPanelClassName.equals(baseTopicPanelClassName)) { baseTopicPanelClassName = topicPanelClassName; options.put("gui.topicPanels.base", baseTopicPanelClassName); baseTopicPanel = getTopicPanel(); } } } public TopicPanel getCurrentTopicPanel() { return baseTopicPanel; } public TopicPanel getTopicPanel() { try { boolean reuse=false; if(baseTopicPanel!=null) { if(baseTopicPanel.getClass().getName().equals(baseTopicPanelClassName)) { reuse=true; } } if(!reuse) { if(baseTopicPanel != null) { baseTopicPanel.stop(); } baseTopicPanel = getTopicPanelWithClassName(baseTopicPanelClassName); if(baseTopicPanel != null) { baseTopicPanel.init(); } } if(baseTopicPanel == null) { baseTopicPanel = new DockingFramePanel(); baseTopicPanel.init(); } } catch (Exception e) { e.printStackTrace(); } return baseTopicPanel; } public TopicPanel getTopicPanel(String topicPanelName) { TopicPanel topicPanel = null; try { String topicPanelClassName = (String) topicPanelMap.get(topicPanelName); topicPanel = getTopicPanelWithClassName(topicPanelClassName); } catch (Exception e) { System.out.println("No topic panel for name: " + topicPanelName); if(wandora != null) wandora.handleError(e); } return topicPanel; } public TopicPanel getTopicPanelWithClassName(String topicPanelClassName) throws Exception { TopicPanel topicPanel = null; try { if(topicPanelClassName != null) { if(!topicPanelClassName.contains("$")) { // Skip inner classes! Class topicPanelClass = Class.forName(topicPanelClassName); if(TopicPanel.class.isAssignableFrom(topicPanelClass) && !Modifier.isAbstract(topicPanelClass.getModifiers()) && !Modifier.isInterface(topicPanelClass.getModifiers()) ){ topicPanel = (TopicPanel) topicPanelClass.newInstance(); } } } } catch (Exception e) { Wandora.getWandora().handleError(e); // All kinds of exceptions are caught here, some because we try // to instantiate something we shouldn't and something which we // might care about. Ideally would catch a bit more specifically. //e.printStackTrace(); } return topicPanel; } // ------------------------------------------------------------------------- public void initialize() { try { int panelCounter = 0; String className = null; do { className = options.get("gui.topicPanels.panel["+panelCounter+"]"); if(className != null) { TopicPanel topicPanel = getTopicPanelWithClassName(className); if(topicPanel != null) { //System.out.println("TopicPanel class found: " + className); String panelName = topicPanel.getName(); topicPanelMap.put(panelName, className); topicPanelOrder.put(panelName, topicPanel.getOrder()); topicPanelIcon.put(panelName, topicPanel.getIcon()); if(topicPanel.supportsOpenTopic()) { topicPanelsSupportingOpenTopic.add(className); } } } panelCounter++; } while(className != null); } catch (Exception e) { e.printStackTrace(); } } public List<List<Object>> getAvailableTopicPanels() { List<List<Object>> availablePanels = new ArrayList<>(); for(String panelName : sortedTopicPanels()) { List<Object> panelData = new ArrayList<>(); String panelClass = topicPanelMap.get(panelName); panelData.add(panelClass); panelData.add(panelName); panelData.add(topicPanelIcon.get(panelName)); availablePanels.add(panelData); } return availablePanels; } public List<List<Object>> getAvailableTopicPanelsSupportingOpenTopic() { List<List<Object>> availablePanels = new ArrayList<>(); for(String panelName : sortedTopicPanels()) { List<Object> panelData = new ArrayList<>(); String panelClass = topicPanelMap.get(panelName); if(topicPanelsSupportingOpenTopic.contains(panelClass)) { panelData.add(panelClass); panelData.add(panelName); panelData.add(topicPanelIcon.get(panelName)); availablePanels.add(panelData); } } return availablePanels; } // ------------------------------------------------------------------------- public Object[] getViewMenuStruct() { if(baseTopicPanel != null) { return baseTopicPanel.getViewMenuStruct(); // Current configuration of Wandora sets baseTopicPanel to // DockingFramePanel. See getViewMenuStruct method in DockingFramePanel. } else { return new Object[] { }; } } public SimpleMenu getTopicPanelMenu() { return (SimpleMenu)getTopicPanelMenu(null); } public JComponent getTopicPanelMenu(JComponent topicPanelMenu) { SimpleMenuItem topicPanelMenuItem = null; if(topicPanelMenu==null) { topicPanelMenu = new SimpleMenu("New panel"); ((SimpleMenu)topicPanelMenu).setIcon(UIBox.getIcon("gui/icons/topic_panels.png")); } int numberOfTopicPanels = 0; for( String topicPanelName : sortedTopicPanels() ) { try { TopicPanel topicPanel = getTopicPanel(topicPanelName); if(topicPanel != null) { topicPanelMenuItem = new SimpleMenuItem(topicPanel.getName(), this); if(topicPanelMenuItem != null) { if(numberOfTopicPanels < accelerators.length) { //topicPanelMenuItem.setAccelerator(accelerators[numberOfTopicPanels]); } numberOfTopicPanels++; topicPanelMenuItem.setIcon(topicPanel.getIcon()); topicPanelMenu.add(topicPanelMenuItem); } } } catch(Exception e) { e.printStackTrace(); } } return topicPanelMenu; } /** * Returns topic panels in the same order as they were read from * options. Old deprecated implementation used to sort topic panels * using a special sort value returned by a topic panel. */ private Collection<String> sortedTopicPanels() { List<String> sortedPanels = new ArrayList<>(); sortedPanels.addAll(topicPanelOrder.keySet()); /* Collections.sort(sortedPanels, new Comparator() { @Override public int compare(Object o1, Object o2) { int oi1 = topicPanelOrder.get(o1).intValue(); int oi2 = topicPanelOrder.get(o2).intValue(); if(oi1 == oi2) return 0; if(oi1 > oi2) return 1; else return -1; } }); */ return sortedPanels; } public Map<Dockable,TopicPanel> getDockedTopicPanels() { if(baseTopicPanel != null && baseTopicPanel instanceof DockingFramePanel) { return ((DockingFramePanel) baseTopicPanel).getDockedTopicPanels(); } return null; } @Override public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if(actionCommand != null) { //WAS: setTopicPanel(actionCommand); try { DockingFramePanel dockingPanel = (DockingFramePanel) baseTopicPanel; String dockableClassName = topicPanelMap.get(actionCommand); Class dockableClass = Class.forName(dockableClassName); if(dockableClass != null && dockingPanel != null) { TopicPanel topicPanel = (TopicPanel) dockableClass.newInstance(); topicPanel.init(); dockingPanel.changeTopicPanelInCurrentDockable(topicPanel, getOpenTopic()); } } catch(Exception ex) { ex.printStackTrace(); } } else { //System.out.println("Topic panel manager activation!"); } } // ------------------------------------------------------------------------- // ---------------------------------------------------------- OPEN TOPIC --- // ------------------------------------------------------------------------- /** * Open the topic again in the base topic panel. */ public void reopenTopic() throws TopicMapException, OpenTopicNotSupportedException { if(baseTopicPanel != null) { openTopic(baseTopicPanel.getTopic()); } } /** * Enforces base topic panel to save all changes. */ public boolean applyChanges() { try { if(baseTopicPanel != null) { baseTopicPanel.applyChanges(); return true; } else { return true; } } catch(TopicMapReadOnlyException troe) { int a = WandoraOptionPane.showConfirmDialog(wandora, "You have locked current topic map layer. Can't apply changes unless you unlock the layer. Press Cancel to reject changes.", "Unlock current topic map layer", WandoraOptionPane.OK_CANCEL_OPTION); if(a == WandoraOptionPane.CANCEL_OPTION) { return true; } } catch(TopicMapException tme){ wandora.handleError(tme); } catch(CancelledException ce) { } catch(Exception exc) { } return false; } /** * Opens the argument topic in the base topic panel. DockingFramePanel * opens the topic in current dockable. * * @param topic to be opened in the current topic panel. */ public void openTopic(Topic topic) throws TopicMapException, OpenTopicNotSupportedException { if(topic == null || topic.isRemoved()) return; if(topic.getSubjectIdentifiers().isEmpty()) { topic.addSubjectIdentifier(TopicTools.createDefaultLocator()); } if(baseTopicPanel == null || !baseTopicPanel.equals(oldTopicPanel)) { deactivateTopicPanel(); } getTopicPanel().open(topic); if(!baseTopicPanel.equals(oldTopicPanel)) { activateTopicPanel(); } oldTopicPanel = baseTopicPanel; wandora.topicPanelsChanged(); } /** * This method is called always before topic panel changes. It removes the * panel from Wandora's UI and removes listeners. */ protected void deactivateTopicPanel() { wandora.editorPanel.removeAll(); if(baseTopicPanel != null) { if(baseTopicPanel instanceof TopicMapListener) { wandora.removeTopicMapListener((TopicMapListener)baseTopicPanel); } if(baseTopicPanel instanceof RefreshListener) { wandora.removeRefreshListener((RefreshListener)baseTopicPanel); } } } /** * This method is called always after topic panel changes. It attaches * the topic panel to Wandora's main window. */ protected void activateTopicPanel() { if(baseTopicPanel instanceof TopicMapListener) { wandora.addTopicMapListener((TopicMapListener)baseTopicPanel); } if(baseTopicPanel instanceof RefreshListener) { wandora.addRefreshListener((RefreshListener)baseTopicPanel); } ((EditorPanel)wandora.editorPanel).addTopicPanel(baseTopicPanel); ((EditorPanel)wandora.editorPanel).revalidate(); ((EditorPanel)wandora.editorPanel).repaint(); } /** * Returns a topic that is open in base topic panel. * DockingFramePanel returns the topic in current dockable. * * @return Current topic opened in the panel. */ public Topic getOpenTopic() { if(baseTopicPanel!=null) { try { return baseTopicPanel.getTopic(); } catch(Exception e) { e.printStackTrace(); } } return null; } /** * Returns an icon for base topic panel. DockingFramePanel * returns the icon for current dockable. * * @return Topic panel's icon. */ public Icon getIcon() { if(baseTopicPanel!=null) { try { return baseTopicPanel.getIcon(); } catch(Exception e) { e.printStackTrace(); } } return null; } }
18,412
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
.#ProcessingTopicPanel.java.1.1
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/.#ProcessingTopicPanel.java.1.1
/* * ProcessingPanel.java * * Created on 2.9.2011, 14:11:43 */ package org.wandora.application.gui.topicpanels; import org.wandora.application.gui.WandoraOptionPane; import java.awt.Component; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Font; import java.awt.Window; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import java.io.Writer; import java.net.URL; import java.net.URLClassLoader; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import org.wandora.application.CancelledException; import org.wandora.application.RefreshListener; import org.wandora.application.Wandora; import org.wandora.application.gui.GuiBox; import org.wandora.application.gui.simple.*; import org.wandora.application.gui.topicpanels.processingpanel.*; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.topicmap.TopicMap; import processing.core.*; import jsyntaxpane.DefaultSyntaxKit; import org.apache.commons.lang.ArrayUtils; import org.eclipse.jdt.core.compiler.CompilationProgress; import org.eclipse.jdt.core.compiler.batch.BatchCompiler; import org.wandora.utils.Options; import org.wandora.utils.Tuples.T2; import org.wandora.application.gui.topicpanels.processingpanel.*; /** * * @author ookami */ public class ProcessingTopicPanel extends JPanel implements TopicMapListener, RefreshListener, TopicPanel, ActionListener, ComponentListener { private String tempReplaceStart = "/*<--||"; private String tempReplaceEnd = "-->||*/"; private TopicMap tm; private Topic rootTopic; private String currentUserGivenSource = ""; private boolean isSourceCompiled = false; private SketchTemplate runningTemplate = null; private boolean isGuiInitialized = false; private int charactersBefore = 0; private ArrayList<T2<String,String>> sketches = new ArrayList<T2<String,String>>(); public static final String optionsPrefix = "options.processingpanel"; public static final String processingClassName = "ProcessingSketch"; public static final String PROCESSING_OCCURRENCETYPE_SI="http://processing.org"; private boolean isSketchStarted = false; /** Creates new form ProcessingPanel */ public ProcessingTopicPanel() { } public void initialize(Topic topic, Wandora manager) throws TopicMapException { rootTopic = topic; if(!isGuiInitialized) { tm = manager.getTopicMap(); isGuiInitialized = true; initComponents(); this.addComponentListener(this); DefaultSyntaxKit.initKit(); codeEditor.setContentType("text/java"); processingListBox.setEditable(false); readOptions(); if(useOccurencesCheckBox.isSelected()) { loadTopicProcessingCode(); } checkAutoRun(); //System.out.println(System.getProperty("java.class.path")); invalidate(); } } private void checkAutoRun() { if(autoRunCheckBox.isSelected()) { parseUserSource(); buildProcessingGraph(); if(isSourceCompiled) { tabPanel.setSelectedComponent(graphHolder); } } else { stopAndRemoveGraph(); tabPanel.setSelectedComponent(editorPanel); } } private void readOptions () { loadStoredSketches(); Options options = Wandora.getWandora().getOptions(); boolean isSelected = options.getBoolean(optionsPrefix+".use_occurence_processing_code", false); useOccurencesCheckBox.setSelected(isSelected); boolean isSelectedAutoRun = options.getBoolean(optionsPrefix+".autorun", false); autoRunCheckBox.setSelected(isSelectedAutoRun); } public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); System.out.println("Processing panel catched action command '" + c + "'."); toggleVisibility(c); } private void parseUserSource() { try { String temp = ""; FileInputStream stream = new FileInputStream( new File("resources/processing/SketchTemplate.java")); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ temp = Charset.defaultCharset().decode(bb).toString(); } finally { stream.close(); } charactersBefore = temp.indexOf(tempReplaceStart); temp = temp.substring(temp.indexOf("\n")); String fullSource = temp.substring(0, temp.indexOf(tempReplaceStart)) + codeEditor.getText() + temp.substring(temp.indexOf(tempReplaceEnd)+tempReplaceEnd.length(), temp.length()); fullSource = fullSource.replaceAll("(?:SketchTemplate)", processingClassName); fullSource = fullSource.replaceFirst("(?:PApplet)", "SketchTemplate"); currentUserGivenSource = fullSource; } catch (Exception ex) { Logger.getLogger(ProcessingTopicPanel.class.getName()).log(Level.SEVERE, null, ex); } } private void stopAndRemoveGraph() { Component[] components = innerPanel.getComponents(); for (int i = 0; i < components.length; i++) { PApplet proComponent = (SketchTemplate) components[i]; proComponent.stop(); innerPanel.remove(proComponent); //proComponent.destroy(); } } private void buildProcessingGraph() { stopAndRemoveGraph(); try { compileProcessing(currentUserGivenSource); runningTemplate.wandoraInit(rootTopic); //runningTemplate.addComponentListener(this); innerPanel.add(runningTemplate); runningTemplate.init(); //runningTemplate.registerPost(this); //runningTemplate.registerPre(this); isSketchStarted = false; int timeElapsed = 0; while (runningTemplate.defaultSize&&!runningTemplate.finished && timeElapsed < 5000) try {timeElapsed += 50;Thread.sleep(50);} catch (Exception e) {} Dimension size = new Dimension(runningTemplate.width, runningTemplate.height); innerPanel.setPreferredSize(size); innerPanel.setMinimumSize(size); invalidate(); //revalidate(); //repaint(); isSourceCompiled = true; //compile; } catch (Exception ex) { Logger.getLogger(ProcessingTopicPanel.class.getName()).log(Level.SEVERE, null, ex); isSourceCompiled = false; } } private boolean compileProcessing(String source) { return compileProcessing(source, true); } // With ECJ compiler. Hmm... bit process should probably be broken to smaller functions. private boolean compileProcessing(String source, boolean replaceApplet) { boolean success = false; File temp = null; try { temp = File.createTempFile(processingClassName, ".java"); temp.deleteOnExit(); BufferedWriter out = new BufferedWriter(new FileWriter(temp)); out.write(source); out.close(); } catch (IOException ex) { ex.printStackTrace(); Logger.getLogger(ProcessingTopicPanel.class.getName()).log(Level.SEVERE, null, ex); } // TODO: Here a chance to optimize the compilation process greatly. // Compilation includes in all the classpaths used by Wandora, which // increase the compilation time greatly. So only the necessary // classpaths should included here. The ones that the SketchTemplate needs. String baseCommand[] = new String[] { "-Xemacs", "-source", "1.6", "-target", "1.6", "-classpath", System.getProperty("java.class.path"), "-nowarn", "-noExit", "-d", "resources/processing/compilations" // output the classes in the buildPath }; String oldname = temp.getName(); // Rename the temporary file to the real classname File temp2 = new File(temp.getParent()+"\\"+processingClassName+".java"); temp2.delete(); temp2.deleteOnExit(); temp.renameTo(temp2); String[] sourceFiles = new String[1]; sourceFiles[0] = temp2.getAbsolutePath(); String[] command = (String[]) ArrayUtils.addAll(baseCommand, sourceFiles); ArrayList<String> errors = new ArrayList<String>(); try { // Load errors into a local StringBuffer final StringBuffer errorBuffer = new StringBuffer(); // Create single method dummy writer class to slurp errors from ecj Writer internalWriter = new Writer() { public void write(char[] buf, int off, int len) { errorBuffer.append(buf, off, len); } public void flush() { } public void close() { } }; // Wrap as a PrintWriter since that's what compile() wants PrintWriter writer = new PrintWriter(internalWriter); //result = com.sun.tools.javac.Main.compile(command, writer); CompilationProgress progress = null; PrintWriter outWriter = new PrintWriter(System.out); success = BatchCompiler.compile(command, outWriter, writer, progress); // Close out the stream for good measure writer.flush(); writer.close(); BufferedReader reader = new BufferedReader(new StringReader(errorBuffer.toString())); //System.err.println(errorBuffer.toString()); String line = null; while ((line = reader.readLine()) != null) { //System.out.println("got line " + line); // debug // get first line, which contains file name, line number, // and at least the first line of the error message String errorFormat = "([\\w\\d_]+.java):(\\d+):\\s*(.*):\\s*(.*)\\s*"; String[] pieces = PApplet.match(line, errorFormat); // if it's something unexpected, die and print the mess to the console if (pieces == null) { // Send out the rest of the error message to the console. if(!line.startsWith("invalid Class-Path header") && line.length() > 3) { errors.add(line); } while ((line = reader.readLine()) != null) { if(!line.startsWith("invalid Class-Path header") && line.length() > 3) { errors.add(line); } } } } } catch (IOException e) { e.printStackTrace(); String bigSigh = "Error while compiling. (" + e.getMessage() + ")"; //e.printStackTrace(); errors.add(bigSigh); success = false; } if(success) { if(runningTemplate != null) { /*if(graphHolder.getComponentCount() > 0) { graphHolder.remove(runningTemplate); }*/ runningTemplate.stop(); } try { File sketchFile = new File("resources/processing/compilations"); ClassLoader loader = new URLClassLoader(new URL[] { sketchFile.toURI().toURL() }); runningTemplate = (SketchTemplate) loader.loadClass(processingClassName).newInstance(); } catch (Exception ex) { ex.printStackTrace(); Logger.getLogger(ProcessingTopicPanel.class.getName()).log(Level.SEVERE, null, ex); showRichErrorDialog(ex.getMessage()); } } if(errors.size() > 0) { StringBuilder erromsg = new StringBuilder(); for (int i = 0; i < errors.size(); i++) { erromsg.append(errors.get(i)); if(i<errors.size()-1) erromsg.append("\n"); } showRichErrorDialog(erromsg.toString()); } return success; } /* // Done with javax compiler private boolean compileProcessing(String source, boolean replaceApplet) { // Full name of the class that will be compiled. // If class should be in some package, // fullName should contain it too // (ex. "testpackage.DynaClass") String fullName = "org.wandora.application.gui.topicpanels.processingpanel.Sketchy"; // We get an instance of JavaCompiler. Then // we create a file manager // (our custom implementation of it) JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); //success = BatchCompiler.compile(command, outWriter, writer, progress); JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(diagnostics, null, null)); // Dynamic compiling requires specifying // a list of "files" to compile. In our case // this is a list containing one "file" which is in our case // our own implementation (see details below) List<JavaFileObject> jfiles = new ArrayList<JavaFileObject>(); jfiles.add(new CharSequenceJavaFileObject(fullName, source)); // We specify a task to the compiler. Compiler should use our file // manager and our list of "files". // Then we run the compilation with call() compiler.getTask(null, fileManager, diagnostics, null, null, jfiles).call(); StringBuilder msg = new StringBuilder(""); boolean hasErrors = false; for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { //msg.append(source); if(diagnostic.getKind() == Diagnostic.Kind.ERROR) { msg.append("ERROR: "); hasErrors = true; System.out.println((diagnostic.getPosition()-charactersBefore)+" "+(diagnostic.getEndPosition()-charactersBefore+1)); Markers.markText(codeEditor, (int)diagnostic.getPosition()-charactersBefore, (int) diagnostic.getEndPosition()-charactersBefore, new Markers.SimpleMarker(new Color(255, 200, 200))); } if(diagnostic.getKind() == Diagnostic.Kind.WARNING) msg.append("WARNING: "); msg.append(String.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic)); msg.append("\n"); } //WandoraOptionPane.showMessageDialog(this, msg.toString(), "Errors", WandoraOptionPane.ERROR_MESSAGE); if(hasErrors) { showRichErrorDialog(msg.toString()); } // Creating an instance of our compiled class and // running its toString() method // Needs to be stopped first if(!hasErrors && replaceApplet) { if(runningTemplate != null) { if(graphHolder.getComponentCount() > 0) { graphHolder.remove(runningTemplate); } runningTemplate.stop(); } try { runningTemplate = (SketchTemplate) fileManager.getClassLoader(null).loadClass(fullName).newInstance(); } catch (Exception ex) { //Logger.getLogger(ProcessingTopicPanel.class.getName()).log(Level.SEVERE, null, ex); hasErrors = true; showRichErrorDialog(ex.getMessage()); } } if(hasErrors) { return false; } else { return true; } } */ private void showRichErrorDialog(String msg) { final JTextArea area = new JTextArea(); area.setFont(new Font("Courier New", Font.BOLD, 13)); //area.setPreferredSize(new Dimension(520, 180)); area.setEditable(false); area.setText(msg); // TIP: Make the JOptionPane resizable using the HierarchyListener area.addHierarchyListener(new HierarchyListener() { public void hierarchyChanged(HierarchyEvent e) { Window window = SwingUtilities.getWindowAncestor(area); if (window instanceof Dialog) { Dialog dialog = (Dialog)window; if (!dialog.isResizable()) { dialog.setResizable(true); } } } }); JScrollPane scroller = new JScrollPane(area); scroller.setPreferredSize(new Dimension(520, 180)); //WandoraOptionPane.showMessageDialog(null, "", "Errors", JOptionPane.PLAIN_MESSAGE); JOptionPane.showMessageDialog(Wandora.getWandora(), scroller, "Errors", JOptionPane.PLAIN_MESSAGE); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; tabPanel = new SimpleTabbedPane(); editorPanel = new javax.swing.JPanel(); editorScroller = new SimpleScrollPane(); codeEditor = new javax.swing.JEditorPane(); codeBottomBar = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); checkBtn = new SimpleButton(); executeBtn = new SimpleButton(); jPanel2 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); autoRunCheckBox = new SimpleCheckBox(); useOccurencesCheckBox = new SimpleCheckBox(); processingListBox = new SimpleComboBox(); newBtn = new SimpleButton(); saveBtn = new SimpleButton(); graphHolder = new javax.swing.JPanel(); innerPanel = new javax.swing.JPanel(); setMaximumSize(new java.awt.Dimension(2147483647, 2147483647)); setLayout(new java.awt.BorderLayout()); editorPanel.setLayout(new java.awt.GridBagLayout()); editorScroller.setMinimumSize(new java.awt.Dimension(300, 300)); editorScroller.setPreferredSize(new java.awt.Dimension(300, 300)); editorScroller.setViewportView(codeEditor); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; editorPanel.add(editorScroller, gridBagConstraints); codeBottomBar.setLayout(new java.awt.GridBagLayout()); jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT)); checkBtn.setText("Check"); checkBtn.setPreferredSize(new java.awt.Dimension(75, 21)); checkBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { checkBtnMouseReleased(evt); } }); jPanel3.add(checkBtn); executeBtn.setText("Run"); executeBtn.setPreferredSize(new java.awt.Dimension(75, 21)); executeBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { executeOnMouseRelease(evt); } }); jPanel3.add(executeBtn); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; codeBottomBar.add(jPanel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; codeBottomBar.add(jPanel2, gridBagConstraints); jPanel1.setLayout(new java.awt.GridBagLayout()); autoRunCheckBox.setText("Autorun"); autoRunCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { autoRunCheckBoxActionPerformed(evt); } }); jPanel1.add(autoRunCheckBox, new java.awt.GridBagConstraints()); useOccurencesCheckBox.setText("Use occurence instead of"); useOccurencesCheckBox.setToolTipText("Use processing code from occurence if available."); useOccurencesCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { useOccurencesCheckBoxActionPerformed(evt); } }); jPanel1.add(useOccurencesCheckBox, new java.awt.GridBagConstraints()); processingListBox.setPreferredSize(new java.awt.Dimension(150, 20)); processingListBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { processingListBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4); jPanel1.add(processingListBox, gridBagConstraints); newBtn.setText("New"); newBtn.setPreferredSize(new java.awt.Dimension(65, 21)); newBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { newBtnMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 5); jPanel1.add(newBtn, gridBagConstraints); saveBtn.setText("Save"); saveBtn.setMaximumSize(new java.awt.Dimension(53, 23)); saveBtn.setMinimumSize(new java.awt.Dimension(53, 23)); saveBtn.setPreferredSize(new java.awt.Dimension(65, 21)); saveBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { saveBtnMouseReleased(evt); } }); jPanel1.add(saveBtn, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(1, 0, 1, 0); codeBottomBar.add(jPanel1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; editorPanel.add(codeBottomBar, gridBagConstraints); tabPanel.addTab("Code", editorPanel); graphHolder.setBackground(new java.awt.Color(255, 255, 255)); graphHolder.setMinimumSize(new java.awt.Dimension(640, 480)); graphHolder.setPreferredSize(new java.awt.Dimension(640, 480)); graphHolder.setLayout(new java.awt.GridBagLayout()); innerPanel.setLayout(new java.awt.BorderLayout()); graphHolder.add(innerPanel, new java.awt.GridBagConstraints()); tabPanel.addTab("Visualization", graphHolder); add(tabPanel, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void executeOnMouseRelease(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_executeOnMouseRelease parseUserSource(); buildProcessingGraph(); if(isSourceCompiled) { tabPanel.setSelectedComponent(graphHolder); } }//GEN-LAST:event_executeOnMouseRelease private void checkBtnMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_checkBtnMouseReleased parseUserSource(); if(compileProcessing(currentUserGivenSource, false)) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "No errors found.", "Syntax check", WandoraOptionPane.PLAIN_MESSAGE); } }//GEN-LAST:event_checkBtnMouseReleased private void newBtnMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_newBtnMouseReleased createNewProcessingSketch(); invalidate(); }//GEN-LAST:event_newBtnMouseReleased private void processingListBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processingListBoxActionPerformed if((evt.getModifiers() | java.awt.event.ActionEvent.ACTION_PERFORMED) != 0) { loadSketch(); } }//GEN-LAST:event_processingListBoxActionPerformed private void useOccurencesCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useOccurencesCheckBoxActionPerformed boolean isSelected = useOccurencesCheckBox.isSelected(); Wandora.getWandora().getOptions().put(optionsPrefix+".use_occurence_processing_code", ""+isSelected); }//GEN-LAST:event_useOccurencesCheckBoxActionPerformed private void autoRunCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoRunCheckBoxActionPerformed boolean isSelected = autoRunCheckBox.isSelected(); Wandora.getWandora().getOptions().put(optionsPrefix+".autorun", ""+isSelected); }//GEN-LAST:event_autoRunCheckBoxActionPerformed private void saveBtnMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveBtnMouseReleased saveCurrentProcessingSketch(); }//GEN-LAST:event_saveBtnMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox autoRunCheckBox; private javax.swing.JButton checkBtn; private javax.swing.JPanel codeBottomBar; private javax.swing.JEditorPane codeEditor; private javax.swing.JPanel editorPanel; private javax.swing.JScrollPane editorScroller; private javax.swing.JButton executeBtn; private javax.swing.JPanel graphHolder; private javax.swing.JPanel innerPanel; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JButton newBtn; private javax.swing.JComboBox processingListBox; private javax.swing.JButton saveBtn; private javax.swing.JTabbedPane tabPanel; private javax.swing.JCheckBox useOccurencesCheckBox; // End of variables declaration//GEN-END:variables public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { doRefresh(); } public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { doRefresh(); } public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { doRefresh(); } public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { doRefresh(); } public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { doRefresh(); } public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { doRefresh(); } public void topicRemoved(Topic t) throws TopicMapException { doRefresh(); } public void topicChanged(Topic t) throws TopicMapException { doRefresh(); } public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { doRefresh(); } public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { doRefresh(); } public void associationRemoved(Association a) throws TopicMapException { doRefresh(); } public void associationChanged(Association a) throws TopicMapException { doRefresh(); } public void doRefresh() throws TopicMapException { System.out.println("Refresh everything... which it is not doing..."); if(useOccurencesCheckBox.isSelected()) { loadTopicProcessingCode(); } checkAutoRun(); } public void stop() { throw new UnsupportedOperationException("Not supported yet."); } public boolean reusePanel(){return true;} public void refresh() throws TopicMapException { //throw new UnsupportedOperationException("Not supported yet."); doRefresh(); } public boolean applyChanges() throws CancelledException, TopicMapException { return true; } public JPanel getGui() { return this; } public Topic getTopic() throws TopicMapException { return rootTopic; } public Icon getIcon() { return GuiBox.getIcon("gui/icons/topic_panel_processing.png"); } public JMenu getViewMenu() { return null; } public JMenu getViewMenu(JMenu baseMenu) { Object[] menuStructure = new Object[] { "---" }; return GuiBox.makeMenu(baseMenu, menuStructure, this); } public void toggleVisibility(String componentName) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getName(){ return "Processing topic panel"; } public void componentShown(ComponentEvent e) {} public void componentResized(ComponentEvent e) { Dimension size = this.getParent().getParent().getSize(); //Container parentti = this.getParent(); size.height -= 30; //System.out.println(e.getComponent().toString()); //Dimension size = tabPanel.getSize(); //tabPanel.setSize(size); graphHolder.setPreferredSize(size); editorPanel.setPreferredSize(size); //repaint(); revalidate(); } public void componentHidden(ComponentEvent e) {} public void componentMoved(ComponentEvent e) {} public void createNewProcessingSketch() { try { String sketchCode = codeEditor.getText(); String sketchName = WandoraOptionPane.showInputDialog(Wandora.getWandora(), "Name of the processing sketch?", "", "Name of the processing sketch?"); String curName = null; String curCode = null; if(sketchName != null && sketchName.length()>0) { processingListBox.addItem(sketchName); sketches.add(new T2(sketchName, sketchCode)); processingListBox.setSelectedIndex(processingListBox.getItemCount()-1); if(Wandora.getWandora() != null && Wandora.getWandora().getOptions() != null) { Options options = Wandora.getWandora().getOptions(); int i=0; do { i++; curName = options.get(optionsPrefix + ".sketches[" + i +"].name"); curCode = options.get(optionsPrefix + ".sketches[" + i +"].code"); } while(curName != null && curCode != null && i<1000); options.put(optionsPrefix + ".sketches[" + i +"].name", sketchName); options.put(optionsPrefix + ".sketches[" + i +"].code", sketchCode); } else { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Unable to store processing sketch to application options!", WandoraOptionPane.WARNING_MESSAGE); } } else { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "No name given. Processing sketch was not stored!", WandoraOptionPane.WARNING_MESSAGE); } } catch(Exception e) { Wandora.getWandora().handleError(e); } } public void saveCurrentProcessingSketch() { try { String sketchCode = codeEditor.getText(); String sketchName = processingListBox.getSelectedItem().toString(); int itemIndex = processingListBox.getSelectedIndex(); sketches.set(itemIndex, new T2<String, String>(sketchName, sketchCode)); Options options = Wandora.getWandora().getOptions(); options.put(optionsPrefix + ".sketches[" + itemIndex +"].name", sketchName); options.put(optionsPrefix + ".sketches[" + itemIndex +"].code", sketchCode); } catch(Exception e) { Wandora.getWandora().handleError(e); } } public void loadStoredSketches() { if(Wandora.getWandora() == null) return; Options options = Wandora.getWandora().getOptions(); if(options == null) return; int i=0; String sketchName = null; String sketchCode = null; do { sketchName = options.get(optionsPrefix + ".sketches[" + i +"].name"); sketchCode = options.get(optionsPrefix + ".sketches[" + i +"].code"); if(sketchName != null && sketchCode != null) { sketches.add(new T2(sketchName, sketchCode)); processingListBox.addItem(sketchName); } i++; } while(sketchName != null && sketchCode != null && i<1000); } public void loadSketch() { try { int sketchIndex = processingListBox.getSelectedIndex(); if(sketches.size() > sketchIndex) { T2 namedSketch = (T2) sketches.get(sketchIndex); if(namedSketch != null) { String code = (String) namedSketch.e2; if(code != null) { codeEditor.setText(code); } } } } catch(Exception e) { Wandora.getWandora().handleError(e); } } private void loadTopicProcessingCode() { try { Topic processing_type = tm.getTopic(PROCESSING_OCCURRENCETYPE_SI); String data = rootTopic.getData(processing_type, Wandora.getWandora().getLang()); if(data != null) { codeEditor.setText(data); } } catch (TopicMapException ex) { Logger.getLogger(ProcessingTopicPanel.class.getName()).log(Level.SEVERE, null, ex); } } // This is called when the first frame of the papplet has been drawn /*public void post() { System.out.println("embedDefaultSize "+runningTemplate.defaultSize+" ja finished: "+runningTemplate.finished); if(!isSketchStarted) { Dimension size = new Dimension(runningTemplate.width, runningTemplate.height); innerPanel.setPreferredSize(size); isSketchStarted = true; } }*/ /*class SelectListItem { private String name = ""; private int index = 0; public SelectListItem(String name, int index) { this.name = name; this.index = index; } public String getName() { return name; } public int getIndex() { return index; } @Override public String toString() { return name; } }*/ }
34,706
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/TopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TopicPanel.java * * Created on 4. marraskuuta 2005, 12:53 * */ package org.wandora.application.gui.topicpanels; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.exceptions.OpenTopicNotSupportedException; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; /** * TopicPanel is an UI element used to view and edit topic map structures * such as topics and associations in Wandora. Wandora contains several * different topic panels such as GraphTopicPanel and TraditionalTopicPanel, * each implementing this interface. * * @author akivela */ public interface TopicPanel extends TopicMapListener { /** * Initialize the TopicPanel. Called always before the topic panel is used */ public void init(); /** * Does the topic panel support topic open? In other words can one call the * open method with a topic. */ public boolean supportsOpenTopic(); /** * Open a topic in the topic panel. Usually opening means that * the topic is being visualized in some way. */ public void open(Topic topic) throws TopicMapException, OpenTopicNotSupportedException; /** * A topic panel should stop all threads and close all (shared) resources. * Stopping closes the topic panel too. */ public void stop(); /** * Request topic panel UI refresh. The topic panel should refresh it's * content and trigger repaint. */ public void refresh() throws TopicMapException; /** * Topic panel should store all pending changes immediately. * Especially topic and association changes are important and should * be stored during applyChanges. */ public boolean applyChanges() throws CancelledException,TopicMapException; /** * Return the UI element for the topic panel. Wandora gets topic panel's * UI element here. */ public JPanel getGui(); /** * Return the active topic in topic panel. Usually the returned * topic is the same topic that was opened with open methed. */ public Topic getTopic() throws TopicMapException; /** * Return name of the topic panel. Name is viewed in Wandora's UI. */ public String getName(); /** * Return title of the topic panel. Name is viewed in the title bar of dockable. */ public String getTitle(); /** * Return icon image of the topic panel. Icon is viewed in Wandora's UI. */ public Icon getIcon(); /** * Return integer number that specifies topic panel's order. Order is used * to sort topic panel sets. Order number is not used anymore as available * panels are read from options.xml and the order in options is the order * Wandora views the panels. * * @deprecated */ public int getOrder(); /** * Topic panel can provide a menu structure that Wandora views in UI. * This method returns a plain object array of menu objects. Plain object * array is transformed into a menu using UIBox. */ public Object[] getViewMenuStruct(); public JMenu getViewMenu(); public JPopupMenu getViewPopupMenu(); /** * If this returns true, then the topic panel will not be wrapped inside * a scroll pane. Useful if the panel provides its own scrolling. */ public boolean noScroll(); /** * A topic panel can store it's own topic history. Topic history is used * to navigate backward and forward in Wandora. However, this is a hidden * feature and has NOT been taken into production yet! Thus, Wandora * doesn't support the topic panel specific topic histories yet! */ public LocatorHistory getTopicHistory(); }
4,844
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TraditionalTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/TraditionalTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TraditionalTopicPanel.java * * Created on August 9, 2004, 2:33 PM */ package org.wandora.application.gui.topicpanels; import java.awt.Color; import java.awt.Component; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.Wandora; import org.wandora.application.WandoraMenuManager; import org.wandora.application.gui.ConfirmResult; import org.wandora.application.gui.NewTopicPanelExtended; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.previews.PreviewWrapper; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleToggleButton; import org.wandora.application.gui.simple.SimpleURIField; import org.wandora.application.gui.topicpanels.traditional.AbstractTraditionalTopicPanel; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.navigate.OpenTopic; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * * @author olli, akivela */ public class TraditionalTopicPanel extends AbstractTraditionalTopicPanel implements ActionListener, TopicPanel { private static final long serialVersionUID = 1L; public static final boolean MAKE_LOCAL_SETTINGS_GLOBAL = false; public Topic topic; public String topicSI; private Wandora wandora; protected Options options; private Object[][] panelStruct; private String originalBN; private String originalSL; private JComponent buttonContainer = null; private PreviewWrapper previewWrapper = null; /** Creates new form TraditionalTopicPanel */ public TraditionalTopicPanel(Topic topic, Wandora wandora) { open(topic); this.setTransferHandler(new TopicPanelTransferHandler(this)); } public TraditionalTopicPanel() { this.options = new Options(Wandora.getWandora().getOptions()); this.setTransferHandler(new TopicPanelTransferHandler(this)); } @Override public void init() { this.wandora = Wandora.getWandora(); if(this.options == null) { // Notice, a copy of global options is created for local use. // Thus, local adjustments have no global effect. this.options = new Options(wandora.getOptions()); } try { if(options != null) { variantGUIType = options.get(VARIANT_GUITYPE_OPTIONS_KEY); if(variantGUIType == null || variantGUIType.length() == 0) { variantGUIType = VARIANT_GUITYPE_SCHEMA; } } } catch(Exception e) { e.printStackTrace(); } Object[] buttonStruct = { "Open topic", new OpenTopic(OpenTopic.ASK_USER), "New topic", UIBox.getIcon("gui/icons/new_topic.png"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { NewTopicPanelExtended newTopicPanel = new NewTopicPanelExtended(null); // TODO: Should pass a context to the constructor. if(newTopicPanel.getAccepted()) { try { Topic newTopic = newTopicPanel.createTopic(); if(newTopic != null) { Wandora.getWandora().openTopic(newTopic); } } catch(Exception ex) { ex.printStackTrace(); } } } }, }; buttonContainer = UIBox.makeButtonContainer(buttonStruct, Wandora.getWandora()); } @Override public void open(Topic topic) { this.topic = topic; this.topicSI = null; try { if(topic != null && !topic.isRemoved()) { this.topicSI = topic.getOneSubjectIdentifier().toExternalForm(); } } catch(Exception e) { e.printStackTrace(); } this.removeAll(); initComponents(); previewWrapper = (PreviewWrapper) previewPanel; buttonWrapperPanel.add(buttonContainer); panelStruct = new Object[][] { { variantRootPanel, "View names", "variantRootPanel" }, { classesRootPanel, "View classes", "classesRootPanel" }, { occurrencesRootPanel, "View occurrences", "occurrencesRootPanel"}, { associationRootPanel, "View associations", "associationRootPanel" }, { typedAssociationsRootPanel, "View associations where type", "typedAssociationsRootPanel" }, { instancesRootPanel, "View instances", "instancesRootPanel" }, { previewPanel, "View subject locators", "previewPanel" }, }; associationRootPanel.setTransferHandler(new AssociationTableTransferHandler(this)); instancesRootPanel.setTransferHandler(new InstancesPanelTransferHandler(this)); classesRootPanel.setTransferHandler(new ClassesPanelTransferHandler(this)); occurrencesRootPanel.setTransferHandler(new OccurrencesPanelTransferHandler(this)); refresh(); } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_panel_traditional.png"); } @Override public String getName() { return "Traditional"; } @Override public String getTitle() { if(topic != null) return TopicToString.toString(topic); else return ""; } @Override public int getOrder() { return 0; } @Override public Topic getTopic() { try { if((topic == null || topic.isRemoved()) && topicSI != null) { topic = wandora.getTopicMap().getTopic(topicSI); } return topic; } catch(Exception e) { e.printStackTrace(); return null; } } @Override public LocatorHistory getTopicHistory() { return null; } @Override public JPanel getGui() { return this; } @Override public boolean noScroll(){ return false; } // ------------------------------------------------------------------------- // ----------------------------------------------------------- VIEW MENU --- // ------------------------------------------------------------------------- @Override public JPopupMenu getViewPopupMenu() { return UIBox.makePopupMenu(getViewMenuStruct(), this); } @Override public JMenu getViewMenu() { return UIBox.makeMenu(getViewMenuStruct(), this); } @Override public Object[] getViewMenuStruct() { Icon viewIcon = UIBox.getIcon("gui/icons/view2.png"); Icon hideIcon = UIBox.getIcon("gui/icons/view2_no.png"); List<Object> menuVector = new ArrayList<>(); for(int i=0; i<panelStruct.length; i++) { Object[] panelData = panelStruct[i]; String panelName = ((JPanel) panelData[0]).getName(); menuVector.add( panelData[1] ); menuVector.add( options.isFalse(OPTIONS_VIEW_PREFIX + panelName) ? hideIcon : viewIcon ); menuVector.add( this ); } menuVector.add( "---" ); menuVector.add( "View all" ); menuVector.add( this ); menuVector.add( "Hide all" ); menuVector.add( this ); return menuVector.toArray(); } // ------------------------------------------------------------------------- // --------------------------------------------------- TOGGLE VISIBILITY --- // ------------------------------------------------------------------------- @Override public void toggleVisibility(String componentName) { boolean iDidIt = false; try { refresh(); } catch(Exception e) { return; } if("View All".equalsIgnoreCase(componentName)) { JPanel panel; for (Object[] panelStruct1 : panelStruct) { panel = (JPanel) panelStruct1[0]; setVisibitilityOption(panelStruct1[2].toString(), true); //panel.setVisible(true); } setVisibitilityOption("subjectLocatorIcons", true); iDidIt = true; } if("Hide All".equalsIgnoreCase(componentName)) { JPanel panel; for (Object[] panelStruct1 : panelStruct) { panel = (JPanel) panelStruct1[0]; setVisibitilityOption(panelStruct1[2].toString(), false); //panel.setVisible(false); } setVisibitilityOption("subjectLocatorIcons", false); iDidIt = true; } else { int panelIndex = solvePanelIndex(componentName); if(panelIndex >= 0) { String optionName = panelStruct[panelIndex][2].toString(); JPanel panel = (JPanel) panelStruct[panelIndex][0]; toggleVisibility(panel, optionName); iDidIt = true; } } if(iDidIt) { // refresh(); wandora.topicPanelsChanged(); } } private int solvePanelIndex(String componentName) { if(componentName == null) return -1; for(int i=0; i<panelStruct.length; i++) { if(componentName.equals(panelStruct[i][1])) return i; } return -1; } private void toggleVisibility(Component component, String optionName) { boolean currentValue = options.isFalse(OPTIONS_VIEW_PREFIX + optionName); //System.out.println("currentValue==" + currentValue); setVisibitilityOption(optionName, currentValue); if(component != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { refresh(); } catch(Exception e) { e.printStackTrace(); } } }); } } private void setVisibitilityOption(String key, boolean value) { options.put(OPTIONS_VIEW_PREFIX + key, value ? "true" : "false"); if(MAKE_LOCAL_SETTINGS_GLOBAL) { Options wandoraOptions = wandora.getOptions(); if(wandoraOptions != null) { wandoraOptions.put(OPTIONS_VIEW_PREFIX + key, value ? "true" : "false"); } } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- @Override public void refresh() { //Thread.dumpStack(); try { if(topicSI != null) { topic = wandora.getTopicMap().getTopic(topicSI); } if(topic==null || topic.isRemoved()) { //System.out.println("Topic is null or removed!"); containerPanel.setVisible(false); removedTopicMessage.setVisible(true); return; } else { containerPanel.setVisible(true); removedTopicMessage.setVisible(false); } } catch(Exception e){ e.printStackTrace(); //System.out.println("Topic is null or removed!"); containerPanel.setVisible(false); removedTopicMessage.setVisible(true); return; } //System.out.println("refresh"); super.refresh(); // First update visibility of panels!! for(int i=0; i<panelStruct.length; i++) { JPanel panel = (JPanel) panelStruct[i][0]; String panelOptionName = (String) panelStruct[i][2]; panel.setVisible( !options.isFalse(OPTIONS_VIEW_PREFIX + panelOptionName) ); } try { boolean viewPreview = options.getBoolean(OPTIONS_VIEW_PREFIX+"previewPanel", false); subjectLocatorViewButton.setSelected(viewPreview); if(viewPreview && previewWrapper != null) { previewWrapper.setURL(topic.getSubjectLocator()); } else { previewWrapper.stop(); } } catch(Exception e) { e.printStackTrace(); } if(associationRootPanel.isVisible()) buildAssociationsPanel(associationPanel, associationsNumber, topic, ASSOCIATIONS_WHERE_PLAYER, options, wandora); if(typedAssociationsRootPanel.isVisible()) buildAssociationsPanel(typedAssociationsPanel, typedAssociationNumber, topic, ASSOCIATIONS_WHERE_TYPE, options, wandora); if(classesRootPanel.isVisible()) buildClassesPanel(classesPanel, classesNumber, topic, options, wandora); if(subjectIdentifierRootPanel.isVisible()) buildSubjectIdentifierPanel(subjectIdentifierPanel, topic, options, wandora); if(instancesRootPanel.isVisible()) buildInstancesPanel(instancesPanel, instancesNumber, topic, options, wandora); variantGUIType = options.get(VARIANT_GUITYPE_OPTIONS_KEY); if(variantGUIType == null || variantGUIType.length() == 0) variantGUIType = VARIANT_GUITYPE_SCHEMA; if(VARIANT_GUITYPE_SCHEMA.equalsIgnoreCase(variantGUIType)) { if("vertical".equals(options.get(OPTIONS_PREFIX + "namePanelOrientation"))) { buildVerticalNamePanel(variantPanel, variantNumber, topic, this, options, wandora); } else { buildHorizontalNamePanel(variantPanel, variantNumber, topic, this, options, wandora); } } else { buildAllNamesPanel(variantPanel, variantNumber, topic, this, options, wandora); } // Always create occurrences panel as data in the panel is updated to topic map // in apply changes. See applyChanges below. buildOccurrencesPanel(dataPanel, dataNumber, topic, options, wandora); try { if(topic.getBaseName()!=null) { baseNameField.setText(topic.getBaseName()); baseNameField.setCaretPosition(0); Color c=wandora.topicHilights.getBaseNameColor(topic); if(c!=null) baseNameField.setForeground(c); else baseNameField.setForeground(Color.BLACK); } else { baseNameField.setText(""); baseNameField.setForeground(Color.BLACK); } originalBN=topic.getBaseName(); if(topic.getSubjectLocator()!=null) { subjectLocatorField.setText(topic.getSubjectLocator().toString()); subjectLocatorField.setCaretPosition(0); Color c=wandora.topicHilights.getSubjectLocatorColor(topic); if(c!=null) subjectLocatorField.setForeground(c); else subjectLocatorField.setForeground(Color.BLACK); originalSL=topic.getSubjectLocator().toString(); } else { subjectLocatorField.setText(""); subjectLocatorField.setForeground(Color.BLACK); originalSL=null; } } catch(Exception e) { System.out.println("Failed to initialize base or/and sl!"); e.printStackTrace(); } this.setComponentPopupMenu(getViewPopupMenu()); variantRootPanel.setComponentPopupMenu(getNamesMenu()); occurrencesRootPanel.setComponentPopupMenu(getOccurrencesMenu()); this.revalidate(); this.repaint(); //System.out.println("refresh-end"); } @Override public boolean applyChanges() throws CancelledException, TopicMapException { //System.out.println("applyChanges"); // First check if user has somehow removed current topic. // Then there is no need for apply changes! try { if(topic==null || topic.isRemoved()) { return false; } } catch(Exception e){ return false; } // Ok, topic is still around and we have to check if it has changed. boolean changed=false; String fieldTextSL = subjectLocatorField.getText().trim(); String origSL = originalSL; // ------- basenames ------- final String fieldTextBN = baseNameField.getText().trim(); String origBN = originalBN; if((origBN==null && fieldTextBN.length()>0) || (origBN!=null && !origBN.equals(fieldTextBN))) { if(TMBox.checkBaseNameChange(wandora, topic, fieldTextBN) != ConfirmResult.yes) { baseNameField.setText(origBN); throw new CancelledException(); } if(fieldTextBN.length() > 0) { System.out.println("set basename to "+fieldTextBN); topic.setBaseName(fieldTextBN); } else { topic.setBaseName(null); } changed=true; } // ------ subject locator ------- if((origSL==null && fieldTextSL.length()>0) || (origSL!=null && !origSL.equals(fieldTextSL))) { if(TMBox.checkSubjectLocatorChange(wandora,topic,fieldTextSL)!=ConfirmResult.yes) { subjectLocatorField.setText(originalSL); throw new CancelledException(); } if(origSL!=null && !origSL.equals(fieldTextSL)) { topic.setSubjectLocator(null); } if(fieldTextSL.length()>0) { topic.setSubjectLocator(topic.getTopicMap().createLocator(fieldTextSL)); } changed=true; } // ------ everything else ------- changed = super.applyChanges(topic, wandora) | changed; if(changed) { wandora.doRefresh(); } //System.out.println("applyChanges-end"); return changed; } @Override public void stop() { if(previewWrapper != null) { previewWrapper.stop(); } PreviewWrapper.removePreviewWrapper(this); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; containerPanel = new javax.swing.JPanel(); previewContainerPanel = new javax.swing.JPanel(); previewPanel = PreviewWrapper.getPreviewWrapper(this); idPanel = new javax.swing.JPanel(); baseNameLabel = new org.wandora.application.gui.simple.SimpleLabel(); baseNameField = new SimpleField(); subjectLocatorLabel = new org.wandora.application.gui.simple.SimpleLabel(); subjectLocatorViewButton = new SimpleToggleButton("gui/icons/view2.png","gui/icons/view2_no.png",false); subjectLocatorField = new SimpleURIField(); subjectIdentifierLabel = new org.wandora.application.gui.simple.SimpleLabel(); subjectIdentifierRootPanel = new org.wandora.application.gui.simple.SimplePanel(); subjectIdentifierPanel = new javax.swing.JPanel(); variantRootPanel = new org.wandora.application.gui.simple.SimplePanel(); variantWrapperPanel = new javax.swing.JPanel(); variantTitlePanel = new javax.swing.JPanel(); variantTitle = new javax.swing.JLabel(); variantNumber = new javax.swing.JLabel(); variantTitleFiller = new javax.swing.JPanel(); variantPanelMargin = new javax.swing.JPanel(); variantPanel = new javax.swing.JPanel(); occurrencesRootPanel = new org.wandora.application.gui.simple.SimplePanel(); occurrencesWrapperPanel = new javax.swing.JPanel(); dataTitlePanel = new javax.swing.JPanel(); dataTitle = new javax.swing.JLabel(); dataNumber = new javax.swing.JLabel(); dataTitleFiller = new javax.swing.JPanel(); dataPanelMargin = new javax.swing.JPanel(); dataPanel = new javax.swing.JPanel(); classesRootPanel = new org.wandora.application.gui.simple.SimplePanel(); classesWrapperPanel = new javax.swing.JPanel(); classesTitlePanel = new javax.swing.JPanel(); classesTitle = new javax.swing.JLabel(); classesNumber = new javax.swing.JLabel(); classesTitleFiller = new javax.swing.JPanel(); classesPanelMargin = new javax.swing.JPanel(); classesPanel = new javax.swing.JPanel(); associationRootPanel = new org.wandora.application.gui.simple.SimplePanel(); associationWrapperPanel = new javax.swing.JPanel(); associationsTitlePanel = new javax.swing.JPanel(); associationsTitle = new javax.swing.JLabel(); associationsNumber = new javax.swing.JLabel(); associationsTitleFiller = new javax.swing.JPanel(); associationPanelMargin = new javax.swing.JPanel(); associationPanel = new javax.swing.JPanel(); typedAssociationsRootPanel = new org.wandora.application.gui.simple.SimplePanel(); typedAssociationsWrapperPanel = new javax.swing.JPanel(); typedAssociationsTitlePanel = new javax.swing.JPanel(); typedAssociationTitle = new javax.swing.JLabel(); typedAssociationNumber = new javax.swing.JLabel(); typedAssociationTitleFiller = new javax.swing.JPanel(); typesAssociationPanelMargin = new javax.swing.JPanel(); typedAssociationsPanel = new javax.swing.JPanel(); instancesRootPanel = new org.wandora.application.gui.simple.SimplePanel(); instancesWrapperPanel = new javax.swing.JPanel(); instancesTitlePanel = new javax.swing.JPanel(); instancesTitle = new javax.swing.JLabel(); instancesNumber = new javax.swing.JLabel(); instancesTitleFiller = new javax.swing.JPanel(); instancesPanelMargin = new javax.swing.JPanel(); instancesPanel = new javax.swing.JPanel(); fillerPanel = new javax.swing.JPanel(); removedTopicMessage = new javax.swing.JPanel(); removedTopicMessageLabel = new SimpleLabel(); buttonWrapperPanel = new javax.swing.JPanel(); setLayout(new java.awt.GridBagLayout()); containerPanel.setLayout(new java.awt.GridBagLayout()); previewContainerPanel.setLayout(new java.awt.GridBagLayout()); previewPanel.setToolTipText(""); previewPanel.setName("previewPanel"); // NOI18N previewPanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; previewContainerPanel.add(previewPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 10); containerPanel.add(previewContainerPanel, gridBagConstraints); idPanel.setLayout(new java.awt.GridBagLayout()); baseNameLabel.setForeground(new java.awt.Color(51, 51, 51)); baseNameLabel.setText("Base name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; idPanel.add(baseNameLabel, gridBagConstraints); baseNameField.setFont(new java.awt.Font("SansSerif", 0, 18)); // NOI18N baseNameField.setForeground(new java.awt.Color(33, 33, 33)); baseNameField.setMargin(new java.awt.Insets(0, 0, 0, 0)); baseNameField.setPreferredSize(new java.awt.Dimension(6, 29)); baseNameField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { baseNameFieldFocusLost(evt); } }); baseNameField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { baseNameFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); idPanel.add(baseNameField, gridBagConstraints); subjectLocatorLabel.setForeground(new java.awt.Color(51, 51, 51)); subjectLocatorLabel.setText("Subject locator"); subjectLocatorLabel.setComponentPopupMenu(getSLMenu()); subjectLocatorLabel.addMouseListener(wandora); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; idPanel.add(subjectLocatorLabel, gridBagConstraints); subjectLocatorViewButton.setToolTipText("View subject locator resource"); subjectLocatorViewButton.setBorderPainted(false); subjectLocatorViewButton.setContentAreaFilled(false); subjectLocatorViewButton.setMargin(new java.awt.Insets(2, 6, 2, 2)); subjectLocatorViewButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { subjectLocatorViewButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; idPanel.add(subjectLocatorViewButton, gridBagConstraints); subjectLocatorField.setFont(new java.awt.Font("SansSerif", 0, 18)); // NOI18N subjectLocatorField.setForeground(new java.awt.Color(33, 33, 33)); subjectLocatorField.setMargin(new java.awt.Insets(0, 0, 0, 0)); subjectLocatorField.setPreferredSize(new java.awt.Dimension(6, 29)); subjectLocatorField.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { subjectLocatorFieldFocusLost(evt); } }); subjectLocatorField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { subjectLocatorFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0); idPanel.add(subjectLocatorField, gridBagConstraints); subjectIdentifierLabel.setForeground(new java.awt.Color(51, 51, 51)); subjectIdentifierLabel.setText("Subject identifiers"); subjectIdentifierLabel.setComponentPopupMenu(getSIMenu()); subjectLocatorLabel.addMouseListener(wandora); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 0); idPanel.add(subjectIdentifierLabel, gridBagConstraints); subjectIdentifierRootPanel.setName("subjectIdentifierRootPanel"); // NOI18N subjectIdentifierRootPanel.setLayout(new java.awt.BorderLayout()); subjectIdentifierPanel.setLayout(new java.awt.GridLayout(1, 0)); subjectIdentifierRootPanel.add(subjectIdentifierPanel, java.awt.BorderLayout.NORTH); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 1); idPanel.add(subjectIdentifierRootPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(7, 10, 7, 10); containerPanel.add(idPanel, gridBagConstraints); variantRootPanel.setComponentPopupMenu(getNamesMenu()); variantRootPanel.setName("variantRootPanel"); // NOI18N variantRootPanel.addMouseListener(wandora); variantRootPanel.setLayout(new java.awt.BorderLayout()); variantWrapperPanel.setLayout(new java.awt.GridBagLayout()); variantTitlePanel.setLayout(new java.awt.GridBagLayout()); variantTitle.setFont(UIConstants.h2Font); variantTitle.setText("Variant names"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; variantTitlePanel.add(variantTitle, gridBagConstraints); variantNumber.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N variantNumber.setText("0"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); variantTitlePanel.add(variantNumber, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; variantTitlePanel.add(variantTitleFiller, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(20, 0, 10, 0); variantWrapperPanel.add(variantTitlePanel, gridBagConstraints); variantPanelMargin.setPreferredSize(new java.awt.Dimension(30, 10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; variantWrapperPanel.add(variantPanelMargin, gridBagConstraints); variantPanel.setLayout(new java.awt.GridLayout(1, 0)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; variantWrapperPanel.add(variantPanel, gridBagConstraints); variantRootPanel.add(variantWrapperPanel, java.awt.BorderLayout.PAGE_END); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10); containerPanel.add(variantRootPanel, gridBagConstraints); occurrencesRootPanel.setComponentPopupMenu(getOccurrencesMenu()); occurrencesRootPanel.setName("occurrencesRootPanel"); // NOI18N occurrencesRootPanel.addMouseListener(wandora); occurrencesRootPanel.setLayout(new java.awt.BorderLayout()); occurrencesWrapperPanel.setLayout(new java.awt.GridBagLayout()); dataTitlePanel.setLayout(new java.awt.GridBagLayout()); dataTitle.setFont(UIConstants.h2Font); dataTitle.setText("Occurrences"); dataTitlePanel.add(dataTitle, new java.awt.GridBagConstraints()); dataNumber.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N dataNumber.setText("0"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4); dataTitlePanel.add(dataNumber, gridBagConstraints); dataTitleFiller.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; dataTitlePanel.add(dataTitleFiller, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(20, 0, 10, 0); occurrencesWrapperPanel.add(dataTitlePanel, gridBagConstraints); dataPanelMargin.setPreferredSize(new java.awt.Dimension(30, 10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; occurrencesWrapperPanel.add(dataPanelMargin, gridBagConstraints); dataPanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; occurrencesWrapperPanel.add(dataPanel, gridBagConstraints); occurrencesRootPanel.add(occurrencesWrapperPanel, java.awt.BorderLayout.PAGE_END); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10); containerPanel.add(occurrencesRootPanel, gridBagConstraints); classesRootPanel.setComponentPopupMenu(getClassesMenu()); classesRootPanel.setName("classesRootPanel"); // NOI18N classesRootPanel.addMouseListener(wandora); classesRootPanel.setLayout(new java.awt.BorderLayout()); classesWrapperPanel.setLayout(new java.awt.GridBagLayout()); classesTitlePanel.setLayout(new java.awt.GridBagLayout()); classesTitle.setFont(UIConstants.h2Font); classesTitle.setText("Classes"); classesTitlePanel.add(classesTitle, new java.awt.GridBagConstraints()); classesNumber.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N classesNumber.setText("0"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); classesTitlePanel.add(classesNumber, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; classesTitlePanel.add(classesTitleFiller, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(20, 0, 10, 0); classesWrapperPanel.add(classesTitlePanel, gridBagConstraints); classesPanelMargin.setPreferredSize(new java.awt.Dimension(30, 10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; classesWrapperPanel.add(classesPanelMargin, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; classesWrapperPanel.add(classesPanel, gridBagConstraints); classesRootPanel.add(classesWrapperPanel, java.awt.BorderLayout.PAGE_END); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10); containerPanel.add(classesRootPanel, gridBagConstraints); associationRootPanel.setComponentPopupMenu(getAssociationsMenu()); associationRootPanel.setName("associationRootPanel"); // NOI18N associationRootPanel.addMouseListener(wandora); associationRootPanel.setLayout(new java.awt.BorderLayout()); associationWrapperPanel.setLayout(new java.awt.GridBagLayout()); associationsTitlePanel.setLayout(new java.awt.GridBagLayout()); associationsTitle.setFont(UIConstants.h2Font); associationsTitle.setText("Associations"); associationsTitlePanel.add(associationsTitle, new java.awt.GridBagConstraints()); associationsNumber.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N associationsNumber.setText("0"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); associationsTitlePanel.add(associationsNumber, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; associationsTitlePanel.add(associationsTitleFiller, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(20, 0, 10, 0); associationWrapperPanel.add(associationsTitlePanel, gridBagConstraints); associationPanelMargin.setPreferredSize(new java.awt.Dimension(30, 10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; associationWrapperPanel.add(associationPanelMargin, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; associationWrapperPanel.add(associationPanel, gridBagConstraints); associationRootPanel.add(associationWrapperPanel, java.awt.BorderLayout.PAGE_END); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10); containerPanel.add(associationRootPanel, gridBagConstraints); typedAssociationsRootPanel.setName("typedAssociationsRootPanel"); // NOI18N typedAssociationsRootPanel.setLayout(new java.awt.BorderLayout()); typedAssociationsWrapperPanel.setLayout(new java.awt.GridBagLayout()); typedAssociationsTitlePanel.setLayout(new java.awt.GridBagLayout()); typedAssociationTitle.setFont(UIConstants.h2Font); typedAssociationTitle.setText("Associations where type"); typedAssociationsTitlePanel.add(typedAssociationTitle, new java.awt.GridBagConstraints()); typedAssociationNumber.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N typedAssociationNumber.setText("0"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); typedAssociationsTitlePanel.add(typedAssociationNumber, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; typedAssociationsTitlePanel.add(typedAssociationTitleFiller, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(20, 0, 10, 0); typedAssociationsWrapperPanel.add(typedAssociationsTitlePanel, gridBagConstraints); typesAssociationPanelMargin.setPreferredSize(new java.awt.Dimension(30, 10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; typedAssociationsWrapperPanel.add(typesAssociationPanelMargin, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; typedAssociationsWrapperPanel.add(typedAssociationsPanel, gridBagConstraints); typedAssociationsRootPanel.add(typedAssociationsWrapperPanel, java.awt.BorderLayout.PAGE_END); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10); containerPanel.add(typedAssociationsRootPanel, gridBagConstraints); instancesRootPanel.setComponentPopupMenu(getInstancesMenu()); instancesRootPanel.setName("instancesRootPanel"); // NOI18N instancesRootPanel.addMouseListener(wandora); instancesRootPanel.setLayout(new java.awt.BorderLayout()); instancesWrapperPanel.setLayout(new java.awt.GridBagLayout()); instancesTitlePanel.setLayout(new java.awt.GridBagLayout()); instancesTitle.setFont(UIConstants.h2Font); instancesTitle.setText("Instances"); instancesTitlePanel.add(instancesTitle, new java.awt.GridBagConstraints()); instancesNumber.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N instancesNumber.setText("0"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); instancesTitlePanel.add(instancesNumber, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; instancesTitlePanel.add(instancesTitleFiller, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(20, 0, 10, 0); instancesWrapperPanel.add(instancesTitlePanel, gridBagConstraints); instancesPanelMargin.setPreferredSize(new java.awt.Dimension(30, 10)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; instancesWrapperPanel.add(instancesPanelMargin, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; instancesWrapperPanel.add(instancesPanel, gridBagConstraints); instancesRootPanel.add(instancesWrapperPanel, java.awt.BorderLayout.PAGE_END); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10); containerPanel.add(instancesRootPanel, gridBagConstraints); fillerPanel.setPreferredSize(new java.awt.Dimension(10, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; containerPanel.add(fillerPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(containerPanel, gridBagConstraints); removedTopicMessage.setBackground(new java.awt.Color(255, 255, 255)); removedTopicMessage.setLayout(new java.awt.GridBagLayout()); removedTopicMessageLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); removedTopicMessageLabel.setText("<html><p align=\"center\">No topic to view.<br>Maybe the topic has been merged or removed.<br>Please, open another topic.</p><html>"); removedTopicMessage.add(removedTopicMessageLabel, new java.awt.GridBagConstraints()); buttonWrapperPanel.setBackground(new java.awt.Color(255, 255, 255)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); removedTopicMessage.add(buttonWrapperPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(removedTopicMessage, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void baseNameFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_baseNameFieldKeyReleased try { if(evt.getKeyCode()==KeyEvent.VK_ENTER) { System.out.println("Applying changes called at keyReleased"); applyChanges(); } } catch(Exception e) {} }//GEN-LAST:event_baseNameFieldKeyReleased private void subjectLocatorFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_subjectLocatorFieldKeyReleased try { if(evt.getKeyCode()==KeyEvent.VK_ENTER) { applyChanges(); } } catch(Exception e) {} }//GEN-LAST:event_subjectLocatorFieldKeyReleased private void subjectLocatorFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_subjectLocatorFieldFocusLost SwingUtilities.invokeLater(new Runnable() { public void run() { try { applyChanges(); } catch(Exception e) {} } }); }//GEN-LAST:event_subjectLocatorFieldFocusLost private void baseNameFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_baseNameFieldFocusLost SwingUtilities.invokeLater(new Runnable() { public void run() { try { applyChanges(); } catch(Exception e) {} } }); }//GEN-LAST:event_baseNameFieldFocusLost private void subjectLocatorViewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_subjectLocatorViewButtonActionPerformed toggleVisibility("View subject locators"); }//GEN-LAST:event_subjectLocatorViewButtonActionPerformed @Override public int print(java.awt.Graphics graphics, java.awt.print.PageFormat pageFormat, int param) throws java.awt.print.PrinterException { if (param > 0) { return(NO_SUCH_PAGE); } else { Graphics2D g2d = (Graphics2D)graphics; g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); // Turn off double buffering this.paint(g2d); // Turn double buffering back on return(PAGE_EXISTS); } } // ------------------------------------------------------------------------- @Override public JPopupMenu getNamesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getVariantsLabelPopupStruct(options), wandora); } @Override public JPopupMenu getClassesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getClassesTablePopupStruct(), wandora); } @Override public JPopupMenu getInstancesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getInstancesTablePopupStruct(), wandora); } @Override public JPopupMenu getSIMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getSubjectIdentifierLabelPopupStruct(), wandora); } @Override public JPopupMenu getOccurrencesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getOccurrencesLabelPopupStruct(options), wandora); } @Override public JPopupMenu getOccurrenceTypeMenu(Topic occurrenceType) { return UIBox.makePopupMenu(WandoraMenuManager.getOccurrenceTypeLabelPopupStruct(occurrenceType, topic), wandora); } public JPopupMenu getSLMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getSubjectLocatorLabelPopupStruct(), wandora); } @Override public JPopupMenu getAssociationsMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getAssociationTableLabelPopupStruct(), wandora); } @Override public JPopupMenu getAssociationTypeMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getAssociationTypeLabelPopupStruct(), wandora); } @Override public JPopupMenu getSubjectMenu() { return null; } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); System.out.println("TraditionalTopicPanel catched action command '" + c + "'."); toggleVisibility(c); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel associationPanel; private javax.swing.JPanel associationPanelMargin; private javax.swing.JPanel associationRootPanel; private javax.swing.JPanel associationWrapperPanel; private javax.swing.JLabel associationsNumber; private javax.swing.JLabel associationsTitle; private javax.swing.JPanel associationsTitleFiller; private javax.swing.JPanel associationsTitlePanel; private javax.swing.JTextField baseNameField; private javax.swing.JLabel baseNameLabel; private javax.swing.JPanel buttonWrapperPanel; private javax.swing.JLabel classesNumber; private javax.swing.JPanel classesPanel; private javax.swing.JPanel classesPanelMargin; private javax.swing.JPanel classesRootPanel; private javax.swing.JLabel classesTitle; private javax.swing.JPanel classesTitleFiller; private javax.swing.JPanel classesTitlePanel; private javax.swing.JPanel classesWrapperPanel; private javax.swing.JPanel containerPanel; private javax.swing.JLabel dataNumber; private javax.swing.JPanel dataPanel; private javax.swing.JPanel dataPanelMargin; private javax.swing.JLabel dataTitle; private javax.swing.JPanel dataTitleFiller; private javax.swing.JPanel dataTitlePanel; private javax.swing.JPanel fillerPanel; private javax.swing.JPanel idPanel; private javax.swing.JLabel instancesNumber; private javax.swing.JPanel instancesPanel; private javax.swing.JPanel instancesPanelMargin; private javax.swing.JPanel instancesRootPanel; private javax.swing.JLabel instancesTitle; private javax.swing.JPanel instancesTitleFiller; private javax.swing.JPanel instancesTitlePanel; private javax.swing.JPanel instancesWrapperPanel; private javax.swing.JPanel occurrencesRootPanel; private javax.swing.JPanel occurrencesWrapperPanel; private javax.swing.JPanel previewContainerPanel; private javax.swing.JPanel previewPanel; private javax.swing.JPanel removedTopicMessage; private javax.swing.JLabel removedTopicMessageLabel; private javax.swing.JLabel subjectIdentifierLabel; private javax.swing.JPanel subjectIdentifierPanel; private javax.swing.JPanel subjectIdentifierRootPanel; private javax.swing.JTextField subjectLocatorField; private javax.swing.JLabel subjectLocatorLabel; private javax.swing.JToggleButton subjectLocatorViewButton; private javax.swing.JLabel typedAssociationNumber; private javax.swing.JLabel typedAssociationTitle; private javax.swing.JPanel typedAssociationTitleFiller; private javax.swing.JPanel typedAssociationsPanel; private javax.swing.JPanel typedAssociationsRootPanel; private javax.swing.JPanel typedAssociationsTitlePanel; private javax.swing.JPanel typedAssociationsWrapperPanel; private javax.swing.JPanel typesAssociationPanelMargin; private javax.swing.JLabel variantNumber; private javax.swing.JPanel variantPanel; private javax.swing.JPanel variantPanelMargin; private javax.swing.JPanel variantRootPanel; private javax.swing.JLabel variantTitle; private javax.swing.JPanel variantTitleFiller; private javax.swing.JPanel variantTitlePanel; private javax.swing.JPanel variantWrapperPanel; // End of variables declaration//GEN-END:variables }
58,010
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DropExtractor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/DropExtractor.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.topicpanels; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collection; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.gui.DropExtractPanel; import org.wandora.application.gui.UIBox; import org.wandora.exceptions.OpenTopicNotSupportedException; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class DropExtractor extends javax.swing.JPanel implements TopicPanel, ActionListener { private static final long serialVersionUID = 1L; private DropExtractPanel dropExtractPanel = null; /** * Creates new form DropExtractor */ public DropExtractor() { } @Override public void init() { initComponents(); dropExtractPanel = new DropExtractPanel(); dropExtractPanelContainer.add(dropExtractPanel); } @Override public boolean supportsOpenTopic() { return false; } @Override public void open(Topic topic) throws TopicMapException, OpenTopicNotSupportedException { } @Override public void stop() { } @Override public void refresh() throws TopicMapException { if(dropExtractPanel != null) { dropExtractPanel.updateMenu(); } } @Override public boolean applyChanges() throws CancelledException, TopicMapException { return true; } @Override public JPanel getGui() { return this; } @Override public Topic getTopic() throws TopicMapException { return null; } @Override public String getName(){ return "Drop extractor"; } @Override public String getTitle() { return "Drop extractor"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_panel_drop_extractor.png"); } @Override public boolean noScroll(){ return false; } @Override public int getOrder() { return 9997; } @Override public Object[] getViewMenuStruct() { return new Object[] { }; } @Override public JMenu getViewMenu() { return UIBox.makeMenu(getViewMenuStruct(), this); } @Override public JPopupMenu getViewPopupMenu() { return UIBox.makePopupMenu(getViewMenuStruct(), this); } @Override public LocatorHistory getTopicHistory() { return null; } @Override public void actionPerformed(ActionEvent e) { } // ---------------------------------------------------- TopicMapListener --- // Topic map changes doesn't affect DropExtractor any way. @Override public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { } @Override public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { } @Override public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { } @Override public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { } @Override public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { } @Override public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { } @Override public void topicRemoved(Topic t) throws TopicMapException { } @Override public void topicChanged(Topic t) throws TopicMapException { } @Override public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { } @Override public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { } @Override public void associationRemoved(Association a) throws TopicMapException { } @Override public void associationChanged(Association a) throws TopicMapException { } // ------------------------------------------------------------------------- /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; dropExtractPanelContainer = new javax.swing.JPanel(); setBackground(new java.awt.Color(255, 255, 255)); setLayout(new java.awt.GridBagLayout()); dropExtractPanelContainer.setBackground(new java.awt.Color(255, 255, 255)); dropExtractPanelContainer.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(dropExtractPanelContainer, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel dropExtractPanelContainer; // End of variables declaration//GEN-END:variables }
6,764
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryEditorTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/QueryEditorTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.topicpanels; /** * This is just a stub to get this registered in TopicPanelManager. The actual * code is in the queryeditorpanel package in a class of the same name, which * this class extends (without adding anything whatsoever). * @author olli */ public class QueryEditorTopicPanel /* extends org.wandora.application.gui.topicpanels.queryeditorpanel.QueryEditorTopicPanel */ { }
1,230
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TabbedTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/TabbedTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TabbedTopicPanel.java * * Created on August 9, 2004, 2:33 PM */ package org.wandora.application.gui.topicpanels; import java.awt.Color; import java.awt.Component; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.util.ArrayList; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.Wandora; import org.wandora.application.WandoraMenuManager; import org.wandora.application.contexts.ApplicationContext; import org.wandora.application.gui.ConfirmResult; import org.wandora.application.gui.NewTopicPanelExtended; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.previews.PreviewWrapper; import org.wandora.application.gui.topicpanels.traditional.AbstractTraditionalTopicPanel; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.navigate.OpenTopic; import org.wandora.application.tools.subjects.AddSubjectIdentifier; import org.wandora.application.tools.subjects.CheckSubjectLocator; import org.wandora.application.tools.subjects.CopySubjectIdentifiers; import org.wandora.application.tools.subjects.DeleteSubjectLocator; import org.wandora.application.tools.subjects.DownloadSubjectLocators; import org.wandora.application.tools.subjects.FlattenSubjectIdentifiers; import org.wandora.application.tools.subjects.PasteSubjectIdentifiers; import org.wandora.application.tools.topicnames.AddVariantName; import org.wandora.application.tools.topicnames.AllEmptyVariantRemover; import org.wandora.application.tools.topicnames.TopicNameCopier; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * * @author olli, ak */ public class TabbedTopicPanel extends AbstractTraditionalTopicPanel implements ActionListener, ChangeListener, TopicPanel, ComponentListener { private static final long serialVersionUID = 1L; public static final boolean MAKE_LOCAL_SETTINGS_GLOBAL = false; public Topic topic; public String topicSI; private Wandora wandora; private Options options; private String originalBN; private String originalSL; // tabComponentName, tabName, menuName private Object[][] tabStruct; private JComponent buttonContainer = null; /** Creates new TabbedTopicPanel */ public TabbedTopicPanel(Topic topic, Wandora wandora) { open(topic); } public TabbedTopicPanel() {} @Override public void init() { this.wandora = Wandora.getWandora(); if(this.options == null) { // Notice, a copy of global options is created for local use. // Thus, local adjustments have no global effect. this.options = new Options(wandora.getOptions()); } Object[] buttonStruct = { "Open topic", new OpenTopic(OpenTopic.ASK_USER), "New topic", UIBox.getIcon("gui/icons/new_topic.png"), new ActionListener() { @Override public void actionPerformed(ActionEvent e) { NewTopicPanelExtended newTopicPanel = new NewTopicPanelExtended(null); // TODO: Should pass a context to the constructor. if(newTopicPanel.getAccepted()) { try { Topic newTopic = newTopicPanel.createTopic(); if(newTopic != null) { Wandora.getWandora().openTopic(newTopic); } } catch(Exception ex) { ex.printStackTrace(); } } } }, }; buttonContainer = UIBox.makeButtonContainer(buttonStruct, Wandora.getWandora()); } @Override public void open(Topic topic) { if(previewPanel != null) { ((PreviewWrapper) previewPanel).stop(); } this.removeAll(); initComponents(); buttonWrapperPanel.add(buttonContainer); tabStruct = new Object[][] { { subjectScrollPanel, "Subject", "View subject tab", "subjectScrollPanel" }, { variantScrollPanel, "Names", "View names tab", "variantScrollPanel" }, { dataScrollPanel, "Occurrences", "View occurrences tab", "dataScrollPanel" }, { classesScrollPanel, "Classes", "View classes tab", "classesScrollPanel" }, { instancesScrollPanel, "Instances", "View instances tab", "instancesScrollPanel" }, { associationScrollPanel, "Associations", "View associations tab", "associationScrollPanel" }, }; associationPanelContainer.setTransferHandler(new AssociationTableTransferHandler(this)); instancesPanelContainer.setTransferHandler(new InstancesPanelTransferHandler(this)); classesPanelContainer.setTransferHandler(new ClassesPanelTransferHandler(this)); this.setTransferHandler(new TopicPanelTransferHandler(this)); this.addComponentListener(this); topicTabbedPane.addChangeListener(this); this.topic = topic; try { if(topic != null && !topic.isRemoved()) { this.topicSI = topic.getOneSubjectIdentifier().toExternalForm(); } } catch(Exception e) { e.printStackTrace(); } refresh(); selectCurrentTab(); } public void selectCurrentTab() { if(options == null) return; String currentTabPanelName = options.get(OPTIONS_PREFIX + "currentTab"); if(currentTabPanelName != null) { try { boolean found = false; for(int i=0; i<topicTabbedPane.getComponentCount(); i++) { Component tabComponent = topicTabbedPane.getComponent(i); if(tabComponent != null) { if(tabComponent.getName() != null) { if(tabComponent.getName().equals(currentTabPanelName)) { topicTabbedPane.setSelectedComponent(tabComponent); found = true; break; } } } } if(!found) { Component component = topicTabbedPane.getSelectedComponent(); if(component != null) options.put(OPTIONS_PREFIX + "currentTab", component.getName()); } } catch(Exception e) { e.printStackTrace(); } } } @Override public void stateChanged(ChangeEvent e) { // System.out.println("TopicTabbedPane state changed!"); if(e.getSource().equals(topicTabbedPane) && options != null) { Component component = topicTabbedPane.getSelectedComponent(); if(component != null) { for(int i=0; i<tabStruct.length; i++) { if(((JPanel) tabStruct[i][0]).equals(component)) { options.put(OPTIONS_PREFIX + "currentTab", component.getName()); if(MAKE_LOCAL_SETTINGS_GLOBAL) { Options globalOptions = wandora.getOptions(); if(globalOptions != null) { globalOptions.put(OPTIONS_PREFIX + "currentTab", component.getName()); } } } } } } } @Override public String getName() { return "Tabbed"; } @Override public String getTitle() { if(topic != null) return TopicToString.toString(topic); else return ""; } @Override public int getOrder() { return 10; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_panel_tabbed.png"); } @Override public boolean noScroll(){ return false; } @Override public Topic getTopic() { try { if(topic == null || topic.isRemoved()) { topic = wandora.getTopicMap().getTopic(topicSI); } return topic; } catch(Exception e) { e.printStackTrace(); return null; } } @Override public LocatorHistory getTopicHistory() { return null; } @Override public JPanel getGui() { return this; } // ------------------------------------------------------------------------- // ----------------------------------------------------------- VIEW MENU --- // ------------------------------------------------------------------------- @Override public JPopupMenu getViewPopupMenu() { return UIBox.makePopupMenu(getViewMenuStruct(), this); } @Override public JMenu getViewMenu() { return UIBox.makeMenu(getViewMenuStruct(), this); } @Override public Object[] getViewMenuStruct() { Icon viewIcon = UIBox.getIcon("gui/icons/view2.png"); Icon hideIcon = UIBox.getIcon("gui/icons/view2_no.png"); ArrayList menuVector = new ArrayList(); for(int i=0; i<tabStruct.length; i++) { Object[] tabData = tabStruct[i]; String tabPanelName = ((JPanel) tabData[0]).getName(); menuVector.add( tabData[2] ); menuVector.add( options.isFalse(OPTIONS_VIEW_PREFIX + tabPanelName) ? hideIcon : viewIcon ); menuVector.add( this ); } menuVector.add( "---" ); menuVector.add( "View all" ); menuVector.add( this ); return menuVector.toArray(); } // ------------------------------------------------------------------------- // --------------------------------------------------- TOGGLE VISIBILITY --- // ------------------------------------------------------------------------- @Override public void toggleVisibility(String componentName) { boolean iDidIt = false; try { applyChanges(); } catch(Exception e) { return; } if("View All".equalsIgnoreCase(componentName)) { JPanel panel; for(int i=0; i<tabStruct.length; i++) { panel = (JPanel) tabStruct[i][0]; setVisibitilityOption(tabStruct[i][3].toString(), true); panel.setVisible(true); } setVisibitilityOption("subjectLocatorIcons", true); refreshTabs(); iDidIt = true; } if("Hide All".equalsIgnoreCase(componentName)) { JPanel panel; for(int i=0; i<tabStruct.length; i++) { panel = (JPanel) tabStruct[i][0]; setVisibitilityOption(tabStruct[i][3].toString(), false); panel.setVisible(false); } setVisibitilityOption("subjectLocatorIcons", false); refreshTabs(); iDidIt = true; } else { int panelIndex = solvePanelIndex(componentName); if(panelIndex >= 0) { String optionName = tabStruct[panelIndex][3].toString(); if(optionName != null) { boolean currentValue = options.isFalse(OPTIONS_VIEW_PREFIX + optionName); setVisibitilityOption(optionName, currentValue); topicTabbedPane.removeAll(); refreshTabs(); iDidIt = true; } } } if(iDidIt) { wandora.topicPanelsChanged(); } } private int solvePanelIndex(String componentName) { if(componentName == null) return -1; for(int i=0; i<tabStruct.length; i++) { if(componentName.equals(tabStruct[i][2])) return i; } return -1; } private void setVisibitilityOption(String key, boolean value) { options.put(OPTIONS_VIEW_PREFIX + key, value ? "true" : "false"); if(MAKE_LOCAL_SETTINGS_GLOBAL) { Options globalOptions = wandora.getOptions(); if(globalOptions != null) { globalOptions.put(OPTIONS_VIEW_PREFIX + key, value ? "true" : "false"); } } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public void updatePreview() { try { boolean viewPreview = options.getBoolean(OPTIONS_VIEW_PREFIX+"subjectPanelContainer", false); if(viewPreview) { if(topic.getSubjectLocator() != null) { ((PreviewWrapper) previewPanel).setURL(topic.getSubjectLocator()); } else { ((PreviewWrapper) previewPanel).setURL(null); } } } catch(Exception e) {} } // ------------------------------------------------------------------------- @Override public void refresh() { try { if(topicSI != null) { topic = wandora.getTopicMap().getTopic(topicSI); } if(topic==null || topic.isRemoved()) { System.out.println("Topic is null or removed!"); topicTabbedPane.setVisible(false); removedTopicMessage.setVisible(true); return; } else { topicTabbedPane.setVisible(true); removedTopicMessage.setVisible(false); } } catch(Exception e){ e.printStackTrace(); System.out.println("Topic is null or removed!"); topicTabbedPane.setVisible(false); removedTopicMessage.setVisible(true); return; } super.refresh(); try { updatePreview(); /* if(topic.getBaseName()!=null) baseNameField.setText(topic.getBaseName()); else baseNameField.setText(""); if(topic.getSubjectLocator()!=null) subjectLocatorField.setText(topic.getSubjectLocator().toString()); else subjectLocatorField.setText("");*/ if(topic.getBaseName()!=null) { baseNameField.setText(topic.getBaseName()); baseNameField.setCaretPosition(0); Color c=wandora.topicHilights.getBaseNameColor(topic); if(c!=null) baseNameField.setForeground(c); else baseNameField.setForeground(Color.BLACK); } else { baseNameField.setText(""); baseNameField.setForeground(Color.BLACK); } originalBN=topic.getBaseName(); if(topic.getSubjectLocator()!=null) { subjectLocatorField.setText(topic.getSubjectLocator().toString()); subjectLocatorField.setCaretPosition(0); Color c=wandora.topicHilights.getSubjectLocatorColor(topic); if(c!=null) subjectLocatorField.setForeground(c); else subjectLocatorField.setForeground(Color.BLACK); originalSL=topic.getSubjectLocator().toString(); } else { subjectLocatorField.setText(""); subjectLocatorField.setForeground(Color.BLACK); originalSL=null; } } catch(Exception e) { System.out.println("Failed to initialize base or/and sl!"); e.printStackTrace(); } buildAssociationsPanel(associationPanel, null, topic, options, wandora); buildClassesPanel(classesPanel, null, topic, options, wandora); buildSubjectIdentifierPanel(subjectIdentifierPanel, topic, options, wandora); buildInstancesPanel(instancesPanel, null, topic, options, wandora); buildAllNamesPanel(variantPanel, null, topic, this, options, wandora); buildOccurrencesPanel(dataPanel, null, topic, options, wandora); refreshTabs(); this.setComponentPopupMenu(this.getViewPopupMenu()); } public void refreshTabs() { String currentTab = options.get(OPTIONS_PREFIX + "currentTab"); topicTabbedPane.removeAll(); for(int i=0; i<tabStruct.length; i++) { JPanel tabPanel = (JPanel) tabStruct[i][0]; if(! options.isFalse(OPTIONS_VIEW_PREFIX + tabPanel.getName())) { topicTabbedPane.addTab((String) tabStruct[i][1], tabPanel); } tabPanel.addMouseListener(this); } if(currentTab != null) { options.put(OPTIONS_PREFIX + "currentTab", currentTab); if(MAKE_LOCAL_SETTINGS_GLOBAL) { Options globalOptions = wandora.getOptions(); if(globalOptions != null) { globalOptions.put(OPTIONS_PREFIX + "currentTab", currentTab); } } } selectCurrentTab(); } @Override public boolean applyChanges() throws CancelledException,TopicMapException { boolean changed=false; String fieldTextSL = subjectLocatorField.getText().trim(); // String origSL=null; // if(topic.getSubjectLocator()!=null) origSL=topic.getSubjectLocator().toString(); String origSL=originalSL; // ------- basenames ------- String baseNameFieldText = baseNameField.getText().trim(); // String origBN=topic.getBaseName(); String origBN=originalBN; if((origBN==null && baseNameFieldText.length()>0) || (origBN!=null && !origBN.equals(baseNameFieldText))){ if(TMBox.checkBaseNameChange(wandora,topic,baseNameFieldText)!=ConfirmResult.yes) { baseNameField.setText(origBN); throw new CancelledException(); } if(baseNameFieldText.length()>0) topic.setBaseName(baseNameFieldText); else topic.setBaseName(null); changed=true; } // ------ subject locator ------- if((origSL==null && fieldTextSL.length()>0) || (origSL!=null && !origSL.equals(fieldTextSL))){ if(TMBox.checkSubjectLocatorChange(wandora,topic,fieldTextSL)!=ConfirmResult.yes) { subjectLocatorField.setText(originalSL); throw new CancelledException(); } if(origSL!=null && !origSL.equals(fieldTextSL)){ topic.setSubjectLocator(null); } if(fieldTextSL.length()>0) topic.setSubjectLocator(topic.getTopicMap().createLocator(fieldTextSL)); changed=true; } // ------ everything else ------- changed = changed | super.applyChanges(topic, wandora); if(changed) wandora.doRefresh(); return changed; } @Override public void stop() { if(previewPanel != null && previewPanel instanceof PreviewWrapper) { ((PreviewWrapper) previewPanel).stop(); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; subjectScrollPanel = new javax.swing.JPanel(); subjectPanelContainer = new javax.swing.JPanel(); subjectLocatorLabel = new org.wandora.application.gui.simple.SimpleLabel(); subjectLocatorField = new org.wandora.application.gui.simple.SimpleURIField(); subjectIdentifierLabel = new org.wandora.application.gui.simple.SimpleLabel(); subjectIdentifierRootPanel = new org.wandora.application.gui.simple.SimplePanel(); subjectIdentifierPanel = new javax.swing.JPanel(); previewPanelContainer = new javax.swing.JPanel(); previewPanel = PreviewWrapper.getPreviewWrapper(this); variantScrollPanel = new javax.swing.JPanel(); variantPanelContainer = new javax.swing.JPanel(); basenamePanel = new javax.swing.JPanel(); basenameLabel = new org.wandora.application.gui.simple.SimpleLabel(); baseNameField = new org.wandora.application.gui.simple.SimpleField(); jSeparator1 = new javax.swing.JSeparator(); jLabel1 = new javax.swing.JLabel(); variantPanel = new org.wandora.application.gui.simple.SimplePanel(); jPanel3 = new javax.swing.JPanel(); dataScrollPanel = new javax.swing.JPanel(); dataPanelContainer = new javax.swing.JPanel(); dataRootPanel = new org.wandora.application.gui.simple.SimplePanel(); jPanel5 = new javax.swing.JPanel(); dataPanel = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); associationScrollPanel = new javax.swing.JPanel(); associationPanelContainer = new javax.swing.JPanel(); associationRootPanel = new org.wandora.application.gui.simple.SimplePanel(); associationPanel = new javax.swing.JPanel(); jPanel6 = new javax.swing.JPanel(); classesScrollPanel = new javax.swing.JPanel(); classesPanelContainer = new javax.swing.JPanel(); classesRootPanel = new org.wandora.application.gui.simple.SimplePanel(); jPanel4 = new javax.swing.JPanel(); classesPanel = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); instancesScrollPanel = new javax.swing.JPanel(); instancesPanelContainer = new javax.swing.JPanel(); instancesPanel = new org.wandora.application.gui.simple.SimplePanel(); jPanel8 = new javax.swing.JPanel(); topicTabbedPane = new org.wandora.application.gui.simple.SimpleTabbedPane(); removedTopicMessage = new javax.swing.JPanel(); removedTopicMessageLabel = new javax.swing.JLabel(); buttonWrapperPanel = new javax.swing.JPanel(); subjectScrollPanel.setComponentPopupMenu(getSubjectMenu()); subjectScrollPanel.setName("subjectScrollPanel"); // NOI18N subjectScrollPanel.setLayout(new java.awt.BorderLayout()); subjectPanelContainer.setComponentPopupMenu(getSubjectMenu()); subjectPanelContainer.setName("subjectPanelContainer"); // NOI18N subjectPanelContainer.setLayout(new java.awt.GridBagLayout()); subjectLocatorLabel.setText("Subject locator"); subjectLocatorLabel.setComponentPopupMenu(getSLMenu()); subjectLocatorLabel.addMouseListener(wandora); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0); subjectPanelContainer.add(subjectLocatorLabel, gridBagConstraints); subjectLocatorField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { subjectLocatorFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 10); subjectPanelContainer.add(subjectLocatorField, gridBagConstraints); subjectIdentifierLabel.setText("Subject identifiers"); subjectIdentifierLabel.setComponentPopupMenu(getSIMenu()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0); subjectPanelContainer.add(subjectIdentifierLabel, gridBagConstraints); subjectIdentifierRootPanel.setComponentPopupMenu(getSIMenu()); subjectIdentifierRootPanel.setName("subjectIdentifierRootPanel"); // NOI18N subjectIdentifierRootPanel.setLayout(new java.awt.BorderLayout()); subjectIdentifierPanel.setLayout(new java.awt.GridLayout(1, 0)); subjectIdentifierRootPanel.add(subjectIdentifierPanel, java.awt.BorderLayout.NORTH); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 10); subjectPanelContainer.add(subjectIdentifierRootPanel, gridBagConstraints); previewPanelContainer.setLayout(new java.awt.GridBagLayout()); previewPanel.setToolTipText(""); previewPanel.setMinimumSize(new java.awt.Dimension(100, 100)); previewPanel.setPreferredSize(new java.awt.Dimension(100, 100)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10); previewPanelContainer.add(previewPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 10, 10); subjectPanelContainer.add(previewPanelContainer, gridBagConstraints); subjectScrollPanel.add(subjectPanelContainer, java.awt.BorderLayout.CENTER); variantScrollPanel.setComponentPopupMenu(getNamesMenu()); variantScrollPanel.setName("variantScrollPanel"); // NOI18N variantScrollPanel.setLayout(new java.awt.BorderLayout()); variantPanelContainer.setComponentPopupMenu(getNamesMenu()); variantPanelContainer.setName("variantPanelContainer"); // NOI18N variantPanelContainer.setLayout(new java.awt.GridBagLayout()); basenamePanel.setLayout(new java.awt.GridBagLayout()); basenameLabel.setText("Base name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0); basenamePanel.add(basenameLabel, gridBagConstraints); baseNameField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { baseNameFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 20); basenamePanel.add(baseNameField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10); variantPanelContainer.add(basenamePanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 0); variantPanelContainer.add(jSeparator1, gridBagConstraints); jLabel1.setText("Variant names"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0); variantPanelContainer.add(jLabel1, gridBagConstraints); variantPanel.setMinimumSize(new java.awt.Dimension(20, 20)); variantPanel.setName("variantPanel"); // NOI18N variantPanel.setLayout(new java.awt.GridLayout(1, 0, 0, 5)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 0, 10, 0); variantPanelContainer.add(variantPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.ipadx = 1; gridBagConstraints.ipady = 1; gridBagConstraints.weighty = 1.0; variantPanelContainer.add(jPanel3, gridBagConstraints); variantScrollPanel.add(variantPanelContainer, java.awt.BorderLayout.CENTER); dataScrollPanel.setComponentPopupMenu(getOccurrencesMenu()); dataScrollPanel.setName("dataScrollPanel"); // NOI18N dataScrollPanel.setLayout(new java.awt.BorderLayout()); dataPanelContainer.setComponentPopupMenu(getOccurrencesMenu()); dataPanelContainer.setName("dataPanelContainer"); // NOI18N dataPanelContainer.setLayout(new java.awt.GridBagLayout()); dataRootPanel.setComponentPopupMenu(getOccurrencesMenu()); dataRootPanel.setName("dataRootPanel"); // NOI18N dataRootPanel.addMouseListener(wandora); dataRootPanel.setLayout(new java.awt.BorderLayout(5, 3)); jPanel5.setLayout(new java.awt.BorderLayout()); jPanel5.add(dataPanel, java.awt.BorderLayout.CENTER); dataRootPanel.add(jPanel5, java.awt.BorderLayout.NORTH); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); dataPanelContainer.add(dataRootPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; dataPanelContainer.add(jPanel7, gridBagConstraints); dataScrollPanel.add(dataPanelContainer, java.awt.BorderLayout.PAGE_START); associationScrollPanel.setComponentPopupMenu(getAssociationsMenu()); associationScrollPanel.setName("associationScrollPanel"); // NOI18N associationScrollPanel.setLayout(new java.awt.BorderLayout()); associationPanelContainer.setComponentPopupMenu(getAssociationsMenu()); associationPanelContainer.setName("associationPanelContainer"); // NOI18N associationPanelContainer.setLayout(new java.awt.GridBagLayout()); associationRootPanel.setComponentPopupMenu(getAssociationsMenu()); associationRootPanel.setName("associationRootPanel"); // NOI18N associationRootPanel.addMouseListener(wandora); associationRootPanel.setLayout(new java.awt.BorderLayout(5, 3)); associationRootPanel.add(associationPanel, java.awt.BorderLayout.NORTH); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); associationPanelContainer.add(associationRootPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; associationPanelContainer.add(jPanel6, gridBagConstraints); associationScrollPanel.add(associationPanelContainer, java.awt.BorderLayout.PAGE_START); classesScrollPanel.setComponentPopupMenu(getClassesMenu()); classesScrollPanel.setName("classesScrollPanel"); // NOI18N classesScrollPanel.setLayout(new java.awt.BorderLayout()); classesPanelContainer.setComponentPopupMenu(getClassesMenu()); classesPanelContainer.setName("classesPanelContainer"); // NOI18N classesPanelContainer.setLayout(new java.awt.GridBagLayout()); classesRootPanel.setComponentPopupMenu(getClassesMenu()); classesRootPanel.setName("classesRootPanel"); // NOI18N classesRootPanel.addMouseListener(wandora); classesRootPanel.setLayout(new java.awt.BorderLayout()); jPanel4.setLayout(new java.awt.BorderLayout()); jPanel4.add(classesPanel, java.awt.BorderLayout.CENTER); classesRootPanel.add(jPanel4, java.awt.BorderLayout.NORTH); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); classesPanelContainer.add(classesRootPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; classesPanelContainer.add(jPanel1, gridBagConstraints); classesScrollPanel.add(classesPanelContainer, java.awt.BorderLayout.PAGE_START); instancesScrollPanel.setComponentPopupMenu(getInstancesMenu()); instancesScrollPanel.setName("instancesScrollPanel"); // NOI18N instancesScrollPanel.setLayout(new java.awt.BorderLayout()); instancesPanelContainer.setComponentPopupMenu(getInstancesMenu()); instancesPanelContainer.setName("instancesPanelContainer"); // NOI18N instancesPanelContainer.setLayout(new java.awt.GridBagLayout()); instancesPanel.setComponentPopupMenu(getInstancesMenu()); instancesPanel.setName("instancesPanel"); // NOI18N instancesPanel.addMouseListener(wandora); instancesPanel.setLayout(new java.awt.GridLayout(1, 0)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); instancesPanelContainer.add(instancesPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; instancesPanelContainer.add(jPanel8, gridBagConstraints); instancesScrollPanel.add(instancesPanelContainer, java.awt.BorderLayout.PAGE_START); setLayout(new java.awt.GridBagLayout()); topicTabbedPane.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT); topicTabbedPane.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { mouseClickedOnTab(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(topicTabbedPane, gridBagConstraints); removedTopicMessage.setBackground(new java.awt.Color(255, 255, 255)); removedTopicMessage.setLayout(new java.awt.GridBagLayout()); removedTopicMessageLabel.setText("<html><p align=\"center\">No topic to view.<br>Maybe the topic has been merged or removed.<br>Please, open another topic.</p><html>"); removedTopicMessage.add(removedTopicMessageLabel, new java.awt.GridBagConstraints()); buttonWrapperPanel.setBackground(new java.awt.Color(255, 255, 255)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10); removedTopicMessage.add(buttonWrapperPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(removedTopicMessage, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void baseNameFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_baseNameFieldKeyReleased try { if(evt.getKeyCode()==KeyEvent.VK_ENTER) { applyChanges(); } } catch(Exception e) {} }//GEN-LAST:event_baseNameFieldKeyReleased private void mouseClickedOnTab(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_mouseClickedOnTab if(evt.getButton()==MouseEvent.BUTTON3){ Component tabComponent=topicTabbedPane.getSelectedComponent(); if(tabComponent == null) return; JPopupMenu tabPopupMenu = null; if(tabComponent.equals(this.variantScrollPanel)) { tabPopupMenu = getNamesMenu(); } else if(tabComponent.equals(classesScrollPanel)) { tabPopupMenu = getClassesMenu(); } else if(tabComponent.equals(dataScrollPanel)) { tabPopupMenu = getOccurrencesMenu(); } else if(tabComponent.equals(associationScrollPanel)) { tabPopupMenu = getAssociationsMenu(); } else if(tabComponent.equals(instancesScrollPanel)) { tabPopupMenu = getInstancesMenu(); } else if(tabComponent.equals(subjectScrollPanel)) { tabPopupMenu = getSubjectMenu(); } if(tabPopupMenu != null) { tabPopupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); } } }//GEN-LAST:event_mouseClickedOnTab private void subjectLocatorFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_subjectLocatorFieldKeyReleased try { if(evt.getKeyCode()==KeyEvent.VK_ENTER) { applyChanges(); updatePreview(); } } catch(Exception e) {} }//GEN-LAST:event_subjectLocatorFieldKeyReleased @Override public int print(java.awt.Graphics graphics, java.awt.print.PageFormat pageFormat, int param) throws java.awt.print.PrinterException { if (param > 0) { return(NO_SUCH_PAGE); } else { Graphics2D g2d = (Graphics2D)graphics; g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); // Turn off double buffering this.paint(g2d); // Turn double buffering back on return(PAGE_EXISTS); } } // ------------------------------------------------------------------------- @Override public JPopupMenu getNamesMenu() { Object[] menuStructure = new Object[] { "Add variant name", new AddVariantName(new ApplicationContext()), "---", "Copy all variant names", new TopicNameCopier(new ApplicationContext()), "Remove all empty variant names...", new AllEmptyVariantRemover(new ApplicationContext()), }; return UIBox.makePopupMenu(menuStructure, wandora); } @Override public JPopupMenu getClassesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getClassesTablePopupStruct(), wandora); } public JPopupMenu getSLMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getSubjectLocatorLabelPopupStruct(), wandora); } @Override public JPopupMenu getInstancesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getInstancesTablePopupStruct(), wandora); } @Override public JPopupMenu getSIMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getSubjectIdentifierLabelPopupStruct(), wandora); } @Override public JPopupMenu getOccurrencesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getOccurrencesLabelPopupStruct(options), wandora); } @Override public JPopupMenu getOccurrenceTypeMenu(Topic occurrenceType) { return UIBox.makePopupMenu(WandoraMenuManager.getOccurrenceTypeLabelPopupStruct(occurrenceType, topic), wandora); } @Override public JPopupMenu getSubjectMenu() { Object[] menuStructure = new Object[] { "Check subject locator...", new CheckSubjectLocator(new ApplicationContext()), "Download subject locator...", new DownloadSubjectLocators(new ApplicationContext()), "Remove subject locator...", new DeleteSubjectLocator(new ApplicationContext()), "---", "Add subject identifier...", new AddSubjectIdentifier(new ApplicationContext()), "Copy subject identifiers", new CopySubjectIdentifiers(new ApplicationContext()), "Paste subject identifiers", new PasteSubjectIdentifiers(new ApplicationContext()), "Flatten identity...", new FlattenSubjectIdentifiers(new ApplicationContext()), }; return UIBox.makePopupMenu(menuStructure, wandora); } @Override public JPopupMenu getAssociationsMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getAssociationTableLabelPopupStruct(), wandora); } @Override public JPopupMenu getAssociationTypeMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getAssociationTypeLabelPopupStruct(), wandora); } // ------------------------------------------------------------------------- @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); System.out.println("TabbedTopicPanel catched action command '" + c + "'."); toggleVisibility(c); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel associationPanel; private javax.swing.JPanel associationPanelContainer; private javax.swing.JPanel associationRootPanel; private javax.swing.JPanel associationScrollPanel; private javax.swing.JTextField baseNameField; private javax.swing.JLabel basenameLabel; private javax.swing.JPanel basenamePanel; private javax.swing.JPanel buttonWrapperPanel; private javax.swing.JPanel classesPanel; private javax.swing.JPanel classesPanelContainer; private javax.swing.JPanel classesRootPanel; private javax.swing.JPanel classesScrollPanel; private javax.swing.JPanel dataPanel; private javax.swing.JPanel dataPanelContainer; private javax.swing.JPanel dataRootPanel; private javax.swing.JPanel dataScrollPanel; private javax.swing.JPanel instancesPanel; private javax.swing.JPanel instancesPanelContainer; private javax.swing.JPanel instancesScrollPanel; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JSeparator jSeparator1; private javax.swing.JPanel previewPanel; private javax.swing.JPanel previewPanelContainer; private javax.swing.JPanel removedTopicMessage; private javax.swing.JLabel removedTopicMessageLabel; private javax.swing.JLabel subjectIdentifierLabel; private javax.swing.JPanel subjectIdentifierPanel; private javax.swing.JPanel subjectIdentifierRootPanel; private javax.swing.JTextField subjectLocatorField; private javax.swing.JLabel subjectLocatorLabel; private javax.swing.JPanel subjectPanelContainer; private javax.swing.JPanel subjectScrollPanel; private javax.swing.JTabbedPane topicTabbedPane; private javax.swing.JPanel variantPanel; private javax.swing.JPanel variantPanelContainer; private javax.swing.JPanel variantScrollPanel; // End of variables declaration//GEN-END:variables // ------------------------------------------------------------------------- @Override public void componentShown(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentResized(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentHidden(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentMoved(ComponentEvent e) { handleComponentEvent(e); } private void handleComponentEvent(ComponentEvent e) { revalidate(); repaint(); } // ------------------------------------------------------------------------- }
49,282
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
CustomTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/CustomTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * CustomTopicPanel.java * * Created on 7. tammikuuta 2008, 10:00 */ package org.wandora.application.gui.topicpanels; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.print.PageFormat; import java.awt.print.PrinterException; import java.util.ArrayList; import java.util.List; import javax.script.ScriptEngine; import javax.script.ScriptException; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.TransferHandler; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.Wandora; import org.wandora.application.WandoraMenuManager; import org.wandora.application.WandoraScriptManager; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.previews.PreviewWrapper; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimplePanel; import org.wandora.application.gui.table.MixedTopicTable; import org.wandora.application.gui.topicpanels.custompanel.CustomTopicPanelConfiguration; import org.wandora.application.gui.topicpanels.traditional.AbstractTraditionalTopicPanel; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.query2.Directive; import org.wandora.query2.QueryContext; import org.wandora.query2.QueryException; import org.wandora.query2.ResultRow; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * * @author olli */ public class CustomTopicPanel extends AbstractTraditionalTopicPanel implements ActionListener, TopicPanel { private static final long serialVersionUID = 1L; public static boolean USE_GLOBAL_OPTIONS = true; private boolean viewSubjectLocatorResources = false; protected Topic topic; protected String topicSI; protected Wandora wandora; protected String originalBN; protected String originalSL; protected Options options; protected Options globalOptions; protected SimplePanel customPanel; protected List<QueryGroupInfo> queryGroups; private String OPTIONS_PREFIX = "gui.customTopicPanel."; private String OPTIONS_VIEW_PREFIX = OPTIONS_PREFIX + "view."; /** Creates new form CustomTopicPanel */ public CustomTopicPanel() { } @Override public void init() { } @Override public Topic getTopic() throws TopicMapException { return topic; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_panel_custom.png"); } @Override public String getName() { return "Custom"; } @Override public String getTitle() { if(topic != null) return TopicToString.toString(topic); else return ""; } @Override public int getOrder() { return 20; } @Override public JPanel getGui() { return this; } @Override public boolean applyChanges() throws CancelledException, TopicMapException { return false; } public JMenu getViewMenu(JMenu baseMenu) { UIBox.attachMenu(baseMenu, new Object[] { "---" }, this); UIBox.attachMenu(baseMenu, getViewMenuStruct(), this); return baseMenu; } @Override public JPopupMenu getViewPopupMenu() { return UIBox.makePopupMenu(getViewMenuStruct(), this); } @Override public JMenu getViewMenu() { return UIBox.makeMenu(getViewMenuStruct(), this); } @Override public Object[] getViewMenuStruct() { Icon viewIcon = UIBox.getIcon("gui/icons/view2.png"); Icon hideIcon = UIBox.getIcon("gui/icons/view2_no.png"); Icon configureIcon = UIBox.getIcon("gui/icons/topic_panel_custom_configure.png"); List<Object> menuVector = new ArrayList<>(); for(int i=0;i<queryGroups.size();i++){ QueryGroupInfo groupInfo=queryGroups.get(i); menuVector.add(groupInfo.name); menuVector.add( options.isFalse(getGroupOptionsKey(groupInfo.name)) ? hideIcon : viewIcon ); menuVector.add( this ); } menuVector.add( "---" ); menuVector.add("View subject locator resources"); menuVector.add( viewSubjectLocatorResources ? viewIcon : hideIcon ); menuVector.add( this ); menuVector.add( "---" ); menuVector.add( "Configure..." ); menuVector.add( configureIcon ); menuVector.add( this ); return menuVector.toArray(); } @Override public void open(Topic topic) throws TopicMapException { try { this.topic = topic; this.topicSI = topic.getOneSubjectIdentifier().toExternalForm(); } catch(Exception e) { e.printStackTrace(); } this.wandora = Wandora.getWandora(); if(globalOptions == null) { globalOptions = wandora.getOptions(); } if(options == null) { if(USE_GLOBAL_OPTIONS) { options = globalOptions; } else { options = new Options(globalOptions); } } this.removeAll(); this.setTransferHandler(new TopicPanelTransferHandler()); initComponents(); refresh(); } public String getGroupOptionsKey(String name){ StringBuilder sb=new StringBuilder(name); for(int i=0;i<sb.length();i++){ char c=sb.charAt(i); if( (c>='A' && c<='Z') || (c>='a' && c<='z') || (i>0 && c>='0' && c<='9') || c=='_'){} else { sb.setCharAt(i,'_'); } } return OPTIONS_VIEW_PREFIX+sb.toString(); } @Override public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if(command == null) return; if(command.startsWith("Configure")){ showConfigureDialog(); } else if(command.equals("View subject locator resources")) { viewSubjectLocatorResources = !viewSubjectLocatorResources; refresh(); wandora.topicPanelsChanged(); } else{ boolean found=false; for(QueryGroupInfo queryGroup : queryGroups) { if(queryGroup.name.equals(command)) { found=true; } } if(found){ boolean old=options.isFalse(getGroupOptionsKey(command)); options.put(getGroupOptionsKey(command), old ? "true" : "false"); refresh(); wandora.topicPanelsChanged(); } } } public void parseOptions(){ queryGroups=new ArrayList<QueryGroupInfo>(); for(int i=0;true;i++){ String groupName=options.get(OPTIONS_PREFIX+"group["+i+"].name"); if(groupName==null) break; QueryGroupInfo group=new QueryGroupInfo(); group.name=groupName; for(int j=0;true;j++){ String queryName=options.get(OPTIONS_PREFIX+"group["+i+"].query["+j+"].name"); if(queryName==null) break; String engine=options.get(OPTIONS_PREFIX+"group["+i+"].query["+j+"].engine"); String script=options.get(OPTIONS_PREFIX+"group["+i+"].query["+j+"].script"); QueryInfo info=new QueryInfo(queryName,engine,script); group.queries.add(info); } queryGroups.add(group); } } public void writeOptions() { // If user adds new custom topic panel script, it is saved to global // options instead of local. Therefore we hide class level variable // with another: Options options = globalOptions; for(int i=0;true;i++) { String groupName=options.get(OPTIONS_PREFIX+"group["+i+"].name"); if(groupName==null) break; options.put(OPTIONS_PREFIX+"group["+i+"].name",null); for(int j=0;true;j++) { String queryName=options.get(OPTIONS_PREFIX+"group["+i+"].query["+j+"].name"); if(queryName==null) break; options.put(OPTIONS_PREFIX+"group["+i+"].query["+j+"].name",null); options.put(OPTIONS_PREFIX+"group["+i+"].query["+j+"].engine",null); options.put(OPTIONS_PREFIX+"group["+i+"].query["+j+"].script",null); } } for(int i=0;i<queryGroups.size();i++) { QueryGroupInfo groupInfo=queryGroups.get(i); options.put(OPTIONS_PREFIX+"group["+i+"].name",groupInfo.name); for(int j=0;j<groupInfo.queries.size();j++) { QueryInfo info=groupInfo.queries.get(j); options.put(OPTIONS_PREFIX+"group["+i+"].query["+j+"].name",info.name); options.put(OPTIONS_PREFIX+"group["+i+"].query["+j+"].engine",info.scriptEngine); options.put(OPTIONS_PREFIX+"group["+i+"].query["+j+"].script",info.script); } } } protected void evalQuery(QueryInfo info){ WandoraScriptManager sm=new WandoraScriptManager(); ScriptEngine engine=sm.getScriptEngine(info.scriptEngine); info.directive=null; try { Object o=engine.eval(info.script); if(o!=null && o instanceof Directive) info.directive=(Directive)o; } catch(ScriptException se){ // sm.showScriptExceptionDialog("custom dialog script "+info.name,se); info.evalException=se; } catch(Exception e){ wandora.handleError(e); } // if(info.directive==null){ // WandoraOptionPane.showMessageDialog(parent, "Error evaluating custom topic panel script.<br>Use Configure panel in view menu for details.", "Custom panel script", WandoraOptionPane.ERROR_MESSAGE); // } } public SimplePanel buildCustomPanel(){ SimplePanel ret=new SimplePanel(); ret.setLayout(new java.awt.GridBagLayout()); parseOptions(); int bcounter=0; for(QueryGroupInfo groupInfo : queryGroups){ boolean disabled=options.isFalse(getGroupOptionsKey(groupInfo.name)); if(disabled) continue; SimplePanel groupPanel=new SimplePanel(); groupPanel.setLayout(new java.awt.GridBagLayout()); groupPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(groupInfo.name)); // groupPanel.setComponentPopupMenu(getAssociationsMenu()); groupPanel.setName(groupInfo.name+"GroupPanel"); groupPanel.addMouseListener(wandora); GridBagConstraints gbc=new GridBagConstraints(); int acounter=0; for(QueryInfo info : groupInfo.queries){ if(info.directive==null) { evalQuery(info); if(info.directive==null) { if(info.evalException!=null) WandoraOptionPane.showMessageDialog(wandora, "Error evaluating custom topic panel script "+groupInfo.name+"/"+info.name+"<br>"+info.evalException.getMessage(), "Custom panel script", WandoraOptionPane.ERROR_MESSAGE); else WandoraOptionPane.showMessageDialog(wandora, "Error evaluating custom topic panel script "+groupInfo.name+"/"+info.name+"<br>Script did not return a Directive object.", "Custom panel script", WandoraOptionPane.ERROR_MESSAGE); continue; } } MixedTopicTable table=buildCustomQuery(info.directive,topic); if(table==null) continue; gbc=new java.awt.GridBagConstraints(); gbc.gridy=acounter++; gbc.gridx=0; gbc.anchor=GridBagConstraints.WEST; if(acounter!=1) gbc.insets=new java.awt.Insets(10,0,0,0); SimpleLabel label=new SimpleLabel(info.name); // JPopupMenu popup = this.getAssociationTypeMenu(); // label.setComponentPopupMenu(popup); groupPanel.add(label,gbc); gbc=new java.awt.GridBagConstraints(); gbc.gridy=acounter++; gbc.gridx=0; gbc.weightx=1.0; gbc.fill=GridBagConstraints.HORIZONTAL; groupPanel.add(table.getTableHeader(),gbc); gbc=new java.awt.GridBagConstraints(); gbc.gridy=acounter++; gbc.gridx=0; gbc.weightx=1.0; gbc.fill=GridBagConstraints.HORIZONTAL; groupPanel.add(table,gbc); } if(acounter>0){ gbc=new java.awt.GridBagConstraints(); gbc.gridy=bcounter++; gbc.gridx=0; gbc.weightx=1.0; gbc.fill=GridBagConstraints.HORIZONTAL; gbc.insets = new java.awt.Insets(7, 0, 7, 0); ret.add(groupPanel, gbc); } } return ret; } public MixedTopicTable buildCustomQuery(Directive query, Topic context){ try { TopicMap tm=wandora.getTopicMap(); List<ResultRow> res=query.doQuery(new QueryContext(tm,wandora.getLang()),new ResultRow(context)); List<String> columns=new ArrayList<>(); for(ResultRow row : res){ for(int i=0;i<row.getNumValues();i++){ String r=row.getRole(i); if(!columns.contains(r)) columns.add(r); } } List<Object> columnLabelsA = new ArrayList<>(); for(int i=0;i<columns.size();i++){ String r=columns.get(i); if(r.startsWith("~")) { columns.remove(i); i--; } else { String locator = r; if(locator.startsWith("#")) locator = Directive.DEFAULT_NS+locator; Topic t = tm.getTopic(locator); if(t != null) columnLabelsA.add(t); else columnLabelsA.add(r); } } Object[] columnLabels = columnLabelsA.toArray(new Object[columnLabelsA.size()]); if(res.size()>0) { Object[][] data=new Object[res.size()][columns.size()]; for(int i=0; i<res.size(); i++){ ResultRow row=res.get(i); for(int j=0; j<columns.size(); j++) { String r=columns.get(j); Object v=row.getValue(r); if(v != null) { if(v instanceof Topic) { Locator l = ((Topic) v).getOneSubjectIdentifier(); if(l != null) { Topic t = tm.getTopic((Locator)l); data[i][j]=t; } else { data[i][j]=l.toExternalForm(); } } else if(v instanceof Locator) { data[i][j]=((Locator) v).toExternalForm(); } else if(v instanceof String) { data[i][j]=((String) v); } else { data[i][j] = v.toString(); } } /* Locator l=new Locator(r); if(v instanceof Topic) v=((Topic)v).getOneSubjectIdentifier(); else if(v instanceof String) v=new Locator((String)v); else if(v instanceof Locator){} else v=null; Topic t=null; if(v!=null) t=tm.getTopic((Locator)v); data[i][j]=t; */ } } MixedTopicTable table=new MixedTopicTable(wandora); table.initialize(data, columnLabels); return table; } } catch(QueryException qe) { qe.printStackTrace(); } catch(TopicMapException tme) { tme.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } return null; } @Override public void refresh() { try { topic=wandora.getTopicMap().getTopic(topicSI); if(topic==null || topic.isRemoved()) { System.out.println("Topic is null or removed!"); panelContainer.setVisible(false); removedTopicMessage.setVisible(true); return; } else { panelContainer.setVisible(true); removedTopicMessage.setVisible(false); } } catch(Exception e){ e.printStackTrace(); System.out.println("Topic is null or removed!"); panelContainer.setVisible(false); removedTopicMessage.setVisible(true); return; } super.refresh(); try { if(viewSubjectLocatorResources && topic.getSubjectLocator() != null) { ((PreviewWrapper) previewPanel).setURL(topic.getSubjectLocator()); } else { ((PreviewWrapper) previewPanel).setURL(null); } } catch(Exception e) {} if(subjectIdentifierRootPanel.isVisible()) { buildSubjectIdentifierPanel(subjectIdentifierPanel, topic, options, wandora); } if(customPanel!=null) panelContainer.remove(customPanel); customPanel=buildCustomPanel(); GridBagConstraints gbc = new java.awt.GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 2; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0; gbc.insets = new java.awt.Insets(0, 10, 0, 10); panelContainer.add(customPanel, gbc); panelContainer.revalidate(); try { if(topic.getBaseName()!=null) { baseNameField.setText(topic.getBaseName()); baseNameField.setCaretPosition(0); Color c=wandora.topicHilights.getBaseNameColor(topic); if(c!=null) baseNameField.setForeground(c); else baseNameField.setForeground(Color.BLACK); } else { baseNameField.setText(""); baseNameField.setForeground(Color.BLACK); } originalBN=topic.getBaseName(); if(topic.getSubjectLocator()!=null) { subjectLocatorField.setText(topic.getSubjectLocator().toString()); subjectLocatorField.setCaretPosition(0); Color c=wandora.topicHilights.getSubjectLocatorColor(topic); if(c!=null) subjectLocatorField.setForeground(c); else subjectLocatorField.setForeground(Color.BLACK); originalSL=topic.getSubjectLocator().toString(); } else { subjectLocatorField.setText(""); subjectLocatorField.setForeground(Color.BLACK); originalSL=null; } } catch(Exception e) { System.out.println("Failed to initialize base or/and sl!"); e.printStackTrace(); } this.setComponentPopupMenu(this.getViewPopupMenu()); } @Override public LocatorHistory getTopicHistory() { return null; } @Override public void stop() { if(previewPanel != null && previewPanel instanceof PreviewWrapper) { ((PreviewWrapper) previewPanel).stop(); } } @Override public int print(Graphics graphics, PageFormat pageFormat, int param) throws PrinterException { if (param > 0) { return(NO_SUCH_PAGE); } else { Graphics2D g2d = (Graphics2D)graphics; g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); // Turn off double buffering this.paint(g2d); // Turn double buffering back on return(PAGE_EXISTS); } } // ------------------------------------------------------------------------- @Override public JPopupMenu getNamesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getVariantsLabelPopupStruct(options), wandora); } @Override public JPopupMenu getClassesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getClassesTablePopupStruct(), wandora); } @Override public JPopupMenu getInstancesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getInstancesTablePopupStruct(), wandora); } @Override public JPopupMenu getSIMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getSubjectIdentifierLabelPopupStruct(), wandora); } @Override public JPopupMenu getOccurrencesMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getOccurrencesLabelPopupStruct(options), wandora); } @Override public JPopupMenu getOccurrenceTypeMenu(Topic occurrenceType) { return UIBox.makePopupMenu(WandoraMenuManager.getOccurrenceTypeLabelPopupStruct(occurrenceType, topic), wandora); } public JPopupMenu getSLMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getSubjectLocatorLabelPopupStruct(), wandora); } @Override public JPopupMenu getAssociationsMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getAssociationTableLabelPopupStruct(), wandora); } @Override public JPopupMenu getAssociationTypeMenu() { return UIBox.makePopupMenu(WandoraMenuManager.getAssociationTypeLabelPopupStruct(), wandora); } @Override public JPopupMenu getSubjectMenu() { return null; } @Override public boolean noScroll(){ return false; } // ------------------------------------------------------------------------- /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; configureButton = new org.wandora.application.gui.simple.SimpleButton(); configDialog = new JDialog(wandora); configurationPanel = new CustomTopicPanelConfiguration(wandora); jPanel4 = new javax.swing.JPanel(); configCancelButton = new org.wandora.application.gui.simple.SimpleButton(); configOkButton = new org.wandora.application.gui.simple.SimpleButton(); panelContainer = new javax.swing.JPanel(); previewPanelContainer = new javax.swing.JPanel(); previewPanel = PreviewWrapper.getPreviewWrapper(this); idPanelWrapper = new javax.swing.JPanel(); idPanel = new javax.swing.JPanel(); baseNameLabel = new org.wandora.application.gui.simple.SimpleLabel(); baseNameField = new org.wandora.application.gui.simple.SimpleField(); subjectLocatorLabel = new org.wandora.application.gui.simple.SimpleLabel(); subjectLocatorField = new org.wandora.application.gui.simple.SimpleURIField(); subjectIdentifierLabel = new org.wandora.application.gui.simple.SimpleLabel(); subjectIdentifierRootPanel = new org.wandora.application.gui.simple.SimplePanel(); subjectIdentifierPanel = new javax.swing.JPanel(); removedTopicMessage = new javax.swing.JPanel(); removedTopicMessageLabel = new javax.swing.JLabel(); configureButton.setText("Configure"); configureButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configureButtonActionPerformed(evt); } }); configDialog.setTitle("Custom topic panel configuration"); configDialog.setModal(true); configDialog.getContentPane().setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); configDialog.getContentPane().add(configurationPanel, gridBagConstraints); jPanel4.setLayout(new java.awt.GridBagLayout()); configCancelButton.setText("Cancel"); configCancelButton.setMaximumSize(new java.awt.Dimension(70, 23)); configCancelButton.setPreferredSize(new java.awt.Dimension(70, 23)); configCancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configCancelButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; jPanel4.add(configCancelButton, gridBagConstraints); configOkButton.setText("OK"); configOkButton.setMaximumSize(new java.awt.Dimension(70, 23)); configOkButton.setPreferredSize(new java.awt.Dimension(70, 23)); configOkButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configOkButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel4.add(configOkButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); configDialog.getContentPane().add(jPanel4, gridBagConstraints); setLayout(new java.awt.GridBagLayout()); panelContainer.setLayout(new java.awt.GridBagLayout()); previewPanelContainer.setLayout(new java.awt.GridBagLayout()); previewPanel.setToolTipText(""); previewPanel.setMinimumSize(new java.awt.Dimension(2, 2)); previewPanel.setName("previewPanel"); // NOI18N previewPanel.setPreferredSize(new java.awt.Dimension(2, 2)); previewPanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; previewPanelContainer.add(previewPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 15, 5, 15); panelContainer.add(previewPanelContainer, gridBagConstraints); idPanelWrapper.setLayout(new java.awt.GridBagLayout()); idPanel.setLayout(new java.awt.GridBagLayout()); baseNameLabel.setText("Base name"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; idPanel.add(baseNameLabel, gridBagConstraints); baseNameField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { baseNameFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); idPanel.add(baseNameField, gridBagConstraints); subjectLocatorLabel.setText("Subject locator"); subjectLocatorLabel.setComponentPopupMenu(getSLMenu()); subjectLocatorLabel.addMouseListener(wandora); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; idPanel.add(subjectLocatorLabel, gridBagConstraints); subjectLocatorField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { subjectLocatorFieldKeyReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); idPanel.add(subjectLocatorField, gridBagConstraints); subjectIdentifierLabel.setText("Subject identifiers"); subjectIdentifierLabel.setComponentPopupMenu(getSIMenu()); subjectLocatorLabel.addMouseListener(wandora); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 0); idPanel.add(subjectIdentifierLabel, gridBagConstraints); subjectIdentifierRootPanel.setName("subjectIdentifierRootPanel"); // NOI18N subjectIdentifierRootPanel.setLayout(new java.awt.BorderLayout()); subjectIdentifierPanel.setLayout(new java.awt.GridLayout(1, 0)); subjectIdentifierRootPanel.add(subjectIdentifierPanel, java.awt.BorderLayout.NORTH); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 1); idPanel.add(subjectIdentifierRootPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(7, 15, 7, 15); idPanelWrapper.add(idPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; panelContainer.add(idPanelWrapper, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(panelContainer, gridBagConstraints); removedTopicMessage.setBackground(new java.awt.Color(255, 255, 255)); removedTopicMessage.setLayout(new java.awt.GridBagLayout()); removedTopicMessageLabel.setText("<html>Topic is either merged or removed and can not be viewed!</html>"); removedTopicMessage.add(removedTopicMessageLabel, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(removedTopicMessage, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents public static String checkScript(Component parent,String engineString,String script){ WandoraScriptManager sm=new WandoraScriptManager(); ScriptEngine engine=sm.getScriptEngine(engineString); if(engine==null){ return "Couldn't find script engine"; } try { Object o=engine.eval(script); if(o==null){ return "Script returned null."; } else if(!(o instanceof org.wandora.query2.Directive)){ return "Script didn't return an instance of Directive.<br>"+ "Class of return value is "+o.getClass().getName(); } } catch(ScriptException se){ return "ScriptException at line "+se.getLineNumber()+" column "+se.getColumnNumber()+"<br>"+se.getMessage(); } catch(Exception e){ e.printStackTrace(); return "Exception occurred during execution: "+e.getClass().getName()+" "+e.getMessage(); } return null; } private void configOkButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configOkButtonActionPerformed if(configDialog.isVisible()){ List<QueryGroupInfo> newGroups=((CustomTopicPanelConfiguration)configurationPanel).getQueryGroups(); /* boolean error=false; for(QueryGroupInfo group : newGroups){ for(QueryInfo query : group.queries){ String message=checkScript(this,query.scriptEngine,query.script); if(message!=null){ error=true; WandoraOptionPane.showMessageDialog(configDialog, "Error in group "+group.name+", query "+query.name+"<br>"+message, "Check syntax", WandoraOptionPane.ERROR_MESSAGE); } } } if(!error){*/ queryGroups=newGroups; writeOptions(); refresh(); configDialog.setVisible(false); // } } }//GEN-LAST:event_configOkButtonActionPerformed private void configCancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configCancelButtonActionPerformed if(configDialog.isVisible()){ configDialog.setVisible(false); } }//GEN-LAST:event_configCancelButtonActionPerformed protected void showConfigureDialog(){ ((CustomTopicPanelConfiguration)configurationPanel).readQueryGroups(queryGroups); configDialog.setSize(400,500); wandora.centerWindow(configDialog); configDialog.setVisible(true); wandora.topicPanelsChanged(); } private void configureButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configureButtonActionPerformed showConfigureDialog(); }//GEN-LAST:event_configureButtonActionPerformed private void subjectLocatorFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_subjectLocatorFieldKeyReleased try { if(evt.getKeyCode()==KeyEvent.VK_ENTER) { applyChanges(); } } catch(Exception e) {} }//GEN-LAST:event_subjectLocatorFieldKeyReleased private void baseNameFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_baseNameFieldKeyReleased try { if(evt.getKeyCode()==KeyEvent.VK_ENTER) { applyChanges(); } } catch(Exception e) {} }//GEN-LAST:event_baseNameFieldKeyReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField baseNameField; private javax.swing.JLabel baseNameLabel; private javax.swing.JButton configCancelButton; private javax.swing.JDialog configDialog; private javax.swing.JButton configOkButton; private javax.swing.JPanel configurationPanel; private javax.swing.JButton configureButton; private javax.swing.JPanel idPanel; private javax.swing.JPanel idPanelWrapper; private javax.swing.JPanel jPanel4; private javax.swing.JPanel panelContainer; private javax.swing.JPanel previewPanel; private javax.swing.JPanel previewPanelContainer; private javax.swing.JPanel removedTopicMessage; private javax.swing.JLabel removedTopicMessageLabel; private javax.swing.JLabel subjectIdentifierLabel; private javax.swing.JPanel subjectIdentifierPanel; private javax.swing.JPanel subjectIdentifierRootPanel; private javax.swing.JTextField subjectLocatorField; private javax.swing.JLabel subjectLocatorLabel; // End of variables declaration//GEN-END:variables // ------------------------------------------------------------------------- public static class QueryGroupInfo { public String name; public ArrayList<QueryInfo> queries; public QueryGroupInfo(){ queries=new ArrayList<QueryInfo>(); } public QueryGroupInfo deepCopy(){ QueryGroupInfo g=new QueryGroupInfo(); g.name=this.name; for(QueryInfo q : queries){ g.queries.add(q.copy()); } return g; } @Override public String toString(){ return name; } } // ------------------------------------------------------------------------- public static class QueryInfo { public String name; public String scriptEngine; public String script; public Directive directive; public ScriptException evalException; public QueryInfo(){} public QueryInfo(String name,String scriptEngine,String script){ this.name=name; this.scriptEngine=scriptEngine; this.script=script; } public QueryInfo copy(){ return new QueryInfo(name,scriptEngine,script); } public String toString(){ return name; } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- private class TopicPanelTransferHandler extends TransferHandler { @Override public boolean canImport(TransferSupport support) { return false; //if(!support.isDrop()) return false; //return support.isDataFlavorSupported(DnDHelper.topicDataFlavor) || // support.isDataFlavorSupported(DataFlavor.stringFlavor); } @Override protected Transferable createTransferable(JComponent c) { // return DnDHelper.makeTopicTableTransferable(data,getSelectedRows(),getSelectedColumns()); return null; } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY_OR_MOVE; } @Override public boolean importData(TransferSupport support) { if(!support.isDrop()) return false; try { /* TopicMap tm=parent.getTopicMap(); ArrayList<Topic> topics=DnDHelper.getTopicList(support, tm, true); if(topics==null) return false; Topic base=topic; if(base==null) return false; for(Topic t : topics) { if(t != null && !t.isRemoved()) { base.addType(t); } } */ wandora.doRefresh(); } catch(Exception ce){ Wandora.getWandora().handleError(ce); } return false; } } }
43,346
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SearchTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/SearchTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.topicpanels; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collection; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.search.QueryPanel; import org.wandora.application.gui.search.SearchPanel; import org.wandora.application.gui.search.SimilarityPanel; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.exceptions.OpenTopicNotSupportedException; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * * @author akivela */ public class SearchTopicPanel extends javax.swing.JPanel implements ActionListener, TopicPanel { private static final long serialVersionUID = 1L; private Options options = null; private SearchPanel searchPanel = null; private SimilarityPanel similarityPanel = null; private QueryPanel queryPanel = null; private Component currentContainerPanel = null; private Topic openedTopic = null; private boolean useResultScrollPanes = false; /** * Creates new form SearchTopicPanel */ public SearchTopicPanel() { } @Override public void init() { searchPanel = new SearchPanel(); similarityPanel = new SimilarityPanel(); queryPanel = new QueryPanel(); if(!useResultScrollPanes) { removeResultScrollPanes(); } Wandora wandora = Wandora.getWandora(); this.options = new Options(wandora.getOptions()); initComponents(); try { tabbedPane.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { // System.out.println("Tab: " + tabbedPane.getSelectedIndex()); setCurrentPanel(tabbedPane.getSelectedComponent()); } }); setCurrentPanel(searchContainerPanel); } catch(Exception e) { e.printStackTrace(); } } public void setUseResultScrollPanes(boolean use) { useResultScrollPanes = use; } /* * By default SearchTopicPanel removes MouseListeners in all result tables of * sub panels. This enables mouse wheel events of SearchTopicPanel to work * over result tables. At the moment SearchTopicsFrame keeps the MouseListeners * intact by calling setUseResultScrollPanes(true). SearchTopicsFrame has no * global ScrollPane but relies on ScrollPanes in result tables. * * Notice, this method in called from init if useResultScrollPanes is false. * By default it is false and you need to call setUseResultScrollPanes(true) * before init is called in order to keep mouse listeners alive. */ public void removeResultScrollPanes() { searchPanel.removeResultScrollPanesMouseListeners(); similarityPanel.removeResultScrollPanesMouseListeners(); queryPanel.removeResultScrollPanesMouseListeners(); } private void setCurrentPanel(Component p) { if(p != null) { if(!p.equals(currentContainerPanel)) { /* Why remove content from other container panels? Tabbed pane's height is inherited from the heighest component within. Removing content from other container panels ensures the tabbed pane inherits it's height from the active tab. */ if(p.equals(searchContainerPanel)) { searchContainerPanel.add(searchPanel, BorderLayout.CENTER); similarityContainerPanel.removeAll(); queryContainerPanel.removeAll(); tmqlContainerPanel.removeAll(); } else if(p.equals(similarityContainerPanel)) { similarityContainerPanel.add(similarityPanel, BorderLayout.CENTER); searchContainerPanel.removeAll(); queryContainerPanel.removeAll(); tmqlContainerPanel.removeAll(); } else if(p.equals(queryContainerPanel)) { queryContainerPanel.add(queryPanel, BorderLayout.CENTER); searchContainerPanel.removeAll(); similarityContainerPanel.removeAll(); tmqlContainerPanel.removeAll(); } currentContainerPanel = p; this.revalidate(); } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; tabbedPane = new SimpleTabbedPane(); searchContainerPanel = new javax.swing.JPanel(); similarityContainerPanel = new javax.swing.JPanel(); queryContainerPanel = new javax.swing.JPanel(); tmqlContainerPanel = new javax.swing.JPanel(); setLayout(new java.awt.GridBagLayout()); searchContainerPanel.setLayout(new java.awt.BorderLayout()); tabbedPane.addTab("Finder", searchContainerPanel); similarityContainerPanel.setLayout(new java.awt.BorderLayout()); tabbedPane.addTab("Similar", similarityContainerPanel); queryContainerPanel.setLayout(new java.awt.BorderLayout()); tabbedPane.addTab("Query", queryContainerPanel); tmqlContainerPanel.setLayout(new java.awt.BorderLayout()); // tabbedPane.addTab("TMQL", tmqlContainerPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(tabbedPane, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel queryContainerPanel; private javax.swing.JPanel searchContainerPanel; private javax.swing.JPanel similarityContainerPanel; private javax.swing.JTabbedPane tabbedPane; private javax.swing.JPanel tmqlContainerPanel; // End of variables declaration//GEN-END:variables @Override public void actionPerformed(ActionEvent e) { } @Override public boolean supportsOpenTopic() { return false; } @Override public void open(Topic topic) throws TopicMapException, OpenTopicNotSupportedException { // Notice, this TopicPanel doesn't support open topic. openedTopic = topic; } @Override public void stop() { openedTopic = null; } @Override public void refresh() throws TopicMapException { searchPanel.refresh(); similarityPanel.refresh(); queryPanel.refresh(); revalidate(); } @Override public boolean applyChanges() throws CancelledException, TopicMapException { return true; } @Override public JPanel getGui() { return this; } @Override public Topic getTopic() throws TopicMapException { Component selectedTab = tabbedPane.getSelectedComponent(); if(selectedTab != null) { if(selectedTab.equals(searchContainerPanel)) { return searchPanel.getSelectedTopic(); } else if(selectedTab.equals(similarityContainerPanel)) { return similarityPanel.getSelectedTopic(); } else if(selectedTab.equals(queryContainerPanel)) { return queryPanel.getSelectedTopic(); } } return openedTopic; } @Override public String getName(){ return "Search"; } @Override public String getTitle() { return "Search and query"; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_panel_search.png"); } @Override public int getOrder() { return 9995; } @Override public Object[] getViewMenuStruct() { return new Object[] { }; } @Override public JMenu getViewMenu() { return UIBox.makeMenu(getViewMenuStruct(), this); } @Override public JPopupMenu getViewPopupMenu() { return UIBox.makePopupMenu(getViewMenuStruct(), this); } @Override public LocatorHistory getTopicHistory() { return null; } @Override public boolean noScroll(){ return false; } // ------------------------------------------------------------------------- @Override public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { refresh(); } @Override public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { refresh(); } @Override public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { refresh(); } @Override public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { refresh(); } @Override public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { refresh(); } @Override public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { refresh(); } @Override public void topicRemoved(Topic t) throws TopicMapException { refresh(); } @Override public void topicChanged(Topic t) throws TopicMapException { refresh(); } @Override public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { refresh(); } @Override public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { refresh(); } @Override public void associationRemoved(Association a) throws TopicMapException { refresh(); } @Override public void associationChanged(Association a) throws TopicMapException { refresh(); } }
12,131
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GraphTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/GraphTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * GraphTopicPanel.java * * Created on 12.6.2007, 14:09 * */ package org.wandora.application.gui.topicpanels; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import javax.swing.ButtonGroup; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JToolBar; import javax.swing.KeyStroke; import javax.swing.Scrollable; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.RefreshListener; import org.wandora.application.Wandora; import org.wandora.application.gui.Clipboardable; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleComponent; import org.wandora.application.gui.simple.SimpleToggleButton; import org.wandora.application.gui.topicpanels.graphpanel.AssociationEdge; import org.wandora.application.gui.topicpanels.graphpanel.Edge; import org.wandora.application.gui.topicpanels.graphpanel.FilterManagerPanel; import org.wandora.application.gui.topicpanels.graphpanel.Node; import org.wandora.application.gui.topicpanels.graphpanel.OccurrenceNode; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.TopicNode; import org.wandora.application.gui.topicpanels.graphpanel.VEdge; import org.wandora.application.gui.topicpanels.graphpanel.VModel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.graph.CenterCurrentTopic; import org.wandora.application.tools.graph.ChangeCurvature; import org.wandora.application.tools.graph.ChangeFramerate; import org.wandora.application.tools.graph.ChangeNodeMass; import org.wandora.application.tools.graph.ChangeScale; import org.wandora.application.tools.graph.ChangeStiffness; import org.wandora.application.tools.graph.SetMouseTool; import org.wandora.application.tools.graph.ToggleProjectionSettings; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.utils.ClipboardBox; import org.wandora.utils.Options; /** * * @author olli, akivela */ public class GraphTopicPanel extends JPanel implements TopicPanel, Scrollable, SimpleComponent, Clipboardable, TopicMapListener, RefreshListener, ActionListener, ComponentListener { private static final long serialVersionUID = 1L; private String OPTIONS_PREFIX = "gui.graphTopicPanel."; private String OPTIONS_VIEW_PREFIX = OPTIONS_PREFIX + "view."; protected Wandora wandora = null; private TopicMapGraphPanel graphPanel; private HashMap<Integer,SimpleToggleButton> toolButtons; private Options localOptions = null; public GraphTopicPanel() { } @Override public void init() { this.wandora = Wandora.getWandora(); JPanel leftPane=new JPanel(); leftPane.setLayout(new BorderLayout()); localOptions = wandora.getOptions(); graphPanel = new TopicMapGraphPanel(wandora, new Options(localOptions)) { @Override public void setMouseTool(int tool) { GraphTopicPanel.this.mouseToolChanged(tool); super.setMouseTool(tool); } }; graphPanel.addFocusListener(this); this.setFocusable(true); leftPane.add(graphPanel,BorderLayout.CENTER); JToolBar toolBar=new JToolBar(JToolBar.VERTICAL); // toolBar.setBorder(MetalBorders.ToolBarBorder()); toolBar.setMargin(new Insets(0,0,0,0)); leftPane.add(toolBar,BorderLayout.WEST); makeToolBar(toolBar); //mouseToolChanged(graphPanel.getMouseTool()); this.setLayout(new BorderLayout()); this.add(leftPane); FilterManagerPanel filterManager=new FilterManagerPanel(wandora); graphPanel.setFilterManagerPanel(filterManager); } public void mouseToolChanged(int tool){ if(toolButtons!=null){ SimpleToggleButton selected=toolButtons.get(tool); for(SimpleToggleButton b : toolButtons.values()){ b.setSelected(false); } selected.setSelected(true); } } public TopicMapGraphPanel getGraphPanel(){ return graphPanel; } private void makeToolBar(Container container){ Object[] struct = new Object[] { new ButtonGroup(), new SimpleToggleButton("gui/icons/graphpanel/hand_on.png", "gui/icons/graphpanel/hand.png", true), new SetMouseTool(getGraphPanel(), TopicMapGraphPanel.TOOL_OPEN), KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), new SimpleToggleButton("gui/icons/graphpanel/lasso_on.png", "gui/icons/graphpanel/lasso.png", true), new SetMouseTool(getGraphPanel(), TopicMapGraphPanel.TOOL_SELECT), KeyStroke.getKeyStroke(KeyEvent.VK_2, 0), new SimpleToggleButton("gui/icons/graphpanel/pen_on.png", "gui/icons/graphpanel/pen.png", true), new SetMouseTool(getGraphPanel(), TopicMapGraphPanel.TOOL_ASSOCIATION), KeyStroke.getKeyStroke(KeyEvent.VK_3, 0), //new SimpleToggleButton("gui/icons/graphpanel/eraser_on.png", "gui/icons/graphpanel/eraser.png", true), new SetMouseTool(getGraphPanel(), TopicMapGraphPanel.TOOL_ERASER), KeyStroke.getKeyStroke(KeyEvent.VK_4, 0), "---", //new SimpleButton(UIBox.getIcon("gui/icons/graphpanel/filter_win.png")), new ToggleFilterWindow(), new SimpleToggleButton("gui/icons/graphpanel/change_scale_on.png", "gui/icons/graphpanel/change_scale.png"), new ChangeScale(getGraphPanel()), new SimpleToggleButton("gui/icons/graphpanel/change_curvature_on.png", "gui/icons/graphpanel/change_curvature.png"), new ChangeCurvature(getGraphPanel()), new SimpleToggleButton("gui/icons/graphpanel/change_framerate_on.png", "gui/icons/graphpanel/change_framerate.png"), new ChangeFramerate(getGraphPanel()), new SimpleToggleButton("gui/icons/graphpanel/change_mass_on.png", "gui/icons/graphpanel/change_mass.png"), new ChangeNodeMass(getGraphPanel()), new SimpleToggleButton("gui/icons/graphpanel/change_stiffness_on.png", "gui/icons/graphpanel/change_stiffness.png"), new ChangeStiffness(getGraphPanel()), "---", new SimpleButton(UIBox.getIcon("gui/icons/graphpanel/change_view.png")), new ToggleProjectionSettings(getGraphPanel()), new SimpleButton(UIBox.getIcon("gui/icons/graphpanel/center_view.png")), new CenterCurrentTopic(getGraphPanel()), }; toolButtons=new HashMap<>(); SimpleToggleButton lastButton=null; for(int i=0;i<struct.length;i++){ if(struct[i] instanceof SimpleToggleButton){ lastButton=(SimpleToggleButton)struct[i]; } if(struct[i] instanceof SetMouseTool){ if(lastButton!=null){ int tool=((SetMouseTool)struct[i]).getMouseTool(); toolButtons.put(tool,lastButton); } } } UIBox.fillGraphToolBar(container, struct, wandora); if(graphPanel!=null) mouseToolChanged(graphPanel.getMouseTool()); } @Override public void refresh() throws TopicMapException { graphPanel.refreshGraph(); } @Override public LocatorHistory getTopicHistory() { return null; } public Collection<Association> getContextAssociations() { Collection<VEdge> edges=graphPanel.getSelectedEdges(); Collection<Association> ret = new ArrayList<>(); if(edges != null) { VEdge vedge = null; Edge edge = null; Association a = null; for(Iterator<VEdge> iter = edges.iterator(); iter.hasNext();) { vedge = iter.next(); if(vedge != null) { edge = vedge.getEdge(); if(edge instanceof AssociationEdge) { ret.add(((AssociationEdge) edge).getAssociation()); } } } } return ret; } public Collection<Topic> getContextTopics(){ Collection<Topic> ret=graphPanel.getSelectedTopics(); if(ret.isEmpty()) { List<Topic> al=new ArrayList<>(); al.add(graphPanel.getRootTopic()); return al; } else return ret; } public Collection getContext(){ Set<VNode> ret=graphPanel.getSelectedNodes(); if(ret.isEmpty()) { List al=new ArrayList(); al.add(graphPanel.getRootNode()); return al; } else return ret; } @Override public Topic getTopic() throws TopicMapException { return graphPanel.getRootTopic(); } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_panel_graph.png"); } @Override public String getName(){ return "Graph"; } @Override public String getTitle() { Topic t = graphPanel.getMouseOverTopic(); if(t == null) t = graphPanel.getRootTopic(); if(t != null) return TopicToString.toString(t); else return ""; } @Override public int getOrder() { return 100; } @Override public JPanel getGui() { return this; } @Override public boolean applyChanges() throws CancelledException, TopicMapException { return true; } @Override public boolean noScroll(){ return false; } @Override public JPopupMenu getViewPopupMenu() { return UIBox.makePopupMenu(getViewMenuStruct(), this); } @Override public JMenu getViewMenu() { List<Object> menuStructure = new ArrayList<>(); menuStructure.add("---"); Object[] a = graphPanel.getOptionsMenuStruct(); for(Object o : a) { menuStructure.add(o); } return UIBox.makeMenu(menuStructure.toArray(new Object[] {}), this); } @Override public Object[] getViewMenuStruct() { return graphPanel.getOptionsMenuStruct(); } @Override public void stop() { // NOTHING TO STOP! } @Override public boolean supportsOpenTopic() { return true; } @Override public void open(Topic topic) throws TopicMapException { graphPanel.setRootTopic(topic); } public void toggleVisibility(String componentName) { } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); System.out.println("GraphTopicPanel catched action command '" + c + "'."); toggleVisibility(c); } // ------------------------------------------------------------------------- // ----------------------------------------------------------- awt stuff --- // ------------------------------------------------------------------------- @Override public boolean getScrollableTracksViewportWidth() { return true; } @Override public boolean getScrollableTracksViewportHeight() { return true; } @Override public Dimension getPreferredScrollableViewportSize() { return getPreferredSize(); } @Override public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { return 1; } @Override public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { return 1; } @Override public void focusLost(FocusEvent e) { } @Override public void focusGained(FocusEvent e) { if(wandora == null) { wandora = Wandora.getWandora(this); } if(wandora != null) { wandora.gainFocus(this); } } // ------------------------------------------------------------------------- // ------------------------------------------------- Topic map listener ---- // ------------------------------------------------------------------------- @Override public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { graphPanel.topicTypeChanged(t,added,removed); } @Override public void doRefresh() throws TopicMapException { graphPanel.doRefresh(); } @Override public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { graphPanel.topicSubjectIdentifierChanged(t,added,removed); } @Override public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { graphPanel.topicSubjectLocatorChanged(t,newLocator,oldLocator); } @Override public void associationChanged(Association a) throws TopicMapException { graphPanel.associationChanged(a); } @Override public void associationRemoved(Association a) throws TopicMapException { graphPanel.associationRemoved(a); } @Override public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { graphPanel.topicBaseNameChanged(t,newName,oldName); } @Override public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { graphPanel.topicDataChanged(t,type,version,newValue,oldValue); } @Override public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { graphPanel.topicVariantChanged(t,scope,newName,oldName); } @Override public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { graphPanel.associationPlayerChanged(a,role,newPlayer,oldPlayer); } @Override public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { graphPanel.associationTypeChanged(a,newType,oldType); } @Override public void topicChanged(Topic t) throws TopicMapException { graphPanel.topicChanged(t); } @Override public void topicRemoved(Topic t) throws TopicMapException { graphPanel.topicRemoved(t); } // ------------------------------------------------------- CLIPBOARDABLE --- @Override public void copy() { VModel model = graphPanel.getModel(); StringBuilder sb = new StringBuilder(""); if(model != null) { Topic t = null; Iterator<VNode> nodeIterator = null; Set<VNode> copyNodes = model.getSelectedNodes(); if(copyNodes != null && !copyNodes.isEmpty()) { nodeIterator = copyNodes.iterator(); } else { nodeIterator = model.getNodes().iterator(); } VNode vnode = null; while( nodeIterator.hasNext() ) { vnode = nodeIterator.next(); if(vnode != null) { Node n = vnode.getNode(); if(n != null) { if(n instanceof TopicNode) { t = ((TopicNode) n).getTopic(); if(t != null) { try { sb.append(TopicToString.toString(t)).append("\n"); } catch(Exception e) { e.printStackTrace(); } } } else if(n instanceof OccurrenceNode) { try { sb.append(((OccurrenceNode) n).getOccurrence()).append("\n"); } catch(Exception e) { e.printStackTrace(); } } } } } } ClipboardBox.setClipboard(sb.toString()); } @Override public void cut() { copy(); } private boolean autoCreateTopicsInPaste = false; @Override public void paste() { Topic originalRootTopic = graphPanel.getRootTopic(); String tabText = ClipboardBox.getClipboard(); StringTokenizer tabLines = new StringTokenizer(tabText, "\n"); autoCreateTopicsInPaste = false; while(tabLines.hasMoreTokens()) { String tabLine = tabLines.nextToken(); StringTokenizer topicIdentifiers = new StringTokenizer(tabLine, "\t"); try { String topicIdentifier = null; while(topicIdentifiers.hasMoreTokens()) { topicIdentifier = topicIdentifiers.nextToken(); if(topicIdentifier != null && topicIdentifier.length() > 0) { Topic pastedTopic = getTopicForIdentifier(topicIdentifier); if(pastedTopic == null) { boolean createTopicInPaste = false; if(!autoCreateTopicsInPaste) { int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Can't find a topic for identifier '"+topicIdentifier+"'. Would you like to create a topic for '"+topicIdentifier+"'?", "Create new topic?", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION); if(a == WandoraOptionPane.YES_OPTION) { createTopicInPaste = true; } else if(a == WandoraOptionPane.YES_TO_ALL_OPTION) { autoCreateTopicsInPaste = true; } else if(a == WandoraOptionPane.CANCEL_OPTION) { graphPanel.setRootTopic(originalRootTopic); return; } } if(autoCreateTopicsInPaste || createTopicInPaste) { TopicMap tm = Wandora.getWandora().getTopicMap(); if(tm != null) { boolean identifierIsURL = false; try { URL u = new URL(topicIdentifier); identifierIsURL = true; } catch(Exception e) {} pastedTopic = tm.createTopic(); if(identifierIsURL) { pastedTopic.addSubjectIdentifier(new Locator(topicIdentifier)); } else { pastedTopic.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); pastedTopic.setBaseName(topicIdentifier); } // pastedTopic.addType(originalRootTopic); } } } if(pastedTopic != null) { graphPanel.setRootTopic(pastedTopic); } } } } catch(Exception e) { } } graphPanel.setRootTopic(originalRootTopic); } protected Topic getTopicForIdentifier(String id) { TopicMap tm = wandora.getTopicMap(); Topic t = null; try { t = tm.getTopicWithBaseName(id); if(t == null) { t = tm.getTopic(id); if(t == null) { t = tm.getTopicBySubjectLocator(new Locator(id)); } } } catch(Exception e) { } return t; } /* * This is the old and deprecated paste method. */ public void old_paste() { boolean requiresRefresh = false; TopicMap topicMap = Wandora.getWandora().getTopicMap(); if(topicMap != null) { String clipboardText = ClipboardBox.getClipboard(); if(clipboardText != null && clipboardText.length() > 0) { String[] identifiers = clipboardText.split("\n"); if(identifiers != null && identifiers.length > 0) { for(int i=0; i<identifiers.length; i++) { String identifier = identifiers[i]; if(identifier != null && identifier.length() > 0) { try { Topic t = topicMap.getTopic(identifier); if(t == null) t = topicMap.getTopicWithBaseName(identifier); if(t == null) t = topicMap.getTopicBySubjectLocator(identifier); if(t == null) { identifier = identifier.trim(); t = topicMap.getTopic(identifier); if(t == null) t = topicMap.getTopicWithBaseName(identifier); if(t == null) t = topicMap.getTopicBySubjectLocator(identifier); } if(t != null) { if(t != null && !t.isRemoved()) { graphPanel.setRootTopic(t); requiresRefresh = true; } } } catch(Exception e) { } } } } } } if(requiresRefresh) { try { Wandora.getWandora().doRefresh(); } catch(Exception e) {} } } // -------------------------------------------------- Component Listener --- @Override public void componentResized(ComponentEvent e) { if(graphPanel != null) graphPanel.setSize(getWidth(), getHeight()); } @Override public void componentMoved(ComponentEvent e) { if(graphPanel != null) graphPanel.setSize(getWidth(), getHeight()); } @Override public void componentShown(ComponentEvent e) { if(graphPanel != null) graphPanel.setSize(getWidth(), getHeight()); } @Override public void componentHidden(ComponentEvent e) { if(graphPanel != null) graphPanel.setSize(getWidth(), getHeight()); } }
25,186
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
DockingFramePanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/DockingFramePanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * DockingFramePanel.java * * */ package org.wandora.application.gui.topicpanels; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.image.BufferedImage; import java.io.File; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.RefreshListener; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.WandoraToolManager; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleMenu; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.application.gui.topicpanels.dockingpanel.SelectTopicPanelPanel; import org.wandora.application.gui.topicpanels.dockingpanel.WandoraDockActionSource; import org.wandora.application.gui.topicpanels.dockingpanel.WandoraDockController; import org.wandora.application.gui.topicpanels.dockingpanel.WandoraDockable; import org.wandora.application.gui.topicpanels.dockingpanel.WandoraSplitDockStation; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.ChainExecuter; import org.wandora.application.tools.docking.AddDockable; import org.wandora.application.tools.docking.DeleteAllDockables; import org.wandora.application.tools.docking.DeleteCurrentDockable; import org.wandora.application.tools.docking.DeleteDockable; import org.wandora.application.tools.docking.MaximizeDockable; import org.wandora.application.tools.docking.SelectDockable; import org.wandora.application.tools.extractors.files.SimpleFileExtractor; import org.wandora.exceptions.OpenTopicNotSupportedException; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.utils.Base64; import org.wandora.utils.DataURL; import org.wandora.utils.DnDBox; import org.wandora.utils.Options; import bibliothek.gui.Dockable; import bibliothek.gui.dock.dockable.AbstractDockable; import bibliothek.gui.dock.event.DockableFocusEvent; import bibliothek.gui.dock.event.DockableFocusListener; import bibliothek.gui.dock.event.DockableListener; import bibliothek.gui.dock.title.DockTitle; /** * DockingFramePanel is a base topic panel of the Wandora application. * It is a topic panel container and can hold several different topic panels. * * * @author akivela */ public class DockingFramePanel extends JPanel implements TopicPanel, ActionListener, RefreshListener, TopicMapListener, DockableFocusListener, ComponentListener, DockableListener, DropTargetListener, DragGestureListener { private static final long serialVersionUID = 1L; private String OPTIONS_PREFIX = "gui.dockingFramePanel."; private HashMap<Dockable,TopicPanel> dockedTopicPanels; private Dockable currentDockable = null; private WandoraSplitDockStation station = null; private WandoraDockController control = null; private Wandora wandora = null; private BufferedImage backgroundImage = null; private int backgroundImageWidth = 0; private int backgroundImageHeight = 0; private DropTarget dropTarget = null; private HashMap<TopicPanel,TopicPanel> chainedTopicPanels = null; private Topic openedTopic = null; public DockingFramePanel() { } @Override public void init() { backgroundImage = UIBox.getImage("gui/startup_image.gif"); backgroundImageWidth = backgroundImage.getWidth(); backgroundImageHeight = backgroundImage.getHeight(); wandora = Wandora.getWandora(); dockedTopicPanels = new HashMap<>(); chainedTopicPanels = new HashMap<>(); control = new WandoraDockController(); control.addDockableFocusListener(this); station = new WandoraSplitDockStation(); control.add(station); this.setLayout(new BorderLayout () ); this.add( station.getComponent() ); this.addComponentListener(this); dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this); } // ------------------------------------------------------------------------- private int x = 0; private int y = 0; private int w = 0; private int h = 0; @Override public void paint(Graphics g) { super.paint(g); if(dockedTopicPanels.isEmpty() && backgroundImage != null) { w = this.getWidth(); h = this.getHeight(); x = (w - backgroundImageWidth) / 2; y = (h - backgroundImageHeight) / 2; g.setColor(Color.WHITE); g.fillRect(0, 0, w, h); g.drawImage(backgroundImage, x, y, this); } } // ------------------------------------------------------------------------- public Dockable getDockableFor(TopicPanel topicPanel) { if(topicPanel != null) { for(Dockable dockable : dockedTopicPanels.keySet()) { TopicPanel dockedTopicPanel = dockedTopicPanels.get(dockable); if(dockedTopicPanel.equals(topicPanel)) { return dockable; } } } return null; } public void updateDockableTitle(TopicPanel topicPanel) { if(topicPanel != null) { Dockable dockable = getDockableFor(topicPanel); if(dockable != null) { if(dockable instanceof AbstractDockable) { AbstractDockable abstractDockable = (AbstractDockable) dockable; abstractDockable.setTitleText(topicPanel.getTitle()); } } } } public void openTo(Topic topic, TopicPanel topicPanel) throws TopicMapException, OpenTopicNotSupportedException { for(Dockable dockable : dockedTopicPanels.keySet()) { TopicPanel dockedTopicPanel = dockedTopicPanels.get(dockable); if(dockedTopicPanel.equals(topicPanel)) { currentDockable = dockable; open(topic); } } } @Override public boolean supportsOpenTopic() { return true; } @Override public void open(Topic topic) throws TopicMapException, OpenTopicNotSupportedException { //System.out.println("initialize Docking Frame Panel"); //String name = TopicToString.toString(topic); openedTopic = topic; if(currentDockable == null) { if(!dockedTopicPanels.isEmpty()) { currentDockable = dockedTopicPanels.keySet().iterator().next(); } } if(currentDockable == null) { // Ensure there is at least one dockable when topic is opened. addDockable(getDefaultPanel(), topic); } else { control.setFocusedDockable(currentDockable, true); TopicPanel currentTopicPanel = dockedTopicPanels.get(currentDockable); if(currentTopicPanel != null) { if(currentTopicPanel.supportsOpenTopic()) { currentTopicPanel.open(topic); updateDockableTitle(currentTopicPanel); } else { // We are going to ask the user where the topic will be opened. List<TopicPanel> availableTopicPanels = new ArrayList<>(); for(Dockable dockable : dockedTopicPanels.keySet()) { TopicPanel availableTopicPanel = dockedTopicPanels.get(dockable); if(availableTopicPanel != null && availableTopicPanel.supportsOpenTopic()) { availableTopicPanels.add( availableTopicPanel ); } } // Easy. No suitable topic panels available. Create one. if(availableTopicPanels.isEmpty()) { addDockable(getDefaultPanel(), topic); } // Easy. Only one suitable topic panel available. Use it. else if(availableTopicPanels.size() == 1) { TopicPanel alternativeTopicPanel = availableTopicPanels.get(0); alternativeTopicPanel.open(topic); updateDockableTitle(alternativeTopicPanel); } // Ask the user if we don't remember any earlier topic panel. else { boolean askForATopicPanel = true; TopicPanel rememberedTargetTopicPanel = chainedTopicPanels.get(currentTopicPanel); if(rememberedTargetTopicPanel != null) { Dockable dockable = this.getDockableFor(rememberedTargetTopicPanel); if(dockable != null) { rememberedTargetTopicPanel.open(topic); updateDockableTitle(rememberedTargetTopicPanel); askForATopicPanel = false; } else { chainedTopicPanels.remove(currentTopicPanel); } } if(askForATopicPanel) { SelectTopicPanelPanel topicPanelSelector = new SelectTopicPanelPanel(); topicPanelSelector.openInDialog(availableTopicPanels, wandora); // WAIT TILL CLOSED if(topicPanelSelector.wasAccepted()) { TopicPanel userSelectedTopicPanel = topicPanelSelector.getSelectedTopicPanel(); if(userSelectedTopicPanel != null) { userSelectedTopicPanel.open(topic); updateDockableTitle(userSelectedTopicPanel); if(topicPanelSelector.getRememberSelection()) { chainedTopicPanels.put(currentTopicPanel, userSelectedTopicPanel); } } } } } } } } revalidate(); repaint(); } @Override public void stop() { if(dockedTopicPanels != null && dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { if(tp != null) { tp.stop(); } } } if(control != null) { control.kill(); } openedTopic = null; dockedTopicPanels.clear(); chainedTopicPanels.clear(); } @Override public void refresh() throws TopicMapException { if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(Dockable dockable : dockedTopicPanels.keySet()) { TopicPanel topicPanel = dockedTopicPanels.get(dockable); if(topicPanel != null) { //System.out.println("refresh topic panel at docking frame panel"); topicPanel.refresh(); updateDockableTitle(topicPanel); } } } revalidate(); repaint(); } @Override public LocatorHistory getTopicHistory() { return null; } public TopicPanel getCurrentTopicPanel() { if(currentDockable != null) { TopicPanel tp = dockedTopicPanels.get(currentDockable); return tp; } return null; } @Override public boolean applyChanges() throws CancelledException, TopicMapException { boolean reply = false; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { if(tp != null) { reply = tp.applyChanges() || reply; } } } //revalidate(); //repaint(); return reply; } @Override public JPanel getGui() { return this; } @Override public Topic getTopic() throws TopicMapException { if(currentDockable != null) { TopicPanel tp = dockedTopicPanels.get(currentDockable); if(tp != null) { return tp.getTopic(); } } return openedTopic; } @Override public String getName() { return "Dockable frame panel"; } @Override public String getTitle() { return getName(); } @Override public Icon getIcon() { if(currentDockable != null) { TopicPanel tp = dockedTopicPanels.get(currentDockable); if(tp != null) { return tp.getIcon(); } } return null; } @Override public int getOrder() { return 1; } @Override public boolean noScroll(){ return false; } // ------------------------------------------------------------------------- @Override public JPopupMenu getViewPopupMenu() { return UIBox.makePopupMenu(getViewMenuStruct(), this); } @Override public JMenu getViewMenu() { return UIBox.makeMenu(getViewMenuStruct(), this); } @Override public Object[] getViewMenuStruct() { JMenu addMenu = new SimpleMenu("New panel", UIBox.getIcon("gui/icons/topic_panel_add.png")); List<List<Object>> availableTopicPanels = wandora.topicPanelManager.getAvailableTopicPanels(); List<Object> addTopicPanelMenuStruct = new ArrayList<>(); for(List<Object> panelData : availableTopicPanels) { try { Class panelClass = Class.forName((String) panelData.get(0)); if(!this.getClass().equals(panelClass)) { addTopicPanelMenuStruct.add( (String) panelData.get(1) ); addTopicPanelMenuStruct.add( (Icon) panelData.get(2) ); addTopicPanelMenuStruct.add( new AddDockable( panelClass ) ); } } catch(Exception e) {} } UIBox.attachMenu(addMenu, addTopicPanelMenuStruct.toArray(new Object[] {} ), wandora); //JMenu selectMenu = new SimpleMenu("Select", UIBox.getIcon("gui/icons/topic_panel_select.png")); //UIBox.attachMenu(selectMenu, getSelectMenuStruct(), wandora); //JMenu closeMenu = new SimpleMenu("Close", UIBox.getIcon("gui/icons/topic_panel_close.png")); //UIBox.attachMenu(closeMenu, getCloseMenuStruct(), wandora); //JMenu optionsMenu = new SimpleMenu("Options", UIBox.getIcon("gui/icons/topic_panel_options.png")); //UIBox.attachMenu(optionsMenu, getOptionsMenuStruct(), wandora); List<Object> struct = new ArrayList<>(); struct.add(addMenu); if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { struct.add("---"); for(Dockable dockable : dockedTopicPanels.keySet()) { TopicPanel tp = dockedTopicPanels.get(dockable); if(tp != null) { String label = tp.getName(); label = label + getAdditionalLabel(tp); JMenu topicPanelMenu = new SimpleMenu(label, tp.getIcon()); List<Object> subStruct = new ArrayList<>(); Object[] subMenuStruct = tp.getViewMenuStruct(); if(subMenuStruct != null) { if(subMenuStruct.length > 0) { for( Object subMenuItem : subMenuStruct ) { subStruct.add(subMenuItem); } subStruct.add("---"); } } subStruct.add( "Select" ); subStruct.add( UIBox.getIcon( "gui/icons/select_dockable.png" ) ); subStruct.add( new SelectDockable(dockable) ); if(dockable.equals(station.getFullScreen())) { subStruct.add( "Demaximize" ); subStruct.add( UIBox.getIcon( "gui/icons/demaximize_dockable.png" ) ); } else { subStruct.add( "Maximize" ); subStruct.add( UIBox.getIcon( "gui/icons/maximize_dockable.png" ) ); } subStruct.add( new MaximizeDockable(dockable) ); subStruct.add( "Close" ); subStruct.add( UIBox.getIcon("gui/icons/close_dockable.png") ); subStruct.add( new DeleteDockable(dockable) ); UIBox.attachMenu(topicPanelMenu, subStruct.toArray(), wandora); struct.add( topicPanelMenu ); } } struct.add("---"); struct.add("Close current"); struct.add(new DeleteCurrentDockable()); struct.add("Close all"); struct.add(new DeleteAllDockables()); } return struct.toArray(); } public Map<Dockable,TopicPanel> getDockedTopicPanels() { return (Map<Dockable,TopicPanel>) dockedTopicPanels.clone(); } private Object[] getCloseMenuStruct() { List<Object> struct = new ArrayList<>(); if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(Dockable dockable : dockedTopicPanels.keySet()) { TopicPanel tp = dockedTopicPanels.get(dockable); if(tp != null) { String label = "Close "+tp.getName(); label = label + getAdditionalLabel(tp); struct.add(label); struct.add( tp.getIcon() ); struct.add( new DeleteDockable(dockable) ); } } } else { struct.add("[Nothing to close]"); } return struct.toArray( new Object[] {} ); } private Object[] getSelectMenuStruct() { List<Object> struct = new ArrayList<>(); if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(Dockable dockable : dockedTopicPanels.keySet()) { TopicPanel tp = dockedTopicPanels.get(dockable); if(tp != null) { String label = "Select "+tp.getName(); label = label + getAdditionalLabel(tp); struct.add(label); struct.add( tp.getIcon() ); struct.add( new SelectDockable(dockable) ); } } } else { struct.add("[Nothing to select]"); } return struct.toArray( new Object[] {} ); } private Object[] getOptionsMenuStruct() { List<Object> struct = new ArrayList<>(); if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(Dockable dockable : dockedTopicPanels.keySet()) { TopicPanel tp = dockedTopicPanels.get(dockable); if(tp != null) { String label = "Configure "+tp.getName(); label = label + getAdditionalLabel(tp); SimpleMenu confMenu = new SimpleMenu(label); confMenu.setIcon(tp.getIcon()); UIBox.attachMenu(confMenu, tp.getViewMenuStruct(), wandora); struct.add( confMenu ); } } } else { struct.add("[Nothing to configure]"); } return struct.toArray( new Object[] {} ); } public static String getAdditionalLabel(TopicPanel tp) { String additionalLabel = ""; try { Topic t = tp.getTopic(); if(t != null) { additionalLabel = TopicToString.toString(t); if(additionalLabel.length() > 30) { additionalLabel = additionalLabel.substring(0,27) + "..."; } additionalLabel = " w " + additionalLabel; } } catch(Exception e) { // IGNORE } return additionalLabel; } // ------------------------------------------------------------------------- public void toggleVisibility(String componentName) { } @Override public void actionPerformed(ActionEvent e) { } public void addDockable(Object c, Topic topic) { addDockable((TopicPanel) c, topic); } public void addDockable(TopicPanel tp, Topic topic) { //System.out.append("Adding dockable "+tp); if(tp == null) return; Icon icon = tp.getIcon(); try { tp.init(); if(tp.supportsOpenTopic()) { if(topic == null) topic = openedTopic; tp.open(topic); } } catch(Exception e) { e.printStackTrace(); } JPanel wrapper = new JPanel(); wrapper.setLayout(new BorderLayout()); if(tp.noScroll()) { wrapper.add(tp.getGui(), BorderLayout.CENTER); } else { JScrollPane wrapperScroll = new SimpleScrollPane(tp.getGui()); wrapper.add(wrapperScroll, BorderLayout.CENTER); } WandoraDockable d = new WandoraDockable(wrapper, tp, tp.getTitle(), icon); d.setActionOffers(new WandoraDockActionSource(tp, this, control)); station.addDockable(d); dockedTopicPanels.put(d, tp); currentDockable = d; control.setFocusedDockable(currentDockable, true); wandora.topicPanelsChanged(); } public void deleteCurrentDockable() { if(currentDockable != null) { TopicPanel tp = dockedTopicPanels.get(currentDockable); if(tp != null) { tp.stop(); } dockedTopicPanels.remove(currentDockable); station.removeDockable(currentDockable); if(!dockedTopicPanels.isEmpty()) { currentDockable = dockedTopicPanels.keySet().iterator().next(); } else { currentDockable = null; } wandora.topicPanelsChanged(); } } public void deleteAllDockables() { if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(Dockable dockable : dockedTopicPanels.keySet()) { TopicPanel tp = dockedTopicPanels.get(dockable); if(tp != null) { tp.stop(); } station.removeDockable(dockable); } dockedTopicPanels.clear(); chainedTopicPanels.clear(); currentDockable = null; wandora.topicPanelsChanged(); } } public void deleteDockable(Dockable dockable) { TopicPanel tp = dockedTopicPanels.get(dockable); if(tp != null) { tp.stop(); } dockedTopicPanels.remove(dockable); station.removeDockable(dockable); if(!dockedTopicPanels.isEmpty()) { currentDockable = dockedTopicPanels.keySet().iterator().next(); } else { currentDockable = null; } wandora.topicPanelsChanged(); } public void selectDockable(Dockable dockable) { control.setFocusedDockable(dockable, true); } public void maximizeDockable(Dockable dockable) { if(dockable != null) { if(dockable.equals(station.getFullScreen())) { station.setFullScreen(null); try { if(currentDockable != null) { TopicPanel tp = dockedTopicPanels.get(dockable); if(tp != null) { tp.refresh(); } } } catch(Exception e) {} } else { station.setFullScreen(dockable); } } } public void changeTopicPanelInCurrentDockable(TopicPanel tp, Topic topic) { //System.out.append("changeTopicPanelInDockable "+tp); if(tp == null || currentDockable == null) return; try { if(currentDockable instanceof WandoraDockable) { try { if(tp.supportsOpenTopic()) { tp.open(topic); } } catch(Exception e) { e.printStackTrace(); } WandoraDockable currentWandoraDockable = (WandoraDockable) currentDockable; TopicPanel oldTopicPanel = currentWandoraDockable.getInnerTopicPanel(); oldTopicPanel.applyChanges(); oldTopicPanel.stop(); currentWandoraDockable.setTitleIcon(tp.getIcon()); currentWandoraDockable.setTitleText(tp.getTitle()); JPanel wrapper = (JPanel) currentWandoraDockable.getWrapper(); wrapper.removeAll(); JScrollPane wrapperScroll = new SimpleScrollPane(tp.getGui()); wrapper.add(wrapperScroll, BorderLayout.CENTER); dockedTopicPanels.put(currentDockable, tp); } control.setFocusedDockable(currentDockable, true); wandora.topicPanelsChanged(); wandora.refreshTopicPanelIcon(); } catch(CancelledException ce) { // PASS } catch(TopicMapException te) { te.printStackTrace(); } } // ----------------------------------------------- DockableFocusListener --- @Override public void dockableFocused(DockableFocusEvent dfe) { if(!dockedTopicPanels.isEmpty()) { if(dfe.getNewFocusOwner() != null) { currentDockable = dfe.getNewFocusOwner(); if(wandora != null) { wandora.refreshInfoFields(); } } } } // ----------------------------------------------------- RefreshListener --- @Override public void doRefresh() throws TopicMapException { refresh(); } // -------------------------------------------------- Topic map listener --- private boolean skipTopicMapActions = false; @Override public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.topicSubjectIdentifierChanged(t, added, removed); } } } @Override public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.topicBaseNameChanged(t, newName, oldName); } } } @Override public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.topicTypeChanged(t, added, removed); } } } @Override public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.topicVariantChanged(t, scope, newName, oldName); } } } @Override public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.topicDataChanged(t, type, version, newValue, oldValue); } } } @Override public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.topicSubjectLocatorChanged(t, newLocator, oldLocator); } } } @Override public void topicRemoved(Topic t) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.topicRemoved(t); } } } @Override public void topicChanged(Topic t) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.topicChanged(t); } } } @Override public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.associationTypeChanged(a, newType, oldType); } } } @Override public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.associationPlayerChanged(a, role, newPlayer, oldPlayer); } } } @Override public void associationRemoved(Association a) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.associationRemoved(a); } } } @Override public void associationChanged(Association a) throws TopicMapException { if(skipTopicMapActions) return; if(dockedTopicPanels != null && !dockedTopicPanels.isEmpty()) { for(TopicPanel tp : dockedTopicPanels.values()) { tp.associationChanged(a); } } } // -------------------------------------------------- Component listener --- @Override public void componentResized(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentMoved(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentShown(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentHidden(ComponentEvent e) { handleComponentEvent(e); } private void handleComponentEvent(ComponentEvent e) { try { Dimension size = this.getParent().getParent().getSize(); setPreferredSize(size); setMinimumSize(size); setSize(size); //revalidate(); //repaint(); } catch(Exception ex) { // SKIP } } // --------------------------------------------------- DockableListener ---- @Override public void titleBound(Dockable dckbl, DockTitle dt) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void titleUnbound(Dockable dckbl, DockTitle dt) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void titleTextChanged(Dockable dckbl, String string, String string1) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void titleIconChanged(Dockable dckbl, Icon icon, Icon icon1) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void titleToolTipChanged(Dockable dckbl, String string, String string1) { throw new UnsupportedOperationException("Not supported yet."); } @Override public void titleExchanged(Dockable dckbl, DockTitle dt) { throw new UnsupportedOperationException("Not supported yet."); } // ------------------------------------------------------------------------- // ------------------------------------------------------ DRAG AND DROP ---- // ------------------------------------------------------------------------- private int orders = 0; @Override public void dragEnter(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { } @Override public void dragExit(java.awt.dnd.DropTargetEvent dropTargetEvent) { } @Override public void dragOver(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { } private void processImage(Image image) throws Exception { SimpleFileExtractor extractor = new SimpleFileExtractor(); DataURL dataUrl = new DataURL(image); extractor.setForceContent( dataUrl.toExternalForm(Base64.DONT_BREAK_LINES) ); ActionEvent fakeEvent = new ActionEvent(wandora, 0, "merge"); extractor.execute(wandora, fakeEvent); } private void processFileList(java.util.List<File> files) throws Exception { ArrayList<WandoraTool> importTools = new ArrayList<>(); boolean yesToAll = false; for(File file : files) { ArrayList<WandoraTool> importToolsForFile = WandoraToolManager.getImportTools(file, orders); if(importToolsForFile != null && !importToolsForFile.isEmpty()) { importTools.addAll(importToolsForFile); } else { if(yesToAll) { SimpleFileExtractor extractor = new SimpleFileExtractor(); extractor.setForceFiles(new File[] { file } ); importTools.add(extractor); } else { int a = WandoraOptionPane.showConfirmDialog(wandora, "Extract the dropped file with Simple File Extractor?", "Extract instead of import?", WandoraOptionPane.YES_TO_ALL_NO_CANCEL_OPTION); if(a == WandoraOptionPane.YES_OPTION || a == WandoraOptionPane.YES_TO_ALL_OPTION) { SimpleFileExtractor extractor = new SimpleFileExtractor(); extractor.setForceFiles(new File[] { file } ); importTools.add(extractor); } if(a == WandoraOptionPane.YES_TO_ALL_OPTION) { yesToAll = true; } if(a == WandoraOptionPane.CANCEL_OPTION || a == WandoraOptionPane.CLOSED_OPTION) { return; } } } } //System.out.println("drop context == " + dropContext); ActionEvent fakeEvent = new ActionEvent(wandora, 0, "merge"); ChainExecuter chainExecuter = new ChainExecuter(importTools); chainExecuter.execute(wandora, fakeEvent); } @Override public void drop(java.awt.dnd.DropTargetDropEvent e) { try { final Image image = DnDBox.acceptImage(e); if(image != null) { Thread dropThread = new Thread() { public void run() { try { processImage(image); } catch(Exception e) { e.printStackTrace(); } catch(Error err) { err.printStackTrace(); } } }; dropThread.start(); } else { final java.util.List<File> files = DnDBox.acceptFileList(e); if(files != null) { if(!files.isEmpty()) { Thread dropThread = new Thread() { public void run() { try { processFileList(files); } catch(Exception e) { e.printStackTrace(); } catch(Error err) { err.printStackTrace(); } } }; dropThread.start(); } } else { System.out.println("Drop rejected! Wrong data flavor!"); e.rejectDrop(); } } } catch(Exception ex){ ex.printStackTrace(); } catch(Error err) { err.printStackTrace(); } this.setBorder(null); } @Override public void dropActionChanged(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { } @Override public void dragGestureRecognized(java.awt.dnd.DragGestureEvent dragGestureEvent) { } // ------------------------------------------------------------------------- protected TopicPanel getDefaultPanel() { try { Options options = wandora.getOptions(); String defaultPanelClassName = options.get("gui.topicPanels.defaultPanel"); if(defaultPanelClassName != null) { Class topicPanelClass = Class.forName(defaultPanelClassName); if(TopicPanel.class.isAssignableFrom(topicPanelClass) && !Modifier.isAbstract(topicPanelClass.getModifiers()) && !Modifier.isInterface(topicPanelClass.getModifiers()) ){ return (TopicPanel) topicPanelClass.newInstance(); } } } catch(Exception e) { e.printStackTrace(); } // Backup plan if default panel fails. return new TraditionalTopicPanel(); } }
43,017
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TreeMapTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/TreeMapTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * TreeMapTopicPanel.java * * Created on Oct 19, 2011, 8:12:21 PM */ package org.wandora.application.gui.topicpanels; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.Collection; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.RefreshListener; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.topicpanels.treemap.TreeMapComponent; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; /** * * @author akivela */ public class TreeMapTopicPanel extends javax.swing.JPanel implements TopicMapListener, RefreshListener, TopicPanel, ActionListener, ComponentListener { private static final long serialVersionUID = 1L; private Topic topic; private String topicSI; private TreeMapComponent treeMapComponent = null; /** Creates new form TreeMapTopicPanel */ public TreeMapTopicPanel() { } @Override public void init() { initComponents(); treeMapComponent = new TreeMapComponent(this); contentPanel.add(treeMapComponent, BorderLayout.CENTER); //contentPanel.addComponentListener(this); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; contentPanel = new javax.swing.JPanel(); removedTopicMessage = new javax.swing.JPanel(); removedTopicMessageLabel = new javax.swing.JLabel(); setMinimumSize(new java.awt.Dimension(400, 300)); setLayout(new java.awt.GridBagLayout()); contentPanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(contentPanel, gridBagConstraints); removedTopicMessage.setBackground(new java.awt.Color(255, 255, 255)); removedTopicMessage.setLayout(new java.awt.GridBagLayout()); removedTopicMessageLabel.setText("<html>Topic is either merged or removed and can not be viewed!</html>"); removedTopicMessage.add(removedTopicMessageLabel, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(removedTopicMessage, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel contentPanel; private javax.swing.JPanel removedTopicMessage; private javax.swing.JLabel removedTopicMessageLabel; // End of variables declaration//GEN-END:variables @Override public boolean supportsOpenTopic() { return true; } @Override public void open(Topic topic) throws TopicMapException { try { this.topic = topic; this.topicSI = topic.getOneSubjectIdentifier().toExternalForm(); } catch(Exception e) { e.printStackTrace(); } doRefresh(); } public void clearCaches() { if(treeMapComponent != null) { treeMapComponent.clearCaches(); } } // -------------------------------------------------- TOPIC MAP LISTENER --- @Override public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void topicRemoved(Topic t) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void topicChanged(Topic t) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void associationRemoved(Association a) throws TopicMapException { clearCaches(); doRefresh(); } @Override public void associationChanged(Association a) throws TopicMapException { clearCaches(); doRefresh(); } // ------------------------------------------------------------------------- @Override public void doRefresh() throws TopicMapException { try { topic=Wandora.getWandora().getTopicMap().getTopic(topicSI); if(topic==null || topic.isRemoved()) { System.out.println("Topic is null or removed!"); contentPanel.setVisible(false); removedTopicMessage.setVisible(true); return; } else { contentPanel.setVisible(true); removedTopicMessage.setVisible(false); } } catch(Exception e){ e.printStackTrace(); System.out.println("Topic is null or removed!"); contentPanel.setVisible(false); removedTopicMessage.setVisible(true); return; } treeMapComponent.initialize(topic); treeMapComponent.repaint(); revalidate(); repaint(); } @Override public void stop() { // NOTHING TO STOP! } @Override public void refresh() throws TopicMapException { doRefresh(); } @Override public boolean applyChanges() throws CancelledException, TopicMapException { return true; } @Override public JPanel getGui() { return this; } @Override public Topic getTopic() throws TopicMapException { return topic; } @Override public LocatorHistory getTopicHistory() { return null; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_panel_treemap.png"); } @Override public boolean noScroll(){ return false; } @Override public JPopupMenu getViewPopupMenu() { return UIBox.makePopupMenu(getViewMenuStruct(), this); } @Override public JMenu getViewMenu() { return UIBox.makeMenu(getViewMenuStruct(), this); } @Override public Object[] getViewMenuStruct() { int d = treeMapComponent.getIterationDepth(); Object[] menuStructure = new Object[] { "Set depth to 1", (d == 1 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), this, "Set depth to 2", (d == 2 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), this, "Set depth to 3", (d == 3 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), this, "Set depth to 4", (d == 4 ? UIBox.getIcon("gui/icons/checkbox_selected.png") : UIBox.getIcon("gui/icons/checkbox.png")), this, //"---", //"Reset zoom", this, }; return menuStructure; } public void toggleVisibility(String componentName) { throw new UnsupportedOperationException("Not supported yet."); } @Override public String getName(){ return "Treemap"; } @Override public String getTitle() { if(topic != null) return TopicToString.toString(topic); else return ""; } @Override public int getOrder() { return 200; } @Override public void actionPerformed(ActionEvent e) { if(e == null) return; String ac = e.getActionCommand(); if("Set depth to 1".equals(ac)) { treeMapComponent.setIterationDepth(1); Wandora.getWandora().topicPanelsChanged(); } if("Set depth to 2".equals(ac)) { treeMapComponent.setIterationDepth(2); Wandora.getWandora().topicPanelsChanged(); } else if("Set depth to 3".equals(ac)) { treeMapComponent.setIterationDepth(3); Wandora.getWandora().topicPanelsChanged(); } else if("Set depth to 4".equals(ac)) { treeMapComponent.setIterationDepth(4); Wandora.getWandora().topicPanelsChanged(); } else if("Reset zoom".equals(ac)) { treeMapComponent.resetZoom(); } } // ------------------------------------------------------------------------- @Override public void componentResized(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentMoved(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentShown(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentHidden(ComponentEvent e) { handleComponentEvent(e); } private void handleComponentEvent(ComponentEvent e) { if(treeMapComponent != null) treeMapComponent.setSize(getWidth(), getHeight()); } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- }
12,277
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TreeTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/TreeTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://wandora.org * * Copyright (C) 2004-2023 Wandora Team * * 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 org.wandora.application.gui.topicpanels; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collection; import java.util.HashSet; import java.util.Set; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.tree.TopicTree; import org.wandora.application.gui.tree.TopicTreeConfigPanel; import org.wandora.application.gui.tree.TopicTreePanel; import org.wandora.application.gui.tree.TopicTreeRelation; import org.wandora.application.gui.tree.TopicTreeRelationsEditor; import org.wandora.exceptions.OpenTopicNotSupportedException; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; /** * * @author akivela */ public class TreeTopicPanel extends javax.swing.JPanel implements ActionListener, TopicPanel { private static final long serialVersionUID = 1L; private String title = "Tree"; private Options options = null; private TopicTreePanel topicTreePanel = null; private String rootSubject = TMBox.WANDORACLASS_SI; private Set<String> selectedRelations = null; private TopicTreeRelation[] allRelations = null; private Topic openedTopic = null; /** * Creates new form TreeTopicPanel */ public TreeTopicPanel() { Wandora wandora = Wandora.getWandora(); this.options = wandora.getOptions(); initComponents(); } @Override public void init() { try { allRelations = TopicTreeRelationsEditor.readRelationTypes(); selectedRelations = new HashSet<>(); for(TopicTreeRelation allRelation : allRelations) { selectedRelations.add(allRelation.name); } treeContainerPanel.removeAll(); Wandora wandora = Wandora.getWandora(); topicTreePanel = new TopicTreePanel(rootSubject, wandora, selectedRelations, allRelations); treeContainerPanel.add(topicTreePanel, BorderLayout.CENTER); revalidate(); } catch(Exception e) { e.printStackTrace(); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; treeContainerPanel = new javax.swing.JPanel(); setLayout(new java.awt.GridBagLayout()); treeContainerPanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(treeContainerPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel treeContainerPanel; // End of variables declaration//GEN-END:variables @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if(cmd != null) { if("Set root topic...".equalsIgnoreCase(cmd)) { try { Wandora wandora = Wandora.getWandora(); Topic t = wandora.showTopicFinder(); if(t != null) { setRootTopic(t); } } catch(Exception ex) { ex.printStackTrace(); } } else if("Configure...".equalsIgnoreCase(cmd)) { configure(); } else { System.out.println("Unprosessed action captured '"+cmd+"' in TreeTopicPanel."); } } } public void configure() { try { Wandora wandora = Wandora.getWandora(); JDialog jd=new JDialog(wandora, true); jd.setTitle("Configure topic tree"); allRelations = TopicTreeRelationsEditor.readRelationTypes(); TopicTreeConfigPanel configurationPanel = new TopicTreeConfigPanel(allRelations, selectedRelations, rootSubject, getTitle(), jd, wandora); jd.add(configurationPanel); jd.setSize(500,400); wandora.centerWindow(jd); jd.setVisible(true); if(configurationPanel.wasCancelled()) return; title = configurationPanel.getTreeName(); rootSubject = configurationPanel.getRoot(); selectedRelations = configurationPanel.getSelectedRelations(); allRelations = TopicTreeRelationsEditor.readRelationTypes(); // Important, may have been altered by the configurationPanel. topicTreePanel.setModel(rootSubject, selectedRelations, allRelations); topicTreePanel.refresh(); revalidate(); } catch(Exception e) { e.printStackTrace(); } } @Override public boolean supportsOpenTopic() { return false; } @Override public void open(Topic topic) throws TopicMapException, OpenTopicNotSupportedException { // Notice, this TopicPanel doesn't support open topic. openedTopic = topic; } @Override public void stop() { treeContainerPanel.removeAll(); topicTreePanel = null; } @Override public void refresh() throws TopicMapException { if(topicTreePanel != null) { topicTreePanel.refresh(); topicTreePanel.repaint(); } revalidate(); } @Override public boolean applyChanges() throws CancelledException, TopicMapException { return true; } @Override public JPanel getGui() { return this; } @Override public Topic getTopic() throws TopicMapException { if(topicTreePanel != null) { TopicTree tree = topicTreePanel.getTopicTree(); if(tree != null && !tree.isBroken()) { Topic t = tree.getSelection(); return t; } } return openedTopic; } @Override public String getName(){ return title; } @Override public String getTitle() { return title; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_panel_tree.png"); } @Override public boolean noScroll(){ return false; } @Override public int getOrder() { return 30; } @Override public Object[] getViewMenuStruct() { return new Object[] { // If you change these, update method actionPerformed too "Set root topic...", this /* as an ActionListener */, "Configure...", this /* as an ActionListener */, }; } @Override public JMenu getViewMenu() { return UIBox.makeMenu(getViewMenuStruct(), this); } @Override public JPopupMenu getViewPopupMenu() { return UIBox.makePopupMenu(getViewMenuStruct(), this); } @Override public LocatorHistory getTopicHistory() { return null; } public void setRootTopic(Topic newRoot) { try { if(newRoot != null && !newRoot.isRemoved()) { rootSubject = newRoot.getOneSubjectIdentifier().toExternalForm(); init(); } } catch(Exception e) { e.printStackTrace(); } } // ---------------------------------------------------- TopicMapListener --- @Override public void topicSubjectIdentifierChanged(Topic t,Locator added,Locator removed) throws TopicMapException { topicTreePanel.topicSubjectIdentifierChanged(t,added,removed); } @Override public void topicBaseNameChanged(Topic t,String newName,String oldName) throws TopicMapException { topicTreePanel.topicBaseNameChanged(t,newName,oldName); } @Override public void topicTypeChanged(Topic t,Topic added,Topic removed) throws TopicMapException { topicTreePanel.topicTypeChanged(t,added,removed); } @Override public void topicVariantChanged(Topic t,Collection<Topic> scope,String newName,String oldName) throws TopicMapException { topicTreePanel.topicVariantChanged(t,scope,newName,oldName); } @Override public void topicDataChanged(Topic t,Topic type,Topic version,String newValue,String oldValue) throws TopicMapException { topicTreePanel.topicDataChanged(t,type,version,newValue,oldValue); } @Override public void topicSubjectLocatorChanged(Topic t,Locator newLocator,Locator oldLocator) throws TopicMapException { topicTreePanel.topicSubjectLocatorChanged(t,newLocator,oldLocator); } @Override public void topicRemoved(Topic t) throws TopicMapException { topicTreePanel.topicRemoved(t); } @Override public void topicChanged(Topic t) throws TopicMapException { topicTreePanel.topicChanged(t); } @Override public void associationTypeChanged(Association a,Topic newType,Topic oldType) throws TopicMapException { topicTreePanel.associationTypeChanged(a,newType,oldType); } @Override public void associationPlayerChanged(Association a,Topic role,Topic newPlayer,Topic oldPlayer) throws TopicMapException { topicTreePanel.associationPlayerChanged(a,role,newPlayer,oldPlayer); } @Override public void associationRemoved(Association a) throws TopicMapException { topicTreePanel.associationRemoved(a); } @Override public void associationChanged(Association a) throws TopicMapException { topicTreePanel.associationChanged(a); } // --------------------------------------------------- /TopicMapListener --- }
11,598
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/topicpanels/RTopicPanel.java
/* * WANDORA * Knowledge Extraction, Management, and Publishing Application * http://www.wandora.org/ * * Copyright (C) 2004-2023 Wandora Team * * 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/>. * * * * RTopicPanel.java * * Created on 21.9.2011, 14:44:26 */ package org.wandora.application.gui.topicpanels; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.io.File; import java.util.Collection; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JMenu; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.KeyStroke; import javax.swing.text.DefaultEditorKit; import org.apache.commons.io.FileUtils; import org.wandora.application.CancelledException; import org.wandora.application.LocatorHistory; import org.wandora.application.RefreshListener; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleCheckBox; import org.wandora.application.gui.simple.SimpleField; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleRadioButton; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.application.gui.simple.SimpleTextConsole; import org.wandora.application.gui.simple.SimpleTextConsoleListener; import org.wandora.application.gui.simple.SimpleTextPane; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.r.RBridge; import org.wandora.application.tools.r.RBridgeListener; import org.wandora.topicmap.Association; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapListener; import org.wandora.utils.IObox; import org.wandora.utils.Options; //import jsyntaxpane.DefaultSyntaxKit; import de.sciss.syntaxpane.DefaultSyntaxKit; /** * * @author akivela */ public class RTopicPanel extends javax.swing.JPanel implements TopicMapListener, RefreshListener, TopicPanel, ActionListener, ComponentListener, SimpleTextConsoleListener, RBridgeListener { private static final long serialVersionUID = 1L; public boolean USE_LOCAL_OPTIONS = true; public boolean SAVE_SKETCH_TO_GLOBAL_OPTIONS = true; public static final int NO_SOURCE = 0; public static final int OCCURRENCE_SOURCE = 1; public static final int FILE_SOURCE = 2; public static final int DONT_AUTORUN = 0; public static final int AUTORUN_OCCURRENCE = 1; public static final int AUTORUN_SCRIPT_IN_EDITOR = 2; public static final int AUTORUN_FILE = 4; private static int autorun = 0; private static String autorunScriptFile = ""; private static boolean autoloadFromOccurrence = false; private int currentScriptSource = NO_SOURCE; private String currentScriptFile = null; private String currentScript = null; private static final String R_OCCURRENCE_TYPE = "http://www.r-project.org"; private static final String optionsPrefix = "options.rpanel"; private static final String scriptPath = "resources/r/"; private Options options = null; private TopicMap tm; private Topic rootTopic; private boolean isGuiInitialized = false; private RBridge rBridge = null; private JDialog optionsDialog = null; private JFileChooser fc = null; private JPopupMenu menu = null; private static final String defaultMessage = "# \n"+ "# Welcome to Wandora's R topic panel!\n"+ "# \n"+ "# R topic panel is used to write and execute R language scripts.\n"+ "# R script can access the topic map in Wandora via Wandora's Java API.\n"+ "# \n"+ "# Learn R language and Wandora API here\n"+ "# http://www.r-project.org/ \n"+ "# http://wandora.org/api/ \n"+ "#\n"; private String[] openScriptMenuStruct = new String[] { "Open script from occurrence", "Open script from file..." }; private String[] saveScriptMenuStruct = new String[] { "Save script to occurrence", "Save script to file..." }; /** Creates new form RTopicPanel */ public RTopicPanel() { } @Override public void init() { Wandora wandora = Wandora.getWandora(); tm = wandora.getTopicMap(); if(options == null) { if(USE_LOCAL_OPTIONS) { options = new Options(wandora.getOptions()); } else { options = wandora.getOptions(); } } initComponents(); this.addComponentListener(this); DefaultSyntaxKit.initKit(); rEditor.setContentType("text/plain"); KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK); rEditor.getInputMap().put(key, "saveOperation"); Action saveOperation = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { saveScript(); } }; rEditor.getActionMap().put("saveOperation", saveOperation); rEditor.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "\n"); rBridge = RBridge.getRBridge(); rBridge.addRBridgeListener(this); fc = new JFileChooser(); fc.setCurrentDirectory(new File(scriptPath)); readOptions(); if(currentScript != null) { rEditor.setText(currentScript); } else { rEditor.setText(defaultMessage); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; optionsPanel = new javax.swing.JPanel(); optionsTabbedPane = new SimpleTabbedPane(); autoloadOptionsPanel = new javax.swing.JPanel(); autoloadPanel = new javax.swing.JPanel(); autoloadLabel = new SimpleLabel(); autoloadCheckBox = new SimpleCheckBox(); autorunOptionsPanel = new javax.swing.JPanel(); autorunOptionsPanelInner = new javax.swing.JPanel(); optionsLabel = new SimpleLabel(); noAutoRunRadioButton = new SimpleRadioButton(); autoRunOccurrenceRadioButton = new SimpleRadioButton(); autoRunScriptInEditorRadioButton = new SimpleRadioButton(); jPanel1 = new javax.swing.JPanel(); autoRunFileRadioButton = new SimpleRadioButton(); autoRunFileTextField = new SimpleField(); autoRunFileBrowseButton = new SimpleButton(); optionsButtonPanel1 = new javax.swing.JPanel(); optionsOkButton = new SimpleButton(); autoRunSource = new javax.swing.ButtonGroup(); tabPanel = new SimpleTabbedPane(); editorPanel = new javax.swing.JPanel(); editorScroller = new SimpleScrollPane(); rEditor = new SimpleTextPane(); codeBottomBar = new javax.swing.JPanel(); runButtonPanel = new javax.swing.JPanel(); executeBtn = new SimpleButton(); fillerPanel = new javax.swing.JPanel(); optionsButtonPanel = new javax.swing.JPanel(); newBtn = new SimpleButton(); openBtn = new SimpleButton(); saveBtn = new SimpleButton(); jSeparator1 = new javax.swing.JSeparator(); optionsBtn = new SimpleButton(); consolePanel = new javax.swing.JPanel(); rConsole = new javax.swing.JPanel(); rConsoleScrollPane = new javax.swing.JScrollPane(); rConsoleTextPane = new SimpleTextConsole(this); optionsPanel.setLayout(new java.awt.GridBagLayout()); autoloadOptionsPanel.setLayout(new java.awt.GridBagLayout()); autoloadPanel.setLayout(new java.awt.GridBagLayout()); autoloadLabel.setText("<html>Whether or not to load script automatically from occurrence.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0); autoloadPanel.add(autoloadLabel, gridBagConstraints); autoloadCheckBox.setText("Autoload script from occurrence"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; autoloadPanel.add(autoloadCheckBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(16, 16, 16, 16); autoloadOptionsPanel.add(autoloadPanel, gridBagConstraints); optionsTabbedPane.addTab("Autoload", autoloadOptionsPanel); autorunOptionsPanel.setLayout(new java.awt.GridBagLayout()); autorunOptionsPanelInner.setLayout(new java.awt.GridBagLayout()); optionsLabel.setText("<html>R topic panel autorun options control automated script execution.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0); autorunOptionsPanelInner.add(optionsLabel, gridBagConstraints); autoRunSource.add(noAutoRunRadioButton); noAutoRunRadioButton.setText("Don't autorun"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; autorunOptionsPanelInner.add(noAutoRunRadioButton, gridBagConstraints); autoRunSource.add(autoRunOccurrenceRadioButton); autoRunOccurrenceRadioButton.setText("Autorun script in occurrence"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; autorunOptionsPanelInner.add(autoRunOccurrenceRadioButton, gridBagConstraints); autoRunSource.add(autoRunScriptInEditorRadioButton); autoRunScriptInEditorRadioButton.setText("Autorun script in editor"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; autorunOptionsPanelInner.add(autoRunScriptInEditorRadioButton, gridBagConstraints); jPanel1.setLayout(new java.awt.GridBagLayout()); autoRunSource.add(autoRunFileRadioButton); autoRunFileRadioButton.setText("Autorun script in file"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; jPanel1.add(autoRunFileRadioButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; jPanel1.add(autoRunFileTextField, gridBagConstraints); autoRunFileBrowseButton.setText("Browse"); autoRunFileBrowseButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); autoRunFileBrowseButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { autoRunFileBrowseButtonMouseReleased(evt); } }); jPanel1.add(autoRunFileBrowseButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; autorunOptionsPanelInner.add(jPanel1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(16, 16, 16, 16); autorunOptionsPanel.add(autorunOptionsPanelInner, gridBagConstraints); optionsTabbedPane.addTab("Autorun", autorunOptionsPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; optionsPanel.add(optionsTabbedPane, gridBagConstraints); optionsButtonPanel1.setLayout(new java.awt.GridBagLayout()); optionsOkButton.setText("OK"); optionsOkButton.setMargin(new java.awt.Insets(1, 4, 1, 4)); optionsOkButton.setMinimumSize(new java.awt.Dimension(65, 21)); optionsOkButton.setPreferredSize(new java.awt.Dimension(65, 21)); optionsOkButton.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { optionsOkButtonMouseReleased(evt); } }); optionsButtonPanel1.add(optionsOkButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); optionsPanel.add(optionsButtonPanel1, gridBagConstraints); setLayout(new java.awt.BorderLayout()); tabPanel.setMinimumSize(new java.awt.Dimension(300, 74)); tabPanel.setPreferredSize(new java.awt.Dimension(300, 53)); editorPanel.setMinimumSize(new java.awt.Dimension(200, 46)); editorPanel.setPreferredSize(new java.awt.Dimension(200, 25)); editorPanel.setLayout(new java.awt.GridBagLayout()); rEditor.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N editorScroller.setViewportView(rEditor); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; editorPanel.add(editorScroller, gridBagConstraints); codeBottomBar.setMinimumSize(new java.awt.Dimension(405, 23)); codeBottomBar.setPreferredSize(new java.awt.Dimension(410, 23)); codeBottomBar.setLayout(new java.awt.GridBagLayout()); runButtonPanel.setLayout(new java.awt.GridBagLayout()); executeBtn.setText("Run"); executeBtn.setMargin(new java.awt.Insets(2, 6, 2, 6)); executeBtn.setMaximumSize(new java.awt.Dimension(75, 21)); executeBtn.setMinimumSize(new java.awt.Dimension(75, 21)); executeBtn.setPreferredSize(new java.awt.Dimension(75, 21)); executeBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { executeBtnexecuteOnMouseRelease(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); runButtonPanel.add(executeBtn, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; codeBottomBar.add(runButtonPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; codeBottomBar.add(fillerPanel, gridBagConstraints); optionsButtonPanel.setLayout(new java.awt.GridBagLayout()); newBtn.setText("New"); newBtn.setMaximumSize(new java.awt.Dimension(75, 21)); newBtn.setMinimumSize(new java.awt.Dimension(75, 21)); newBtn.setPreferredSize(new java.awt.Dimension(75, 21)); newBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { newBtnMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 2, 0, 2); optionsButtonPanel.add(newBtn, gridBagConstraints); openBtn.setText("Open"); openBtn.setMaximumSize(new java.awt.Dimension(75, 21)); openBtn.setMinimumSize(new java.awt.Dimension(75, 21)); openBtn.setPreferredSize(new java.awt.Dimension(75, 21)); openBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { openBtnMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { openBtnMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); optionsButtonPanel.add(openBtn, gridBagConstraints); saveBtn.setText("Save"); saveBtn.setMargin(new java.awt.Insets(2, 4, 2, 4)); saveBtn.setMaximumSize(new java.awt.Dimension(75, 21)); saveBtn.setMinimumSize(new java.awt.Dimension(75, 21)); saveBtn.setPreferredSize(new java.awt.Dimension(75, 21)); saveBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { saveBtnMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { saveBtnMouseReleased(evt); } }); optionsButtonPanel.add(saveBtn, new java.awt.GridBagConstraints()); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4); optionsButtonPanel.add(jSeparator1, gridBagConstraints); optionsBtn.setText("Options"); optionsBtn.setMaximumSize(new java.awt.Dimension(75, 21)); optionsBtn.setMinimumSize(new java.awt.Dimension(75, 21)); optionsBtn.setPreferredSize(new java.awt.Dimension(75, 21)); optionsBtn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { optionsBtnMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2); optionsButtonPanel.add(optionsBtn, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START; gridBagConstraints.insets = new java.awt.Insets(1, 0, 1, 0); codeBottomBar.add(optionsButtonPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; editorPanel.add(codeBottomBar, gridBagConstraints); tabPanel.addTab("Script", editorPanel); consolePanel.setLayout(new java.awt.GridBagLayout()); rConsole.setLayout(new java.awt.GridBagLayout()); rConsoleScrollPane.setViewportView(rConsoleTextPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; rConsole.add(rConsoleScrollPane, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; consolePanel.add(rConsole, gridBagConstraints); tabPanel.addTab("R console", consolePanel); add(tabPanel, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void executeBtnexecuteOnMouseRelease(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_executeBtnexecuteOnMouseRelease tabPanel.setSelectedComponent(consolePanel); executeScriptInEditor(); }//GEN-LAST:event_executeBtnexecuteOnMouseRelease private void newBtnMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_newBtnMouseReleased newScript(); invalidate(); }//GEN-LAST:event_newBtnMouseReleased private void saveBtnMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveBtnMouseReleased }//GEN-LAST:event_saveBtnMouseReleased private void optionsOkButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_optionsOkButtonMouseReleased if(optionsDialog != null) { optionsDialog.setVisible(false); } if(noAutoRunRadioButton.isSelected()) autorun = DONT_AUTORUN; else if(autoRunOccurrenceRadioButton.isSelected()) autorun = AUTORUN_OCCURRENCE; else if(autoRunScriptInEditorRadioButton.isSelected()) autorun = AUTORUN_SCRIPT_IN_EDITOR; else if(autoRunFileRadioButton.isSelected()) autorun = AUTORUN_FILE; autorunScriptFile = autoRunFileTextField.getText(); autoloadFromOccurrence = autoloadCheckBox.isSelected(); if(options != null) { options.put(optionsPrefix+".autorun", ""+autorun); options.put(optionsPrefix+".autorunScriptFile", autorunScriptFile); options.put(optionsPrefix+".autoload", Boolean.toString(autoloadFromOccurrence)); } }//GEN-LAST:event_optionsOkButtonMouseReleased private void optionsBtnMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_optionsBtnMouseReleased openOptionsDialog(); }//GEN-LAST:event_optionsBtnMouseReleased private void openBtnMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_openBtnMouseReleased }//GEN-LAST:event_openBtnMouseReleased private void openBtnMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_openBtnMousePressed showMenu(openScriptMenuStruct, evt); }//GEN-LAST:event_openBtnMousePressed private void saveBtnMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveBtnMousePressed showMenu(saveScriptMenuStruct, evt); }//GEN-LAST:event_saveBtnMousePressed private void autoRunFileBrowseButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_autoRunFileBrowseButtonMouseReleased fc.setDialogType(JFileChooser.OPEN_DIALOG); fc.setDialogTitle("Select R Script"); int answer = fc.showDialog(Wandora.getWandora(), "Select"); if(answer == JFileChooser.APPROVE_OPTION) { File f = fc.getSelectedFile(); if(f != null) { autoRunFileTextField.setText(f.getAbsolutePath()); autoRunFileRadioButton.setSelected(true); } } }//GEN-LAST:event_autoRunFileBrowseButtonMouseReleased // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton autoRunFileBrowseButton; private javax.swing.JRadioButton autoRunFileRadioButton; private javax.swing.JTextField autoRunFileTextField; private javax.swing.JRadioButton autoRunOccurrenceRadioButton; private javax.swing.JRadioButton autoRunScriptInEditorRadioButton; private javax.swing.ButtonGroup autoRunSource; private javax.swing.JCheckBox autoloadCheckBox; private javax.swing.JLabel autoloadLabel; private javax.swing.JPanel autoloadOptionsPanel; private javax.swing.JPanel autoloadPanel; private javax.swing.JPanel autorunOptionsPanel; private javax.swing.JPanel autorunOptionsPanelInner; private javax.swing.JPanel codeBottomBar; private javax.swing.JPanel consolePanel; private javax.swing.JPanel editorPanel; private javax.swing.JScrollPane editorScroller; private javax.swing.JButton executeBtn; private javax.swing.JPanel fillerPanel; private javax.swing.JPanel jPanel1; private javax.swing.JSeparator jSeparator1; private javax.swing.JButton newBtn; private javax.swing.JRadioButton noAutoRunRadioButton; private javax.swing.JButton openBtn; private javax.swing.JButton optionsBtn; private javax.swing.JPanel optionsButtonPanel; private javax.swing.JPanel optionsButtonPanel1; private javax.swing.JLabel optionsLabel; private javax.swing.JButton optionsOkButton; private javax.swing.JPanel optionsPanel; private javax.swing.JTabbedPane optionsTabbedPane; private javax.swing.JPanel rConsole; private javax.swing.JScrollPane rConsoleScrollPane; private javax.swing.JTextPane rConsoleTextPane; private javax.swing.JEditorPane rEditor; private javax.swing.JPanel runButtonPanel; private javax.swing.JButton saveBtn; private javax.swing.JTabbedPane tabPanel; // End of variables declaration//GEN-END:variables private void openOptionsDialog() { optionsDialog = new JDialog(Wandora.getWandora(), true); optionsDialog.setSize(500,270); optionsDialog.add(optionsPanel); optionsDialog.setTitle("R topic panel options"); Wandora.getWandora().centerWindow(optionsDialog); optionsDialog.setVisible(true); } public void showMenu(String[] struct, MouseEvent evt) { menu = UIBox.makePopupMenu(struct, this); menu.setLocation(evt.getXOnScreen()-2, evt.getYOnScreen()-2); menu.show(evt.getComponent(), evt.getX()-2, evt.getY()-2); } @Override public void doRefresh() throws TopicMapException { } @Override public boolean supportsOpenTopic() { return true; } @Override public void open(Topic topic) throws TopicMapException { rootTopic = topic; if(autoloadFromOccurrence) { rEditor.setText(getROccurrence()); } autorun(); } private void readOptions() { autoloadFromOccurrence = options.getBoolean(optionsPrefix+".autoload", autoloadFromOccurrence); autoloadCheckBox.setSelected(autoloadFromOccurrence); autorun = options.getInt(optionsPrefix+".autorun", 0); autorunScriptFile = options.get(optionsPrefix+".autorunScriptFile"); autoRunFileTextField.setText(autorunScriptFile); currentScript = options.get(optionsPrefix+".currentScript"); switch(autorun) { case DONT_AUTORUN: { noAutoRunRadioButton.setSelected(true); break; } case AUTORUN_OCCURRENCE: { autoRunOccurrenceRadioButton.setSelected(true); break; } case AUTORUN_SCRIPT_IN_EDITOR: { autoRunScriptInEditorRadioButton.setSelected(true); break; } case AUTORUN_FILE: { autoRunFileRadioButton.setSelected(true); break; } } } private void autorun() { String autorunScript = null; switch(autorun) { case AUTORUN_OCCURRENCE: { autorunScript = getROccurrence(); break; } case AUTORUN_SCRIPT_IN_EDITOR: { autorunScript = rEditor.getText(); break; } case AUTORUN_FILE: { try { if(autorunScriptFile != null && autorunScriptFile.length() > 0) { autorunScript = IObox.loadFile(autorunScriptFile); } } catch(Exception e) { e.printStackTrace(); } break; } } if(autorunScript != null) { executeScript(autorunScript); } } // ------------------------------------------------------------------------- private String getROccurrence() { return getROccurrence(rootTopic); } private String getROccurrence(Topic t) { String o = null; if(t != null) { try { Topic otype = tm.getTopic(R_OCCURRENCE_TYPE); Topic olang = tm.getTopic(TMBox.LANGINDEPENDENT_SI); if(otype != null && olang != null) { o = t.getData(otype, olang); } } catch(Exception e) { e.printStackTrace(); } } return o; } private void setROccurrence(String o) { setROccurrence(rootTopic, o); } private void setROccurrence(Topic t, String o) { if(t != null) { try { Topic otype = tm.getTopic(R_OCCURRENCE_TYPE); Topic olang = tm.getTopic(TMBox.LANGINDEPENDENT_SI); if(otype != null && olang != null) { t.setData(otype, olang, o); } } catch(Exception e) { e.printStackTrace(); } } } // ------------------------------------------------------------------------- @Override public void stop() { saveCurrentScriptToOptions(); } @Override public LocatorHistory getTopicHistory() { return null; } @Override public void refresh() throws TopicMapException { } @Override public boolean applyChanges() throws CancelledException, TopicMapException { saveCurrentScriptToOptions(); return true; } @Override public JPanel getGui() { return this; } @Override public Topic getTopic() throws TopicMapException { return rootTopic; } @Override public Icon getIcon() { return UIBox.getIcon("gui/icons/topic_panel_r.png"); } @Override public JPopupMenu getViewPopupMenu() { return UIBox.makePopupMenu(getViewMenuStruct(), this); } @Override public JMenu getViewMenu() { return UIBox.makeMenu(getViewMenuStruct(), this); } @Override public Object[] getViewMenuStruct() { Object[] menuStructure = new Object[] { "New script", this, "Open script", this, new Object[] { "Open script from occurrence", this, "Open script from file...", this, }, "Save script", this, new Object[] { "Save script to occurrence", this, "Save script to file...", this, }, "Run script", this, "---", "Options...", this, }; return menuStructure; } @Override public boolean noScroll(){ return false; } @Override public String getName() { return "R"; } @Override public String getTitle() { if(rootTopic != null) return TopicToString.toString(rootTopic); else return getName(); } @Override public int getOrder() { return 1000; } // ------------------------------------------------------------------------- @Override public void actionPerformed(ActionEvent e) { String ac = e.getActionCommand(); if("New script".equalsIgnoreCase(ac)) { newScript(); } else if("Open script from occurrence".equalsIgnoreCase(ac)) { loadScriptFromOccurrence(); } else if("Open script from file...".equalsIgnoreCase(ac)) { loadScriptFromFile(); } else if("Save script to occurrence".equalsIgnoreCase(ac)) { saveScriptToOccurrence(); } else if("Save script to file...".equalsIgnoreCase(ac)) { saveScriptToFile(); } else if("Options...".equalsIgnoreCase(ac)) { openOptionsDialog(); } else if("Run script".equalsIgnoreCase(ac)) { executeScriptInEditor(); } } // ------------------------------------------------------------------------- private void newScript() { int answer = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Erase current script in editor?", "Erase script in editor?", WandoraOptionPane.YES_NO_OPTION); if(answer == WandoraOptionPane.YES_OPTION) { currentScriptSource = NO_SOURCE; currentScriptFile = null; rEditor.setText(""); } } public void executeScriptInEditor() { String script = rEditor.getText(); executeScript(script); } public void executeScript(String script) { if(script != null) { if(script.trim().length() > 0) { String newline = "\n"; //String commands[] = script.split(newline); //script = script.replaceAll("(?m)^[ \t]*\r?\n",""); script = script.replace("'","\'"); //script = script.replaceAll("\r\n", ";"); script = script.replace("\n", "\\n"); script = script.replace("\r", "\\r"); script = script.replace("\t", "\\t"); String out = "source(textConnection('" + script + "'),print.eval=TRUE)"; SimpleTextConsole console = (SimpleTextConsole) rConsoleTextPane; tabPanel.setSelectedComponent(consolePanel); console.output(console.handleInput(out)); //for(int i=0; i<commands.length; i++) { //console.output(commands[i]+newline); //console.output(console.handleInput(commands[i].trim())); //} } } } private void loadScriptFromOccurrence() { try { Topic otype = tm.getTopic(R_OCCURRENCE_TYPE); Topic olang = tm.getTopic(TMBox.LANGINDEPENDENT_SI); if(otype != null && olang != null) { currentScriptFile = null; String o = rootTopic.getData(otype, olang); if(o != null) { rEditor.setText(o); } else { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Can't find R occurrence in current topic. Can't restore R script from occurrence.", "Can't restore R occurrence", WandoraOptionPane.INFORMATION_MESSAGE); } } else { if(otype == null) WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Can't find R occurrence type. Can't restore R script from occurrence.", "Can't find R occurrence type", WandoraOptionPane.INFORMATION_MESSAGE); if(olang == null) WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Can't find Language independent scope topic. Can't restore R script from occurrence.", "Can't find Language independent scope topic", WandoraOptionPane.INFORMATION_MESSAGE); } } catch(Exception e) { e.printStackTrace(); } } private void loadScriptFromFile() { fc.setDialogType(JFileChooser.OPEN_DIALOG); fc.setDialogTitle("Open R Script"); int answer = fc.showDialog(Wandora.getWandora(), "Open"); if(answer == SimpleFileChooser.APPROVE_OPTION) { File scriptFile = fc.getSelectedFile(); try { String script = IObox.loadFile(scriptFile); currentScriptFile = scriptFile.getAbsolutePath(); if(script != null) { rEditor.setText(script); } } catch(Exception e) { e.printStackTrace(); WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Exception '"+e.getMessage()+"' occurred while restoring R script from file '"+scriptFile.getName()+"'.", "Can't restore R script", WandoraOptionPane.INFORMATION_MESSAGE); } } } private void saveScriptToOccurrence() { String script = rEditor.getText(); try { Topic otype = tm.getTopic(R_OCCURRENCE_TYPE); Topic olang = tm.getTopic(TMBox.LANGINDEPENDENT_SI); if(otype != null && olang != null) { boolean storeToOccurrence = true; currentScriptSource = OCCURRENCE_SOURCE; String oldScript = rootTopic.getData(otype, olang); if(oldScript != null) { int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Current topic contains an R script occurrence already. Storing current script erases older. Do you want to store the script to the occurrence?","Topic already has an R script occurrence", WandoraOptionPane.INFORMATION_MESSAGE); if(a != WandoraOptionPane.YES_OPTION) storeToOccurrence = false; } if(storeToOccurrence) { rootTopic.setData(otype, olang, script); } } else { if(otype == null) WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Can't find R occurrence type. Can't save R script to occurrence.", "Can't find R occurrence type", WandoraOptionPane.INFORMATION_MESSAGE); if(olang == null) WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Can't find Language independent scope topic. Can't save R script to occurrence.", "Can't find Language independent scope topic", WandoraOptionPane.INFORMATION_MESSAGE); } } catch(Exception e) { e.printStackTrace(); WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Exception '"+e.getMessage()+"' occurred while storing the R script to an occurrence to current topic.", "Can't store R script", WandoraOptionPane.INFORMATION_MESSAGE); } } private void saveScriptToFile() { File scriptFile = null; try { fc.setDialogTitle("Save R script"); fc.setDialogType(JFileChooser.SAVE_DIALOG); int answer = fc.showDialog(Wandora.getWandora(), "Save"); if(answer == SimpleFileChooser.APPROVE_OPTION) { scriptFile = fc.getSelectedFile(); String scriptCode = rEditor.getText(); FileUtils.writeStringToFile(scriptFile, scriptCode, "UTF-8"); currentScriptSource = FILE_SOURCE; } } catch(Exception e) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Exception '"+e.getMessage()+"' occurred while storing R script to file '"+scriptFile.getName()+"'.", "Can't save R script", WandoraOptionPane.INFORMATION_MESSAGE); } } private void saveScript() { if(currentScriptSource == OCCURRENCE_SOURCE) { saveScriptToOccurrence(); } else if(currentScriptSource == FILE_SOURCE) { saveScriptToFile(); } } private void saveCurrentScriptToOptions() { if(options != null) { options.put(optionsPrefix+".currentScript", rEditor.getText()); } if(USE_LOCAL_OPTIONS && SAVE_SKETCH_TO_GLOBAL_OPTIONS) { try { Wandora.getWandora().getOptions().put(optionsPrefix+".currentScript", rEditor.getText()); } catch(Exception e) { } } } // ------------------------------------------------------------------------- @Override public String handleInput(String input) { //System.out.println("HANDLE INPUT: "+input); return rBridge.handleInput(input); } @Override public void output(String output) { ((SimpleTextConsole) rConsoleTextPane).output(output); ((SimpleTextConsole) rConsoleTextPane).refresh(); } // ------------------------------------------------------------------------- @Override public void topicSubjectIdentifierChanged(Topic t, Locator added, Locator removed) throws TopicMapException { } @Override public void topicBaseNameChanged(Topic t, String newName, String oldName) throws TopicMapException { } @Override public void topicTypeChanged(Topic t, Topic added, Topic removed) throws TopicMapException { } @Override public void topicVariantChanged(Topic t, Collection<Topic> scope, String newName, String oldName) throws TopicMapException { } @Override public void topicDataChanged(Topic t, Topic type, Topic version, String newValue, String oldValue) throws TopicMapException { } @Override public void topicSubjectLocatorChanged(Topic t, Locator newLocator, Locator oldLocator) throws TopicMapException { } @Override public void topicRemoved(Topic t) throws TopicMapException { } @Override public void topicChanged(Topic t) throws TopicMapException { } @Override public void associationTypeChanged(Association a, Topic newType, Topic oldType) throws TopicMapException { } @Override public void associationPlayerChanged(Association a, Topic role, Topic newPlayer, Topic oldPlayer) throws TopicMapException { } @Override public void associationRemoved(Association a) throws TopicMapException { } @Override public void associationChanged(Association a) throws TopicMapException { } // ------------------------------------------------------------------------- @Override public void componentResized(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentMoved(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentShown(ComponentEvent e) { handleComponentEvent(e); } @Override public void componentHidden(ComponentEvent e) { handleComponentEvent(e); } private void handleComponentEvent(ComponentEvent e) { saveCurrentScriptToOptions(); revalidate(); repaint(); } // ------------------------------------------------------------------------- }
45,013
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z