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
OccurrenceTextEditor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/texteditor/OccurrenceTextEditor.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/>. * * * OccurrenceTextEditor.java * * Created on 5. toukokuuta 2006, 20:29 */ package org.wandora.application.gui.texteditor; import java.util.HashSet; import java.util.Set; import javax.swing.Icon; import javax.swing.JMenu; import javax.swing.KeyStroke; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleMenu; import org.wandora.application.tools.FindTopicsWithSimilarOccurrence; import org.wandora.application.tools.associations.FindAssociationsInOccurrenceSimple; import org.wandora.application.tools.extractors.gate.AnnieExtractor; import org.wandora.application.tools.extractors.stanfordner.StanfordNERClassifier; import org.wandora.application.tools.extractors.tagthe.TagtheExtractor; import org.wandora.application.tools.extractors.uclassify.SentimentUClassifier; import org.wandora.application.tools.extractors.uclassify.TextLanguageUClassifier; import org.wandora.application.tools.extractors.uclassify.TopicsUClassifier; import org.wandora.application.tools.extractors.uclassify.UClassifier; import org.wandora.application.tools.occurrences.CreateTopicWithOccurrenceSelection; import org.wandora.topicmap.Locator; import org.wandora.topicmap.TMBox; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class OccurrenceTextEditor extends TextEditor { private static final long serialVersionUID = 1L; protected Topic occurrenceTopic = null; protected Topic occurrenceType = null; protected Topic occurrenceVersion = null; public OccurrenceTextEditor(Wandora wandora, boolean modal, String initText, Topic occurrenceTopic, Topic type, Topic version) { this(wandora,modal,initText,null,occurrenceTopic,type,version); } public OccurrenceTextEditor(Wandora wandora, boolean modal, String initText) { this(wandora,modal,initText,null); } public OccurrenceTextEditor(Wandora wandora, boolean modal, String initText, String contentType) { super(wandora, modal, initText, contentType); infoLabel.setText("Editing occurrence"); } public OccurrenceTextEditor(Wandora wandora, boolean modal, String initText, String contentType, Topic occurrenceTopic, Topic type, Topic version) { super(wandora, modal, initText, contentType); this.occurrenceTopic = occurrenceTopic; this.occurrenceType = type; this.occurrenceVersion = version; infoLabel.setText("Editing occurrence"); } @Override public JMenu[] getUserMenus() { JMenu processMenu = new SimpleMenu("Refine", (Icon) null); Object[] menuStruct = new Object[] { "Make topics", new Object[] { "Make topic with selection", new CreateTopicWithOccurrenceSelection(false), "Make topic with selection and associate", new CreateTopicWithOccurrenceSelection(true), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.CTRL_MASK) }, "Find topics", new Object[] { "Find topics in occurrences...", new FindAssociationsInOccurrenceSimple(), KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK), "Find topics with similar occurrences...", new FindTopicsWithSimilarOccurrence(), }, "Classify", new Object[] { "Classify with GATE Annie", new AnnieExtractor(), UIBox.getIcon("gui/icons/extract_gate.png"), "Classify with Stanford NER", new StanfordNERClassifier(), UIBox.getIcon("gui/icons/extract_stanford_ner.png"), "Classify with Tagthe", new TagtheExtractor(), UIBox.getIcon("gui/icons/extract_tagthe.png"), }, "uClassify", new Object[] { "uClassify Text Language", new TextLanguageUClassifier(), UIBox.getIcon("gui/icons/extract_uclassify.png"), "uClassify Sentiment", new SentimentUClassifier(), UIBox.getIcon("gui/icons/extract_uclassify.png"), "uClassify Topics", new TopicsUClassifier(), UIBox.getIcon("gui/icons/extract_uclassify.png"), "uClassify Mood", new UClassifier("Mood", "prfekt", 0.0001), UIBox.getIcon("gui/icons/extract_uclassify.png"), "uClassify GenderAnalyzer_v5", new UClassifier("GenderAnalyzer_v5", "uClassify", 0.0001), UIBox.getIcon("gui/icons/extract_uclassify.png"), "uClassify Ageanalyzer", new UClassifier("Ageanalyzer", "uClassify", 0.0001), UIBox.getIcon("gui/icons/extract_uclassify.png"), }, "Insert", new Object[] { "Insert base name", KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK), "Insert variant name", KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK | java.awt.event.InputEvent.SHIFT_MASK), "Insert subject identifier", KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK | java.awt.event.InputEvent.ALT_MASK), "Insert subject locator",KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK | java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.SHIFT_MASK), } }; return new JMenu[] { UIBox.attachMenu(processMenu, menuStruct, this) }; } /** Creates new form OccurrenceTextEditor */ public OccurrenceTextEditor(Wandora wandora, boolean modal) { super(wandora, modal); } public Topic getOccurrenceTopic() { return occurrenceTopic; } public Topic getOccurrenceType() { return occurrenceType; } public Topic getOccurrenceVersion() { return occurrenceVersion; } // ------------------------------------------------------------------------- @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { if(actionEvent == null) return; String c = actionEvent.getActionCommand(); if(c == null) return; try { if("Insert base name".equalsIgnoreCase(c)) { if(occurrenceTopic != null && !occurrenceTopic.isRemoved()) { String bn = occurrenceTopic.getBaseName(); if(bn != null) { simpleTextPane.insertText(bn); } else { WandoraOptionPane.showMessageDialog(this, "Base name is null and can not be inserted to the occurrence text.", "Base name is null", WandoraOptionPane.ERROR_MESSAGE); } } else { WandoraOptionPane.showMessageDialog(this, "Invalid occurrence carrier topic.", "Invalid occurrence carrier topic.", WandoraOptionPane.ERROR_MESSAGE); } } else if("Insert variant name".equalsIgnoreCase(c)) { if(occurrenceTopic != null && !occurrenceTopic.isRemoved()) { Set<Topic> scope = new HashSet<>(); scope.add(this.occurrenceVersion); scope.add(TMBox.getDisplayNameTopic(occurrenceType)); String variantName = occurrenceTopic.getVariant(scope); if(variantName == null) variantName = occurrenceTopic.getDisplayName(); if(variantName != null) { simpleTextPane.insertText(variantName); } else { WandoraOptionPane.showMessageDialog(this, "No variant names found for insertion.", "No variant names found", WandoraOptionPane.ERROR_MESSAGE); } } else { WandoraOptionPane.showMessageDialog(this, "Invalid occurrence carrier topic.", "Invalid occurrence carrier topic.", WandoraOptionPane.ERROR_MESSAGE); } } else if("Insert subject identifier".equalsIgnoreCase(c)) { if(occurrenceTopic != null && !occurrenceTopic.isRemoved()) { String si = occurrenceTopic.getOneSubjectIdentifier().toExternalForm(); if(si != null) { simpleTextPane.insertText(si); } else { WandoraOptionPane.showMessageDialog(this, "No subject identifiers found for insertion. Invalid topic as occurrence carrier.", "No subject identifier found", WandoraOptionPane.ERROR_MESSAGE); } } else { WandoraOptionPane.showMessageDialog(this, "Invalid occurrence carrier topic.", "Invalid occurrence carrier topic.", WandoraOptionPane.ERROR_MESSAGE); } } else if("Insert subject locator".equalsIgnoreCase(c)) { if(occurrenceTopic != null && !occurrenceTopic.isRemoved()) { Locator sl = occurrenceTopic.getSubjectLocator(); if(sl != null) { String sls = sl.toExternalForm(); simpleTextPane.insertText(sls); } else { WandoraOptionPane.showMessageDialog(this, "No subject locator found for insertion.", "No subject locator found", WandoraOptionPane.ERROR_MESSAGE); } } else { WandoraOptionPane.showMessageDialog(this, "Invalid occurrence carrier topic.", "Invalid occurrence carrier topic.", WandoraOptionPane.ERROR_MESSAGE); } } else { super.actionPerformed(actionEvent); } } catch(Exception e) { e.printStackTrace(); } } }
10,843
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LocatorTableCellRenderer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/LocatorTableCellRenderer.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/>. * * * LocatorTableCellRenderer.java * * Created on 16. lokakuuta 2005, 22:05 * */ package org.wandora.application.gui.table; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import org.wandora.application.gui.UIConstants; import org.wandora.topicmap.Locator; import org.wandora.utils.DataURL; /** * * @author akivela */ public class LocatorTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer { private static final long serialVersionUID = 1L; private LocatorTable locatorTable; public LocatorTableCellRenderer(LocatorTable table) { this.locatorTable = table; } @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); try { Color foregroundColor = locatorTable.getColorFor(row, column); if(foregroundColor != null) { c.setForeground(foregroundColor); } if(c instanceof JLabel) { JLabel label = (JLabel) c; label.setBorder(UIConstants.defaultTableCellLabelBorder); Locator l = (Locator) value; String locatorString = l.toExternalForm(); if(DataURL.isDataURL(locatorString)) { String locatorFragment = locatorString.substring(0, Math.min(locatorString.length(), 64)) + "... ("+locatorString.length()+")"; label.setText(locatorFragment); } } } catch(Exception e){ e.printStackTrace(); // TODO EXCEPTION } return c; } }
2,758
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTableCellEditor.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicTableCellEditor.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/>. * * * TopicTableCellEditor.java * * Created on 14. lokakuuta 2005, 14:50 */ package org.wandora.application.gui.table; import java.awt.Component; import java.awt.Font; import javax.swing.AbstractCellEditor; import javax.swing.JTable; import javax.swing.table.TableCellEditor; import org.wandora.application.gui.TopicGuiWrapper; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Topic; /** * * @author olli,akivela */ public class TopicTableCellEditor extends AbstractCellEditor implements TableCellEditor { private static final long serialVersionUID = 1L; private Topic topic; private SimpleLabel label; private TopicTable table; public TopicTableCellEditor(TopicTable table) { this.table = table; label = new SimpleLabel(); Font f = label.getFont(); label.setFont(new Font(f.getName(),Font.PLAIN,f.getSize())); } public Object getCellEditorValue() { return TopicToString.toString(topic); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { if(value instanceof TopicGuiWrapper) { topic=((TopicGuiWrapper) value).topic; } label.setText(TopicToString.toString(topic)); return label; } }
2,220
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LocatorTableModel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/LocatorTableModel.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.table; import java.awt.Color; import javax.swing.table.DefaultTableModel; import org.wandora.topicmap.Locator; /** * * @author akivela */ public class LocatorTableModel extends DefaultTableModel { private static final long serialVersionUID = 1L; private String[] cols; private Locator[][] data; private Color[][] colors; public LocatorTableModel(Locator[][] tableData, String[] columnData, Color[][] colorData) { data = tableData; cols = columnData; colors = colorData; } @Override public int getColumnCount() { if(cols != null) return cols.length; return 0; } @Override public Class getColumnClass(int col) { return Locator.class; } @Override public int getRowCount() { if(data != null) return data.length; return 0; } public Color getColorAt(int rowIndex, int columnIndex) { try { if(data != null && rowIndex >= 0 && columnIndex >= 0) { return colors[rowIndex][columnIndex]; } } catch (Exception e) {} return null; } @Override public Object getValueAt(int rowIndex, int columnIndex) { try { if(data != null && rowIndex >= 0 && columnIndex >= 0 && columnIndex < getColumnCount() && rowIndex < getRowCount()) { return data[rowIndex][columnIndex]; } } catch (Exception e) {} return "[ERROR]"; } @Override public String getColumnName(int columnIndex){ try { if(cols != null && columnIndex >= 0 && cols.length > columnIndex && cols[columnIndex] != null) { return cols[columnIndex]; } return ""; } catch (Exception e) {} return "[ERROR]"; } @Override public boolean isCellEditable(int row,int col){ return false; } }
2,869
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
InstanceTable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/InstanceTable.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/>. * * * InstanceTable.java * * Created on August 18, 2004, 9:19 AM */ package org.wandora.application.gui.table; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.net.URL; import java.util.List; import java.util.Collection; import java.util.StringTokenizer; import javax.swing.DropMode; import javax.swing.JComponent; import javax.swing.TransferHandler; import org.wandora.application.Wandora; import org.wandora.application.contexts.ApplicationContext; import org.wandora.application.gui.DnDHelper; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.tools.AddInstance; import org.wandora.application.tools.DeleteFromTopics; import org.wandora.application.tools.PasteInstances; 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.utils.ClipboardBox; /** * @author olli, akivela */ public class InstanceTable extends TopicTable /*implements DropTargetListener*/ { private static final long serialVersionUID = 1L; private Topic topic; private Topic[] instances; private Object[] instancePopupStruct = new Object[] { "---", "Add instance...", new AddInstance(new ApplicationContext()), "Paste instances", new Object[] { "Paste instances as basenames...", new PasteInstances(new ApplicationContext()), "Paste instances as SIs...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_NOTHING, PasteInstances.PASTE_SIS), "---", "Paste instances with names...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_NAMES), "Paste instances with SLs...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_SLS), "Paste instances with SIs...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_SIS), "Paste instances with classes...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_CLASSES), "Paste instances with instances...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_INSTANCES), "Paste instances with players...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_PLAYERS), "Paste instances with occurrences...", new PasteInstances(new ApplicationContext(), PasteInstances.INCLUDE_TEXTDATAS), }, "Delete instances...", new DeleteFromTopics(DeleteFromTopics.LOOSE_INSTANCES_IN_CONTEXT), }; /** Creates a new instance of InstanceTable */ public InstanceTable(Topic topic, Wandora w) throws TopicMapException { super(w); this.topic = topic; Collection<Topic> unsorted = topic.getTopicMap().getTopicsOfType(topic); this.instances = (Topic[]) TMBox.sortTopics(unsorted,null).toArray(new Topic[0]); initialize(instances, null); this.setTransferHandler(new InstanceTableTransferHandler()); this.setDropMode(DropMode.ON); } @Override public Object[] getPopupStruct() { return getPopupStruct(instancePopupStruct); } 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 != null) { pastedTopic.addType(topic); } } } } catch(Exception e) { } } } // ------------------------------------------------------------------------- // ----------------------------------------------------- actionPerformed --- // ------------------------------------------------------------------------- @Override public void actionPerformed(ActionEvent e) { super.actionPerformed(e); } // ------------------------------------------------------------------------- // --------------------------------------------------------- DRAG & DROP --- // ------------------------------------------------------------------------- private class InstanceTableTransferHandler extends TransferHandler { private static final long serialVersionUID = 1L; @Override public boolean canImport(TransferSupport support) { if(!support.isDrop()) return false; return support.isDataFlavorSupported(DnDHelper.topicDataFlavor) || support.isDataFlavorSupported(DataFlavor.stringFlavor); } @Override protected Transferable createTransferable(JComponent c) { return DnDHelper.makeTopicTableTransferable(InstanceTable.this); } @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=Wandora.getWandora().getTopicMap(); List<Topic> topics=DnDHelper.getTopicList(support, tm, true); if(topics==null) return false; Topic base=Wandora.getWandora().getOpenTopic(); if(base==null) return false; for(Topic t : topics){ t.addType(base); } Wandora.getWandora().doRefresh(); } catch(TopicMapException tme){tme.printStackTrace();} catch(Exception ce){} return false; } } }
9,579
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTableSorter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicTableSorter.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/>. * * * TopicTableSorter.java * * Created on 1. elokuuta 2006, 19:03 * */ package org.wandora.application.gui.table; import javax.swing.table.JTableHeader; import javax.swing.table.TableModel; import org.wandora.utils.swing.TableSorter; /** * * @author akivela */ public class TopicTableSorter extends TableSorter { private static final long serialVersionUID = 1L; public TopicTableSorter() { super(); } public TopicTableSorter(TableModel tableModel) { super(tableModel); } public TopicTableSorter(TableModel tableModel, JTableHeader tableHeader) { super(tableModel, tableHeader); } }
1,462
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTableModel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicTableModel.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.table; import javax.swing.table.DefaultTableModel; import org.wandora.application.Wandora; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class TopicTableModel extends DefaultTableModel { private static final long serialVersionUID = 1L; private Topic[][] data = null; private Object[] cols = null; public TopicTableModel(Topic[][] tableTopics, Object[] columnObjects) { data = tableTopics; cols = columnObjects; } @Override public Class getColumnClass(int c) { return Topic.class; } @Override public int getColumnCount() { if(cols != null) return cols.length; return 0; } @Override public int getRowCount() { if(data != null) return data.length; return 0; } public Topic getTopicAt(int rowIndex, int columnIndex) { try { if(data != null && rowIndex >= 0 && columnIndex >= 0) { return data[rowIndex][columnIndex]; } } catch (Exception e) { Wandora.getWandora().handleError(e); } return null; } @Override public Object getValueAt(int rowIndex, int columnIndex) { try { if(data != null && rowIndex >= 0 && columnIndex >= 0) { return data[rowIndex][columnIndex]; } } catch (Exception e) { Wandora.getWandora().handleError(e); } return null; } public Object getColumnObjectAt(int columnIndex) { if(cols != null && columnIndex >= 0 && cols.length > columnIndex) { return cols[columnIndex]; } return null; } @Override public String getColumnName(int columnIndex){ try { if(cols != null && columnIndex >= 0 && cols.length > columnIndex && cols[columnIndex] != null) { if(cols[columnIndex] instanceof Topic) return TopicToString.toString((Topic)cols[columnIndex]); else return cols[columnIndex].toString(); } return ""; } catch (Exception e) { Wandora.getWandora().handleError(e); } return "ERROR"; } @Override public boolean isCellEditable(int row,int col){ return false; } }
3,263
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LocatorTable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/LocatorTable.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/>. * * * LocatorTable.java * * Created on 23. lokakuuta 2007, 11:02 * */ package org.wandora.application.gui.table; import java.awt.Color; import java.awt.Point; 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.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.swing.JComponent; import javax.swing.JPopupMenu; import javax.swing.ListSelectionModel; import javax.swing.TransferHandler; import org.wandora.application.Wandora; import org.wandora.application.gui.Clipboardable; import org.wandora.application.gui.DnDHelper; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleTable; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Base64; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import org.wandora.utils.DnDBox; import org.wandora.utils.swing.anyselectiontable.TableSelectionModel; /** * * @author akivela */ public class LocatorTable extends SimpleTable implements MouseListener, ActionListener, Clipboardable /*, DropTargetListener, DragGestureListener*/ { private static final long serialVersionUID = 1L; protected Wandora wandora = null; protected MouseEvent mouseEvent; /** Creates a new instance of LocatorTable */ public LocatorTable(Wandora wandora) { this.wandora = wandora; } // ------------------------------------------------------------------------- public void setSort(int column) { } public void initialize(Locator[] tableLocators, String columnTitle, Color[] tableColors) { Locator[][] extendedTableLocators = new Locator[tableLocators.length][1]; Color[][] extendedTableColors = new Color[tableColors.length][1]; for(int i=0; i<tableLocators.length; i++) { extendedTableLocators[i][0] = tableLocators[i]; } for(int i=0; i<tableColors.length; i++) { extendedTableColors[i][0] = tableColors[i]; } initialize(extendedTableLocators, new String[] { columnTitle }, extendedTableColors ); } public void initialize(Locator[][] tableLocators, String[] columnTitles, Color[][] tableColors) { try { if(tableLocators == null || columnTitles == null) return; LocatorTableModel model = new LocatorTableModel(tableLocators, columnTitles, tableColors); setModel(model); setRowSorter(new LocatorTableRowSorter(model)); createDefaultTableSelectionModel(); setDefaultRenderer(Locator.class, new LocatorTableCellRenderer(this)); addMouseListener(this); JPopupMenu popup = UIBox.makePopupMenu(getPopupStruct(), wandora); setComponentPopupMenu(popup); JPopupMenu headerPopup = UIBox.makePopupMenu(getHeaderPopupStruct(), wandora); getTableHeader().setComponentPopupMenu(headerPopup); setDragEnabled(true); setTransferHandler(new LocatorTableTransferHandler()); getTableHeader().addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent e) { mouseEvent = e; } @Override public void mousePressed(java.awt.event.MouseEvent e) { mouseEvent = e; // FOR POPUP } }); } catch(Exception e) { wandora.handleError(e); } } // ------------------------------------------------------------------------- public Object[] getHeaderPopupStruct() { return null; } public Object[] getPopupStruct() { return null; } @Override public String getToolTipText(MouseEvent e) { Locator l = getLocatorAt(getTablePoint(e)); try { if(l == null) { return null; } else { return l.toExternalForm(); } } catch(Exception ex) { ex.printStackTrace(); // TODO EXCEPTION } return null; } // ------------------------------------------------------------------------- public void selectLocators(Locator[] locators) { if(locators == null || locators.length == 0) return; for(Locator l : locators) { selectLocator(l); } } public void selectLocator(Locator locator) { int c = this.getColumnCount(); int r = this.getRowCount(); Locator tableLocator = null; for(int x=0; x<c; x++) { for(int y=0; y<r; y++) { tableLocator = this.getLocatorAt(y, x); try { if(tableLocator != null) { if(tableLocator.equals(locator)) { selectCell(x, y); return; } } } catch(Exception e) { e.printStackTrace(); } } } } // ------------------------------------------------------------------------- @Override public void cut() { copy(); } @Override public void paste() { } @Override public void copy() { String c = getCopyString(); ClipboardBox.setClipboard( c ); } public String getCopyString() { StringBuilder copyString = new StringBuilder(""); try { Locator[] selectedLocators = getSelectedLocators(); if(selectedLocators != null && selectedLocators.length > 0) { for(int i=0; i<selectedLocators.length; i++) { copyString.append(selectedLocators[i].toExternalForm()); copyString.append("\n"); } } else { Point loc = getTablePoint(mouseEvent); Locator l = getLocatorAt(loc); copyString.append(l.toExternalForm()); } } catch(Exception ex){ wandora.handleError(ex); } return copyString.toString(); } //--------- public Point getTablePoint() { return getTablePoint(mouseEvent); } public Point getTablePoint(java.awt.event.MouseEvent e) { if(e == null) return null; try { java.awt.Point p=e.getPoint(); int y=rowAtPoint(p); int x=columnAtPoint(p); return new Point(x, y); } catch (Exception ex) { wandora.handleError(ex); return null; } } public List<int[]> getSelectedCells() { List<int[]> selected = new ArrayList<>(); TableSelectionModel selection = getTableSelectionModel(); int colCount = this.getColumnCount(); int rowCount = this.getRowCount(); //System.out.println("----"); for(int c=0; c<colCount; c++) { int cc = convertColumnIndexToModel(c); ListSelectionModel columnSelectionModel = selection.getListSelectionModelAt(cc); if(columnSelectionModel != null && !columnSelectionModel.isSelectionEmpty()) { for(int r=0; r<rowCount; r++) { if(columnSelectionModel.isSelectedIndex(r)) { selected.add( new int[] { r, c } ); //System.out.println("found cell "+cc+","+r); } } } } return selected; } public Locator[] getSelectedLocators() { List<Locator> locators = new ArrayList<Locator>(); List<int[]> selectedCells = getSelectedCells(); for(int[] cell : selectedCells) { locators.add( getLocatorAt(cell[0], cell[1]) ); } if(locators.isEmpty()) { Point loc = getTablePoint(); Locator t = getLocatorAt(loc); if(t != null) { locators.add( t ); } } return locators.toArray( new Locator[] {} ); } public int getCurrentRow() { Point point = getTablePoint(); if(point != null) return convertRowIndexToModel(point.x); return -1; } public int[] getCurrentRows() { int[] rows = getSelectedRows(); if(rows == null || rows.length == 0) { int r = getCurrentRow(); if(r != -1) return new int[] { r }; else return new int[] {}; } else { for(int i=0; i<rows.length; i++) { rows[i] = convertRowIndexToModel(rows[i]); } return rows; } } public Object getValueAt(MouseEvent e) { if(e == null) return null; return getValueAt(getTablePoint(e)); } public Object getValueAt(Point p) { if(p == null) return null; return getValueAt(p.y, p.x); } @Override public Object getValueAt(int y, int x) { try { if(x >= 0 && x < getModel().getColumnCount() && y >= 0 && y < getModel().getRowCount()) { int cx = convertColumnIndexToModel(x); int cy = convertRowIndexToModel(y); return getModel().getValueAt(cy, cx); } } catch (Exception e) { e.printStackTrace(); } return null; } public Locator getLocatorAt(MouseEvent e) { return getLocatorAt(getTablePoint(e)); } public Locator getLocatorAt(Point point) { if(point == null) return null; return getLocatorAt(point.x, point.y); } public Locator getLocatorAt(int x, int y) { Object object = getValueAt(x, y); if(object instanceof Locator) { return (Locator) object; } return null; } public Color getColorFor(int row, int col) { try { int cx = convertColumnIndexToModel(col); int cy = convertRowIndexToModel(row); return ((LocatorTableModel) getModel()).getColorAt(cy, cx); } catch (Exception e) { e.printStackTrace(); } return null; } public void selectColumn() { if(getSelectedRow() != -1) { setRowSelectionInterval(0, getRowCount()-1); } } @Override public int convertRowIndexToModel(int row) { return getRowSorter().convertRowIndexToModel(row); } @Override public int convertRowIndexToView(int row) { return getRowSorter().convertRowIndexToView(row); } @Override public int convertColumnIndexToModel(int col) { return super.convertColumnIndexToModel(col); } @Override public int convertColumnIndexToView(int col) { return super.convertColumnIndexToView(col); } // ------------------------------------------------------------------------- public void refreshGUI() { try { wandora.doRefresh(); } catch(Exception e) { wandora.handleError(e); } } // ------------------------------------------------------------------------- public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { } public void mouseExited(java.awt.event.MouseEvent mouseEvent) { } public void mousePressed(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } // ------------------------------------------------------------------------- // --------------------------------------------------------- DRAG & DROP --- // ------------------------------------------------------------------------- private class LocatorTableTransferHandler extends TransferHandler { @Override public boolean canImport(TransferSupport support) { if(!support.isDrop()) return false; return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) || support.isDataFlavorSupported(DnDHelper.topicDataFlavor) || support.isDataFlavorSupported(DataFlavor.stringFlavor); } @Override protected Transferable createTransferable(JComponent c) { String str = getCopyString(); DnDHelper.GenericTransferable ret=new DnDHelper.GenericTransferable(); ret.addData(DnDBox.uriListFlavor, str); ret.addData(DataFlavor.stringFlavor, str); return ret; } @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(DnDHelper.topicDataFlavor)) { java.util.List<Topic> topics = (java.util.List<Topic>)support.getTransferable().getTransferData(DnDHelper.topicDataFlavor); for( Topic topic : topics ) { Collection<Locator> sis = topic.getSubjectIdentifiers(); for(Locator si : sis) { processDrop(si.toExternalForm()); } } } else if(support.isDataFlavorSupported(DnDBox.uriListFlavor)){ String data=(String)support.getTransferable().getTransferData(DnDBox.uriListFlavor); String[] split=data.split("\n"); for(int i=0;i<split.length;i++){ processDrop(split[i].trim()); } } else if(support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)){ java.util.List<File> files = (java.util.List<File>)support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); 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); String dataUrlLocator = dataURL.toExternalForm(Base64.DONT_BREAK_LINES); processDrop(dataUrlLocator); } } else if(ret==WandoraOptionPane.NO_OPTION) { for( File file : files ) { processDrop(file.toURI().toString()); } } } else if(support.isDataFlavorSupported(DataFlavor.stringFlavor)){ String data=(String)support.getTransferable().getTransferData(DataFlavor.stringFlavor); processDrop(data); } } catch(TopicMapException tme){tme.printStackTrace();} catch(UnsupportedFlavorException ufe){ufe.printStackTrace();} catch(IOException ioe){ioe.printStackTrace();} // catch(CancelledException ce){} return false; } } public void processDrop(String data) { // Override this method in extending implementations! // Look at the SITable class for an example. } @Override public void actionPerformed(ActionEvent e) { String c = e.getActionCommand(); } }
17,577
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SITable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/SITable.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/>. * * * SITable.java * * Created on August 18, 2004, 8:53 AM */ package org.wandora.application.gui.table; import java.awt.Color; import org.wandora.application.Wandora; import org.wandora.application.WandoraMenuManager; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli, akivela */ public class SITable extends LocatorTable { private static final long serialVersionUID = 1L; private Topic topic; private Locator[] sis; private Color[] colors; /** Creates a new instance of SITable */ public SITable(Topic topic, Wandora w) throws TopicMapException { super(w); this.topic=topic; sis=(Locator[])topic.getSubjectIdentifiers().toArray(new Locator[0]); colors=new Color[sis.length]; for(int i=0;i<colors.length;i++){ colors[i]=w.topicHilights.getSIColor(topic,sis[i]); } initialize(sis, "Subject identifiers", colors); } @Override public Object[] getHeaderPopupStruct() { return WandoraMenuManager.getSubjectIdentifierTablePopupStruct(); } @Override public Object[] getPopupStruct() { return WandoraMenuManager.getSubjectIdentifierTablePopupStruct(); } @Override public void processDrop(String data) { boolean siAdded = false; //System.out.println("data == " + data); if(data.startsWith("file:")) { try { topic.addSubjectIdentifier(new Locator(data)); siAdded = true; } catch(Exception e) { wandora.handleError(e); } } else if(data.startsWith("data:")) { try { topic.addSubjectIdentifier(new Locator(data)); siAdded = true; } catch(Exception e) { wandora.handleError(e); } } else { while(data.length() > 0) { int l = data.indexOf("http:"); if(l == -1) l = data.indexOf("https:"); if(l == -1) l = data.indexOf("ftp:"); if(l == -1) l = data.indexOf("ftps:"); if(l == -1) l = data.indexOf("mailto:"); if(l == -1) l = data.indexOf("gopher:"); if(l == -1) l = data.indexOf("file:"); if(l > -1) { String url = data.substring(l); // System.out.println("url == " + url); data = ""; int j = url.indexOf(' '); if(j == -1) j = url.indexOf('\n'); if(j > -1) { data = url.substring(j); url = url.substring(0, j); // System.out.println("url == " + url); } try { topic.addSubjectIdentifier(new Locator(url.trim())); siAdded = true; } catch(Exception e) { wandora.handleError(e); } } else { break; } } } if(siAdded) { wandora.reopenTopic(); } } }
4,186
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicGridModel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicGridModel.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.table; import javax.swing.table.DefaultTableModel; import org.wandora.application.Wandora; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class TopicGridModel extends DefaultTableModel { private static final long serialVersionUID = 1L; private TopicGrid topicGrid; private static final String columnNames = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public TopicGridModel(TopicGrid tg) { topicGrid = tg; } @Override public Class getColumnClass(int c) { return Topic.class; } @Override public int getColumnCount() { if(topicGrid != null) return topicGrid.getGridColumnCount(); return 0; } @Override public int getRowCount() { if(topicGrid != null) return topicGrid.getGridRowCount(); return 0; } public Topic getTopicAt(int rowIndex, int columnIndex) { try { if(topicGrid != null && rowIndex >= 0 && columnIndex >= 0) { return topicGrid.getTopicAt(rowIndex, columnIndex); } } catch (Exception e) { Wandora.getWandora().handleError(e); } return null; } @Override public Object getValueAt(int rowIndex, int columnIndex) { try { if(topicGrid != null && rowIndex >= 0 && columnIndex >= 0) { return topicGrid._getTopicAt(rowIndex, columnIndex); } } catch (Exception e) { Wandora.getWandora().handleError(e); } return null; } public Object getColumnObjectAt(int columnIndex) { return getColumnName(columnIndex); } @Override public String getColumnName(int columnIndex){ try { int d1 = (columnIndex) / columnNames.length(); int d2 = (columnIndex) % columnNames.length(); if(d1 == 0) { return ""+columnNames.charAt(d2); } else { return ""+columnNames.charAt(d1)+columnNames.charAt(d2); } } catch (Exception e) { Wandora.getWandora().handleError(e); } return "ERROR"; } @Override public boolean isCellEditable(int row,int col){ return false; } }
3,161
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OperationTable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/OperationTable.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/>. * * * OperationTable.java * */ package org.wandora.application.gui.table; import java.util.List; import javax.swing.ListSelectionModel; import javax.swing.table.TableColumnModel; import javax.swing.table.TableRowSorter; import org.wandora.application.gui.simple.SimpleTable; import org.wandora.topicmap.undowrapper.UndoOperation; /** * * @author akivela */ public class OperationTable extends SimpleTable /*, DropTargetListener, DragGestureListener*/ { private static final long serialVersionUID = 1L; private OperationTableModel opsModel = null; public void initialize(UndoOperation[] tableOperations) { opsModel = new OperationTableModel(tableOperations); initialize(); } public void initialize(List<UndoOperation> tableOperations) { opsModel = new OperationTableModel(tableOperations.toArray(new UndoOperation[] {})); initialize(); } private void initialize() { setDefaultRenderer(Object.class, new OperationTableRenderer(this)); this.setModel(opsModel); setRowSorter(new TableRowSorter(opsModel)); this.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); this.setRowSelectionAllowed(false); TableColumnModel cm = this.getColumnModel(); cm.getColumn(0).setPreferredWidth(40); cm.getColumn(1).setPreferredWidth(100); cm.getColumn(2).setPreferredWidth(100); cm.getColumn(3).setPreferredWidth(200); cm.getColumn(4).setPreferredWidth(200); cm.getColumn(5).setPreferredWidth(40); } public OperationTableModel getOperationDataModel() { return opsModel; } }
2,525
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TableViewerPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TableViewerPanel.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.table; import java.awt.BorderLayout; import java.awt.Component; import javax.swing.JDialog; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleButton; /** * * @author akivela */ public class TableViewerPanel extends javax.swing.JPanel { private static final long serialVersionUID = 1L; private Component component = null; private JDialog dialog = null; /** * Creates new form TableViewerPanel */ public TableViewerPanel() { initComponents(); } public void setTable(Component table) { if(table != null) { component = table; tableContainer.add(table, BorderLayout.CENTER); } } public void openInDialog(Component table, String title) { setTable(table); Wandora wandora = Wandora.getWandora(); dialog = new JDialog(wandora, true); dialog.setTitle(title); dialog.add(this); dialog.setSize(700, 600); wandora.centerWindow(dialog); dialog.setVisible(true); // WAIT TILL CLOSED } /** * 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; tablePanelContainer = new javax.swing.JPanel(); tableScrollPane = new javax.swing.JScrollPane(); tableContainer = new javax.swing.JPanel(); buttonPanel = new javax.swing.JPanel(); buttonFillerPanel = new javax.swing.JPanel(); closeButton = new SimpleButton(); setLayout(new java.awt.GridBagLayout()); tablePanelContainer.setLayout(new java.awt.GridBagLayout()); tableContainer.setLayout(new java.awt.BorderLayout()); tableScrollPane.setViewportView(tableContainer); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.ipadx = 77; gridBagConstraints.ipady = 77; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; tablePanelContainer.add(tableScrollPane, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(tablePanelContainer, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); javax.swing.GroupLayout buttonFillerPanelLayout = new javax.swing.GroupLayout(buttonFillerPanel); buttonFillerPanel.setLayout(buttonFillerPanelLayout); buttonFillerPanelLayout.setHorizontalGroup( buttonFillerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); buttonFillerPanelLayout.setVerticalGroup( buttonFillerPanelLayout.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(buttonFillerPanel, gridBagConstraints); closeButton.setText("Close"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); buttonPanel.add(closeButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; add(buttonPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed if(dialog != null) { dialog.setVisible(false); } }//GEN-LAST:event_closeButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonFillerPanel; private javax.swing.JPanel buttonPanel; private javax.swing.JButton closeButton; private javax.swing.JPanel tableContainer; private javax.swing.JPanel tablePanelContainer; private javax.swing.JScrollPane tableScrollPane; // End of variables declaration//GEN-END:variables }
6,136
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ClassTable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/ClassTable.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/>. * * * ClassTable.java * * Created on August 17, 2004, 4:41 PM */ package org.wandora.application.gui.table; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.net.URL; import java.util.List; import java.util.Collection; import java.util.StringTokenizer; import javax.swing.DropMode; import javax.swing.JComponent; import javax.swing.TransferHandler; import org.wandora.application.Wandora; import org.wandora.application.contexts.ApplicationContext; import org.wandora.application.gui.DnDHelper; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.tools.AddClass; import org.wandora.application.tools.DeleteFromTopics; import org.wandora.application.tools.PasteClasses; import org.wandora.application.tools.PasteInstances; 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.utils.ClipboardBox; /** * @author olli, akivela */ public class ClassTable extends TopicTable /*implements DropTargetListener*/ { private static final long serialVersionUID = 1L; private Topic topic; private Topic[] types; private Object[] classPopupStruct = new Object[] { "---", "Add class...", new AddClass(new ApplicationContext()), "Paste classes", new Object[] { "Paste classes as basenames...", new PasteClasses(new ApplicationContext()), "Paste classes as SIs...", new PasteClasses(new ApplicationContext(), PasteClasses.INCLUDE_NOTHING, PasteClasses.PASTE_SIS), "---", "Paste classes with names...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_NAMES), "Paste classes with SLs...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_SLS), "Paste classes with SIs...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_SIS), "Paste classes with classes...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_CLASSES), "Paste classes with instances...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_INSTANCES), "Paste classes with players...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_PLAYERS), "Paste classes with occurrences...", new PasteClasses(new ApplicationContext(), PasteInstances.INCLUDE_TEXTDATAS), }, "Delete classes...", new DeleteFromTopics(DeleteFromTopics.LOOSE_CLASSES_OF_CURRENT), }; /** Creates a new instance of ClassTable */ public ClassTable(Topic topic, Wandora w) throws TopicMapException { super(w); this.topic = topic; Collection<Topic> unsorted = topic.getTypes(); this.types = (Topic[]) TMBox.sortTopics(unsorted,null).toArray(new Topic[0]); initialize(types, null); this.setTransferHandler(new ClassTableTransferHandler()); this.setDropMode(DropMode.ON); } @Override public Object[] getPopupStruct() { return getPopupStruct(classPopupStruct); } 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.addType(pastedTopic); } } } } catch(Exception e) { } } } // ------------------------------------------------------------------------- // ----------------------------------------------------- actionPerformed --- // ------------------------------------------------------------------------- @Override public void actionPerformed(ActionEvent e) { super.actionPerformed(e); } // ------------------------------------------------------------------------- // --------------------------------------------------------- DRAG & DROP --- // ------------------------------------------------------------------------- /* public void dragEnter(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { if(! parent.dragBorder.equals( this.getBorder())) { defaultBorder = this.getBorder(); this.setBorder(parent.dragBorder); } } public void dragExit(java.awt.dnd.DropTargetEvent dropTargetEvent) { this.setBorder(defaultBorder); } public void dragOver(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { if(! parent.dragBorder.equals( this.getBorder())) { defaultBorder = this.getBorder(); this.setBorder(parent.dragBorder); } } public void drop(java.awt.dnd.DropTargetDropEvent e) { try { DataFlavor fileListFlavor = DataFlavor.javaFileListFlavor; DataFlavor stringFlavor = DataFlavor.stringFlavor; Transferable tr = e.getTransferable(); if(e.isDataFlavorSupported(stringFlavor)) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); String data = (String)tr.getTransferData(stringFlavor); System.out.println("Trying string data flavor. Data="+data); String[] split=data.split("\n"); String identifier = null; TopicMap topicmap = parent.getTopicMap(); Topic t = null; Topic base = parent.getOpenTopic(); boolean changed = false; if(base != null) { for(int i=0; i<split.length; i++) { identifier = split[i]; if(identifier != null) { identifier = identifier.trim(); if(identifier.length() > 0) { if(identifier.startsWith("http:")) { t = TMBox.getOrCreateTopic(topicmap, identifier); } else { t = TMBox.getOrCreateTopicWithBaseName(topicmap, identifier); } if(t != null) { base.addType(t); changed = true; } } } } if(changed) { parent.refreshTopic(); } } e.dropComplete(true); } else { System.out.println("Drop rejected! Wrong data flavor!"); e.rejectDrop(); } this.setBorder(null); } catch(UnsupportedFlavorException ufe) { ufe.printStackTrace(); } catch(Exception ex) { ex.printStackTrace(); } } public void dropActionChanged(java.awt.dnd.DropTargetDragEvent dropTargetDragEvent) { }*/ private class ClassTableTransferHandler extends TransferHandler { private static final long serialVersionUID = 1L; @Override public boolean canImport(TransferSupport support) { if(!support.isDrop()) return false; return support.isDataFlavorSupported(DnDHelper.topicDataFlavor) || support.isDataFlavorSupported(DataFlavor.stringFlavor); } @Override protected Transferable createTransferable(JComponent c) { return DnDHelper.makeTopicTableTransferable(ClassTable.this); } @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=Wandora.getWandora().getTopicMap(); List<Topic> topics=DnDHelper.getTopicList(support, tm, true); if(topics==null) return false; Topic base=Wandora.getWandora().getOpenTopic(); if(base==null) return false; for(Topic t : topics){ base.addType(t); } Wandora.getWandora().doRefresh(); } catch(TopicMapException tme){tme.printStackTrace();} catch(Exception ce){} return false; } } }
12,553
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTableCellRenderer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicTableCellRenderer.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/>. * * * TopicTableCellRenderer.java * * Created on 16. lokakuuta 2005, 22:05 * */ package org.wandora.application.gui.table; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import org.wandora.application.Wandora; import org.wandora.application.gui.TopicGuiWrapper; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class TopicTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer { private static final long serialVersionUID = 1L; private Wandora wandora = null; private Topic topic; private TopicTable topicTable; public TopicTableCellRenderer(TopicTable table) { topicTable = table; wandora = Wandora.getWandora(); } @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); try { if(value == null || value instanceof Topic) { topic = (Topic) value; } else if(value instanceof TopicGuiWrapper) { TopicGuiWrapper topicWrapper = (TopicGuiWrapper) value; topic = topicWrapper.topic; } if(!isSelected && !hasFocus) { Color hilight = wandora.topicHilights.get(topic); if(hilight != null) c.setForeground(hilight); else { Color layerColor = wandora.topicHilights.getLayerColor(topic); if(layerColor != null) c.setForeground(layerColor); else c.setForeground(Color.BLACK); } } if(topic == null) { c.setForeground(Color.LIGHT_GRAY); } else if(topic.isRemoved()) { c.setForeground(Color.RED); } if(c instanceof JLabel) { JLabel label = (JLabel) c; String topicName = TopicToString.toString(topic); label.setText(topicName); label.setBorder(UIConstants.defaultTableCellLabelBorder); } } catch(Exception e) { e.printStackTrace(); } return c; } }
3,435
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTableHeaderRenderer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicTableHeaderRenderer.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/>. * * * TopicTableHeaderRenderer.java * * Created on 1. elokuuta 2006, 20:48 * */ package org.wandora.application.gui.table; import java.awt.Color; import java.awt.Component; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; /** * * @author akivela */ public class TopicTableHeaderRenderer extends DefaultTableCellRenderer implements TableCellRenderer { private static final long serialVersionUID = 1L; private Color[] columnColors = null; private TableCellRenderer oldRenderer = null; /** Creates a new instance of TopicTableHeaderRenderer */ public TopicTableHeaderRenderer(TableCellRenderer renderer, Color[] columnColors) { this.columnColors = columnColors; this.oldRenderer = renderer; } @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); column=table.convertColumnIndexToModel(column); if(columnColors != null && columnColors[column]!=null) { c.setForeground(columnColors[column]); } return c; } }
2,121
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MixedTopicTableRowSorter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/MixedTopicTableRowSorter.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/>. * * * MixedTopicTableRowSorter.java * */ package org.wandora.application.gui.table; import java.util.Comparator; import javax.swing.table.TableRowSorter; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class MixedTopicTableRowSorter extends TableRowSorter { private static final long serialVersionUID = 1L; public MixedTopicTableRowSorter(MixedTopicTableModel dm) { super(dm); } @Override public Comparator<?> getComparator(int column) { return new Comparator() { public int compare(Object o1, Object o2) { if(o1 == null || o2 == null) return 0; if(o1 instanceof Topic && o2 instanceof Topic) { try { String n1 = TopicToString.toString((Topic) o1); String n2 = TopicToString.toString((Topic) o2); return n1.compareTo(n2); } catch(Exception e) { return 0; } } else if(o1 instanceof String && o2 instanceof String) { try { int d = ((String) o1).compareTo((String) o2); return d; } catch(Exception e) {} return 0; } else { return 0; } } }; } @Override public boolean useToString(int column) { return false; } }
2,469
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MixedTopicTable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/MixedTopicTable.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/>. * * * MixedTopicTable.java */ package org.wandora.application.gui.table; import java.awt.Dimension; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.List; import javax.swing.JComponent; import javax.swing.JPopupMenu; import javax.swing.TransferHandler; 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.UIBox; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.DuplicateTopics; import org.wandora.application.tools.SplitTopics; import org.wandora.application.tools.SplitTopicsWithBasename; import org.wandora.application.tools.navigate.OpenTopic; import org.wandora.topicmap.Topic; import org.wandora.utils.Textbox; import org.wandora.utils.swing.TableSorter; /** * * @author olli, akivela */ public class MixedTopicTable extends TopicTable implements MouseListener, ActionListener, Clipboardable /*, DragSourceListener , DragGestureListener*/ { private static final long serialVersionUID = 1L; public Wandora wandora = null; public TableSorter sorter; public MixedTopicTable(Wandora w) { super(w); this.wandora = w; this.setDragEnabled(true); this.setTransferHandler(new MixedTopicTableTransferHandler()); } @Override protected Object[] getPopupStruct() { return new Object[] { "Copy", this, "---", "Open topic", new OpenTopic(), "Open topic in", WandoraMenuManager.getOpenInMenu(), "---", "Select", WandoraMenuManager.getDefaultSelectMenuStruct(wandora, this), "Topics", WandoraMenuManager.getDefaultTopicMenuStruct(wandora, this), }; } @Override protected Object[] getHeaderPopupStruct() { Object header = this.getTableHeader(); return new Object[] { "Open topic", new OpenTopic(), "Open topic in", WandoraMenuManager.getOpenInMenu(), "---", "Duplicate topic", new DuplicateTopics(), "Split topic", new Object[] { "Split topic with subject identifiers", new SplitTopics(), "Split topic with base name...", new SplitTopicsWithBasename(), }, "---", "Add to topic", WandoraMenuManager.getDefaultAddToTopicMenuStruct(wandora, header), "Delete from topic", WandoraMenuManager.getDefaultDeleteFromTopicMenuStruct(wandora, header), "---", "Copy", WandoraMenuManager.getDefaultCopyMenuStruct(wandora, header), "Copy also", WandoraMenuManager.getDefaultCopyAlsoMenuStruct(wandora, header), "Paste", WandoraMenuManager.getDefaultPasteMenuStruct(wandora, header), "Paste also", WandoraMenuManager.getDefaultPasteAlsoMenuStruct(wandora, header), "---", "Subject locators", WandoraMenuManager.getDefaultSLMenuStruct(wandora, header), "Subject identifiers", WandoraMenuManager.getDefaultSIMenuStruct(wandora, header), "Base names", WandoraMenuManager.getDefaultBasenameMenuStruct(wandora, header), "Variant names", WandoraMenuManager.getDefaultVariantNameMenuStruct(wandora, header), "Associations", WandoraMenuManager.getDefaultAssociationMenuStruct(wandora, header), "Occurrences", WandoraMenuManager.getDefaultOccurrenceMenuStruct(wandora, header), }; } // ------------------------------------------------------------------------- public void initialize(Object[] tableTopics, Object columnTopic) { Object[][] extendedTableTopics = new Topic[tableTopics.length][1]; for(int i=0; i<tableTopics.length; i++) { extendedTableTopics[i][0] = tableTopics[i]; } initialize(extendedTableTopics, new Object[] { columnTopic } ); } public void initialize(Object[][] rawData, Object[] columnObjects) { try { if(rawData == null || columnObjects == null) return; setDefaultRenderer(Topic.class, new MixedTopicTableCellRenderer(this)); setDefaultRenderer(String.class, new MixedTopicTableCellRenderer(this)); MixedTopicTableModel model = new MixedTopicTableModel(rawData, columnObjects); this.setModel(model); this.setRowSorter(new MixedTopicTableRowSorter(model)); this.createDefaultTableSelectionModel(); this.addMouseListener(this); this.getTableHeader().setPreferredSize(new Dimension(100, DEFAULT_ROW_HEIGHT)); this.getTableHeader().addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { mouseClicked(e); } @Override public void mouseReleased(java.awt.event.MouseEvent e) { mouseClicked(e); } @Override public void mouseClicked(java.awt.event.MouseEvent e) { if(e.isPopupTrigger()) { Object o=getColumnAt(e.getX()); if(o instanceof Topic){ JPopupMenu rolePopup = UIBox.makePopupMenu(getHeaderPopupStruct(), wandora); rolePopup.show(e.getComponent(),e.getX(),e.getY()); } } } }); } catch(Exception e) { wandora.handleError(e); } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- @Override public String getToolTipText(MouseEvent e) { Object o = getValueAt(getTablePoint(e)); if(o != null) { try { if(o instanceof String) { return Textbox.makeHTMLParagraph(o.toString(), 60); } if(o instanceof Topic) { Topic t = (Topic) o; String tooltipText = TopicToString.toString(t); return Textbox.makeHTMLParagraph(tooltipText, 60); } } catch(Exception ex) {} } return ""; } @Override public String getCopyString() { StringBuilder copyString = new StringBuilder(""); try { Object[][] selectedValues = getSelectedValues(); if(selectedValues.length > 0) { for(int col=0; col<selectedValues.length; col++) { boolean rowHasContent = false; StringBuilder rawString = new StringBuilder(""); for(int row=0; row<selectedValues[col].length; row++) { if(selectedValues[col][row] != null) { rawString.append(selectedValues[col][row]); rowHasContent = true; } if(rowHasContent && row+1<selectedValues[col].length) { rawString.append("\t"); } } if(rowHasContent) { copyString.append(rawString); copyString.append("\n"); }; } } else { copyString.append( getValueAt(getTablePoint()) ); } } catch(Exception tme){ wandora.handleError(tme); } return copyString.toString(); } @Override public Object[][] getSelectedValues() { List<int[]> selectedCells = getSelectedCells(); int rlen = 0; int clen = 0; for(int[] cell : selectedCells) { if(clen < cell[0]) clen = cell[0]; if(rlen < cell[1]) rlen = cell[1]; } Object[][] selectedValues = new Object[clen+1][rlen+1]; for(int[] cell : selectedCells) { selectedValues[cell[0]][cell[1]] = getValueAt( cell[0], cell[1] ); } return selectedValues; } // ------------------------------------------------------------------------- @Override public void actionPerformed(ActionEvent e) { String c = e.getActionCommand(); if("Copy".equalsIgnoreCase(c)) { this.copy(); } } // ------------------------------------------------------------------------- // ----------------------------------------------------------------- DND --- // ------------------------------------------------------------------------- private class MixedTopicTableTransferHandler extends TransferHandler { private static final long serialVersionUID = 1L; @Override public boolean canImport(TransferSupport support) { return false; } @Override protected Transferable createTransferable(JComponent c) { return DnDHelper.makeTopicTableTransferable(MixedTopicTable.this); } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY_OR_MOVE; } @Override public boolean importData(TransferSupport support) { return false; } } }
10,600
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MixedTopicTableHeaderRenderer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/MixedTopicTableHeaderRenderer.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/>. * * * MixedTopicTableHeaderRenderer.java * * */ package org.wandora.application.gui.table; import java.awt.Color; import java.awt.Component; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; /** * * @author olli,akivela */ public class MixedTopicTableHeaderRenderer extends DefaultTableCellRenderer implements TableCellRenderer { private static final long serialVersionUID = 1L; Color[] columnColors = null; TableCellRenderer oldRenderer = null; /** Creates a new instance of TopicTableHeaderRenderer */ public MixedTopicTableHeaderRenderer(TableCellRenderer renderer, Color[] columnColors) { this.columnColors = columnColors; this.oldRenderer = renderer; } @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); column=table.convertColumnIndexToModel(column); if(columnColors != null && columnColors[column]!=null) { c.setForeground(columnColors[column]); } return c; } }
2,052
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MixedTopicTableCellRenderer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/MixedTopicTableCellRenderer.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/>. * * * MixedTopicTableCellRenderer.java * * */ package org.wandora.application.gui.table; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import org.wandora.application.Wandora; import org.wandora.application.gui.MixedTopicGuiWrapper; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class MixedTopicTableCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer { private static final long serialVersionUID = 1L; public Object content; private Topic topic; private MixedTopicTable topicTable; private int topicRenders; private static MixedTopicGuiWrapper defaultWrapper = null; public MixedTopicTableCellRenderer(MixedTopicTable table) { topicTable = table; topicRenders = Wandora.getWandora().options.getInt(MixedTopicGuiWrapper.TOPIC_RENDERS_OPTION_KEY); defaultWrapper = new MixedTopicGuiWrapper(null); } public Object getTableCellRendererValue() { if(content == null) return "--"; else if(topic!=null){ try { return topic.getBaseName(); } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION; return "Exception retrieving name"; } } else return content.toString(); } @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); try { MixedTopicGuiWrapper wrapper = null; if(value != null && value instanceof MixedTopicGuiWrapper) { wrapper = (MixedTopicGuiWrapper) value; } else { defaultWrapper.content = value; wrapper = defaultWrapper; } content = wrapper.getContent(); topic = null; if(content instanceof Topic) { topic = (Topic) content; } if(!isSelected && !hasFocus) { Color hilight=null; Color bg=null; if(content==null){ bg = new Color(0xffcece); } else if(topic==null){ bg = new Color(0xfff1ce); } else{ hilight = Wandora.getWandora().topicHilights.get(topic); } if(hilight != null) c.setForeground(hilight); else { Color layerColor = Wandora.getWandora().topicHilights.getLayerColor(topic); if(layerColor != null) c.setForeground(layerColor); else c.setForeground(Color.BLACK); } c.setBackground(bg); // note null is valid value } if(c instanceof JLabel) { JLabel label = (JLabel) c; try { String topicName = wrapper.toString(topicRenders); label.setText(topicName); label.setBorder(UIConstants.defaultTableCellLabelBorder); if(MixedTopicGuiWrapper.TOPIC_RENDERS_BASENAME_WITH_SL_ICON == topicRenders) { if(topic!=null && topic.getSubjectLocator() != null) { String iconUrl = topic.getSubjectLocator().toExternalForm(); label.setIcon(UIBox.getCachedIconThumbForLocator(iconUrl, 24, 24)); } else { label.setIcon(null); } } } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION; label.setText("Exception retrieving name"); } } } catch(Exception e) { e.printStackTrace(); } return c; } }
5,213
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicGrid.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicGrid.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/>. * * * TopicGrid.java * * Created on 14. lokakuuta 2005, 10:59 */ package org.wandora.application.gui.table; import java.awt.Component; import java.awt.Point; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javax.swing.JComponent; import javax.swing.JPopupMenu; import javax.swing.ListSelectionModel; import javax.swing.TransferHandler; 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.UIConstants; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.simple.SimpleTable; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.importers.SimpleRDFImport; import org.wandora.application.tools.selections.SelectionInfo; 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.XTMPSI; import org.wandora.utils.ClipboardBox; import org.wandora.utils.IObox; import org.wandora.utils.Textbox; import org.wandora.utils.Tuples.T2; import org.wandora.utils.swing.anyselectiontable.TableSelectionModel; /** * * @author akivela */ public class TopicGrid extends SimpleTable implements Clipboardable, MouseListener, ActionListener { private static final long serialVersionUID = 1L; public static final int LEFT = 201; public static final int UP = 202; public static final int RIGHT = 203; public static final int DOWN = 204; private Wandora wandora; private MouseEvent mouseEvent; private int gridWidth = 0; private int gridHeight = 0; Map<T2<Integer,Integer>, Topic> gridData; public TopicGrid(Wandora w) { wandora = w; gridData = new HashMap<>(); this.setDragEnabled(true); this.setTransferHandler(new TopicGridTransferHandler()); } public void initialize(int width, int height) { try { this.gridWidth = width; this.gridHeight = height; setDefaultRenderer(Topic.class, new TopicGridCellRenderer(this)); TopicGridModel model = new TopicGridModel(this); this.setModel(model); this.addMouseListener(this); //gridPopup = UIBox.makePopupMenu(getPopupStruct(), this); //this.setComponentPopupMenu(popup); //final JPopupMenu rolePopup = UIBox.makePopupMenu(getRolePopupStruct(), wandora); //this.getTableHeader().setComponentPopupMenu(rolePopup); this.getTableHeader().setReorderingAllowed(false); this.getTableHeader().addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { mouseClicked(e); } @Override public void mouseReleased(java.awt.event.MouseEvent e) { mouseClicked(e); } @Override public void mouseClicked(java.awt.event.MouseEvent e) { mouseEvent = e; /* int columnNumber = convertColumnIndexToModel(columnAtPoint(e.getPoint())); if(!e.isPopupTrigger()) { if(e.isShiftDown()) { deselectColumn(columnNumber); } else { selectColumn(columnNumber); } } */ /*if(e.isPopupTrigger()) { Object o=getColumnAt(e.getX()); if(o instanceof Topic){ rolePopup.show(e.getComponent(),e.getX(),e.getY()); } e.consume(); }*/ } }); } catch(Exception e) { wandora.handleError(e); } } private Object[] getPopupStruct() { return new Object[] { "Open in", WandoraMenuManager.getOpenInMenu(), "---", "Cut", "Copy", "Paste", "---", "Select", WandoraMenuManager.getDefaultSelectMenuStruct(wandora, this), "Selection info", new SelectionInfo(), "---", "Insert rows", "Insert columns", "Delete rows", "Delete columns", "---", "Clear selected", "Clear all", "---", "Rotate CV", "Rotate CCV", "Flip horizontal", "Flip vertical", "---", "Sort rows", "Sort columns", "---", "Expand", new Object[] { "Expand instances", "Expand classes", "Expand superclasses", "Expand subclasses", "Expand association types", "Expand associated topics", "Expand association roles", }, //"---", //"Add to topic", WandoraMenuManager.getDefaultAddToTopicMenuStruct(wandora, this), //"Delete from topic", WandoraMenuManager.getDefaultDeleteFromTopicMenuStruct(wandora, this), "---", "Make associations", new Object[] { "Make class-instance chain", "Make class-instances using tree layout", "---", "Make associations using Wandora layout", "Make associations using LTM layout", "Make associations using RDF triplet layout", "Make associations using player layout", }, "Topics", WandoraMenuManager.getDefaultTopicMenuStruct(wandora, this), "---", "Import grid...", "Merge grid...", "Export grid...", }; } public int getGridRowCount() { return gridHeight; } public int getGridColumnCount() { return gridWidth; } public void setCurrentTopic(Topic t) { List<int[]> cells = this.getSelectedCells(); for(int[] c : cells) { gridData.put(new T2<>(c[0], c[1]), t); } } public void setTopicAt(Topic t, int column, int row) { gridData.put(new T2<>(row, column), t); } public Topic[] getCurrentTopics() { List<int[]> cells = this.getSelectedCells(); List<Topic> ts = new ArrayList<>(); Topic t; for(int[] c : cells) { t = gridData.get(new T2<>(c[0], c[1])); if(t != null) { ts.add(t); } } return ts.toArray(new Topic[] {}); } public void selectTopics(Topic[] topics) { if(topics == null || topics.length == 0) return; for(Topic t : topics) { selectTopic(t); } } public void selectTopic(Topic topic) { int c = this.getColumnCount(); int r = this.getRowCount(); Topic tableTopic = null; for(int x=0; x<c; x++) { for(int y=0; y<r; y++) { tableTopic = this.getTopicAt(y, x); try { if(tableTopic != null && !tableTopic.isRemoved()) { if(tableTopic.mergesWithTopic(topic)) { selectCell(x, y); } } } catch(Exception e) { e.printStackTrace(); } } } } // ------------------------------------------------------------------------- private void moveSelection(int[] newOrigo) { if(newOrigo != null) { List<int[]> selectedCells = getSelectedCells(); if(selectedCells != null && !selectedCells.isEmpty()) { int[] oldOrigo = getOrigo(selectedCells); clearSelection(); for(int[] c : selectedCells) { int n0 = c[0] - oldOrigo[0] + newOrigo[0]; int n1 = c[1] - oldOrigo[1] + newOrigo[1]; selectCell(n1, n0); } } } } // ------------------------------------------------------------------------- @Override public String getToolTipText(MouseEvent e) { if(e != null) { Point p = getTablePoint(e); Topic t = getTopicAt(p); if(t != null) { String tooltipText = TopicToString.toString(t); return Textbox.makeHTMLParagraph(tooltipText, 60); } } return null; } // ------------------------------------------------------------------------- @Override public void cut() { copy(); clearSelectedCells(); } private boolean autoCreateTopicsInPaste = false; @Override public void paste() { String tabText = ClipboardBox.getClipboard(); StringTokenizer tabLines = new StringTokenizer(tabText, "\n"); int ocol = this.getSelectedColumn(); int orow = this.getSelectedRow(); int row = orow; autoCreateTopicsInPaste = false; while(tabLines.hasMoreTokens()) { String tabLine = tabLines.nextToken(); StringTokenizer topicIdentifiers = new StringTokenizer(tabLine, "\t"); int col = ocol; try { String topicIdentifier = null; while(topicIdentifiers.hasMoreTokens()) { topicIdentifier = topicIdentifiers.nextToken(); if(topicIdentifier != null && topicIdentifier.length() > 0) { Topic topic = getTopicForIdentifier(topicIdentifier); if(topic == null) { boolean createTopicInPaste = false; if(!autoCreateTopicsInPaste) { int a = WandoraOptionPane.showConfirmDialog(wandora, "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.getTopicMap(); boolean identifierIsURL = false; try { URL u = new URL(topicIdentifier); identifierIsURL = true; } catch(Exception e) {} topic = tm.createTopic(); if(identifierIsURL) { topic.addSubjectIdentifier(new Locator(topicIdentifier)); } else { topic.addSubjectIdentifier(tm.makeSubjectIndicatorAsLocator()); topic.setBaseName(topicIdentifier); } } } if(topic != null) { _setTopicAt(topic, row, col); } } col++; } } catch(Exception e) { } row++; } } @Override public void copy() { ClipboardBox.setClipboard(getCopyString()); } public void clearSelectedCells() { List<int[]> cells = getSelectedCells(); for(int[] c : cells) { _setTopicAt(null, c[0], c[1]); } } public void clearAllCells() { gridData.clear(); } 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; } public String getCopyString() { StringBuilder copyString = new StringBuilder(""); try { Object[][] selectedValues = getSelectedValues(); if(selectedValues.length > 0) { for(int col=0; col<selectedValues.length; col++) { boolean rowHasContent = false; StringBuilder rawString = new StringBuilder(""); for(int row=0; row<selectedValues[col].length; row++) { if(selectedValues[col][row] != null) { rawString.append(TopicToString.toString((Topic) selectedValues[col][row])); rowHasContent = true; } if(row+1<selectedValues[col].length) { rawString.append("\t"); } } if(rowHasContent) { copyString.append(rawString); copyString.append("\n"); }; } } else { Point loc = getTablePoint(mouseEvent); Topic t = getTopicAt(loc); copyString.append(TopicToString.toString(t)); } } catch(Exception tme){ wandora.handleError(tme); } return copyString.toString(); } public void insertRows() { List<int[]> cells = getSelectedCells(); Map<Integer, List<Integer>> rowsByColumn = new LinkedHashMap<>(); for(int[] c : cells) { Integer column = c[1]; Integer row = c[0]; List<Integer> columnRows = rowsByColumn.get(column); if(columnRows == null) { columnRows = new ArrayList<>(); } columnRows.add(row); rowsByColumn.put(column, columnRows); } for(Integer column : rowsByColumn.keySet()) { List<Integer> rows = rowsByColumn.get(column); Collections.sort(rows); for(Integer row : rows) { Map<T2<Integer,Integer>, Topic> subData = new LinkedHashMap<>(); for(T2<Integer,Integer> coords : gridData.keySet()) { if(column.equals(coords.e2)) { if(row <= coords.e1) { subData.put(coords, gridData.get(coords)); } } } for(T2<Integer,Integer> coords : subData.keySet()) { gridData.remove(coords); } for(T2<Integer,Integer> coords : subData.keySet()) { gridData.put(new T2<>(coords.e1+1, coords.e2), subData.get(coords)); } } } int numberOfNewRows = 0; for(Integer column : rowsByColumn.keySet()) { List<Integer> rows = rowsByColumn.get(column); if(rows.size() > numberOfNewRows) { numberOfNewRows = rows.size(); } } gridHeight += numberOfNewRows; } public void deleteRows() { List<int[]> cells = getSelectedCells(); Map<Integer, List<Integer>> rowsByColumn = new LinkedHashMap<>(); for(int[] c : cells) { Integer column = c[1]; Integer row = c[0]; List<Integer> columnRows = rowsByColumn.get(column); if(columnRows == null) { columnRows = new ArrayList<>(); } columnRows.add(row); rowsByColumn.put(column, columnRows); } for(Integer column : rowsByColumn.keySet()) { List<Integer> rows = rowsByColumn.get(column); Collections.sort(rows); Collections.reverse(rows); for(Integer row : rows) { Map<T2<Integer,Integer>, Topic> subData = new LinkedHashMap<>(); for(T2<Integer,Integer> coords : gridData.keySet()) { if(column.equals(coords.e2)) { if(row < coords.e1) { subData.put(coords, gridData.get(coords)); } } } if(subData.isEmpty()) { gridData.remove(new T2<>(row, column)); } else { for(T2<Integer,Integer> coords : subData.keySet()) { gridData.remove(coords); } for(T2<Integer,Integer> coords : subData.keySet()) { gridData.put(new T2<>(coords.e1-1, coords.e2), subData.get(coords)); } } } } } public void insertColumns() { List<int[]> cells = getSelectedCells(); Map<Integer, List<Integer>> columnsByRow = new LinkedHashMap<>(); for(int[] c : cells) { Integer column = c[1]; Integer row = c[0]; List<Integer> rowColumns = columnsByRow.get(row); if(rowColumns == null) { rowColumns = new ArrayList<>(); } rowColumns.add(column); columnsByRow.put(row, rowColumns); } for(Integer row : columnsByRow.keySet()) { List<Integer> columns = columnsByRow.get(row); Collections.sort(columns); for(Integer column : columns) { Map<T2<Integer,Integer>, Topic> subData = new LinkedHashMap<>(); for(T2<Integer,Integer> coords : gridData.keySet()) { if(row.equals(coords.e1)) { if(column <= coords.e2) { subData.put(coords, gridData.get(coords)); } } } for(T2<Integer,Integer> coords : subData.keySet()) { gridData.remove(coords); } for(T2<Integer,Integer> coords : subData.keySet()) { gridData.put(new T2<>(coords.e1, coords.e2+1), subData.get(coords)); } } } int numberOfNewColumns = 0; for(Integer row : columnsByRow.keySet()) { List<Integer> columns = columnsByRow.get(row); if(columns.size() > numberOfNewColumns) { numberOfNewColumns = columns.size(); } } gridWidth += numberOfNewColumns; } public void deleteColumns() { List<int[]> cells = getSelectedCells(); Map<Integer, List<Integer>> columnsByRow = new LinkedHashMap<>(); for(int[] c : cells) { Integer column = c[1]; Integer row = c[0]; List<Integer> rowColumns = columnsByRow.get(row); if(rowColumns == null) { rowColumns = new ArrayList<>(); } rowColumns.add(column); columnsByRow.put(row, rowColumns); } for(Integer row : columnsByRow.keySet()) { List<Integer> columns = columnsByRow.get(row); Collections.sort(columns); Collections.reverse(columns); for(Integer column : columns) { Map<T2<Integer,Integer>, Topic> subData = new LinkedHashMap<>(); for(T2<Integer,Integer> coords : gridData.keySet()) { if(row.equals(coords.e1)) { if(column < coords.e2) { subData.put(coords, gridData.get(coords)); } } } if(subData.isEmpty()) { gridData.remove(new T2<>(row, column)); } else { for(T2<Integer,Integer> coords : subData.keySet()) { gridData.remove(coords); } for(T2<Integer,Integer> coords : subData.keySet()) { gridData.put(new T2<>(coords.e1, coords.e2-1), subData.get(coords)); } } } } } // ------------------------------------------------------------------------- public Point getTablePoint() { return getTablePoint(mouseEvent); } public Point getTablePoint(java.awt.event.MouseEvent e) { if(e == null) return null; else return getTablePoint(e.getPoint()); } public Point getTablePoint(Point screenPoint) { try { int y=rowAtPoint(screenPoint); int x=columnAtPoint(screenPoint); return new Point(x, y); } catch (Exception ex) { wandora.handleError(ex); return null; } } public int[] getSelectionOrigo() { return getOrigo(getSelectedCells()); } private int[] getOrigo(List<int[]> cells) { int[] o = null; if(cells != null && !cells.isEmpty()) { for(int[] c : cells) { if(o == null) o = c; else { try { if(c[0] < o[0]) o = c; else if(c[1] < o[1]) o = c; } catch(Exception e) { e.printStackTrace(); } } } } return o; } public List<int[]> getSelectedCells() { List<int[]> selected = new ArrayList<>(); TableSelectionModel selection = getTableSelectionModel(); int colCount = this.getColumnCount(); int rowCount = this.getRowCount(); //System.out.println("----"); for(int c=0; c<colCount; c++) { int cc = convertColumnIndexToModel(c); ListSelectionModel columnSelectionModel = selection.getListSelectionModelAt(cc); if(columnSelectionModel != null && !columnSelectionModel.isSelectionEmpty()) { for(int r=0; r<rowCount; r++) { if(columnSelectionModel.isSelectedIndex(r)) { selected.add( new int[] { r, c } ); //System.out.println("found cell "+cc+","+r); } } } } return selected; } public Object[][] getSelectedValues() { List<int[]> selectedCells = getSelectedCells(); int rlen = 0; int clen = 0; for(int[] cell : selectedCells) { if(clen < cell[0]) clen = cell[0]; if(rlen < cell[1]) rlen = cell[1]; } Object[][] selectedValues = new Object[clen+1][rlen+1]; for(int[] cell : selectedCells) { selectedValues[cell[0]][cell[1]] = getValueAt( cell[0], cell[1] ); } return selectedValues; } public Topic[][] getSelectedTopicsNormalized() { List<int[]> selectedCells = getSelectedCells(); int ymax = 0; int xmax = 0; int ymin = Integer.MAX_VALUE; int xmin = Integer.MAX_VALUE; for(int[] cell : selectedCells) { if(xmax < cell[0]) xmax = cell[0]; if(ymax < cell[1]) ymax = cell[1]; if(xmin > cell[0]) xmin = cell[0]; if(ymin > cell[1]) ymin = cell[1]; } Topic[][] selectedValues = new Topic[xmax-xmin+1][ymax-ymin+1]; for(int[] cell : selectedCells) { selectedValues[cell[0]-xmin][cell[1]-ymin] = getTopicAt( cell[0], cell[1] ); } return selectedValues; } public Topic[] getSelectedTopics() { List<Topic> topics = new ArrayList<>(); List<int[]> selectedCells = getSelectedCells(); for(int[] cell : selectedCells) { topics.add( getTopicAt(cell[0], cell[1]) ); } if(topics.isEmpty()) { Point loc = getTablePoint(); Topic t = getTopicAt(loc); if(t != null) { topics.add( t ); } } return topics.toArray( new Topic[] {} ); } 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 { if(x >= 0 && x < getModel().getColumnCount() && y >= 0 && y < getModel().getRowCount()) { int cx = convertColumnIndexToModel(x); int cy = convertRowIndexToModel(y); return getModel().getValueAt(cy, cx); } } catch (Exception e) { e.printStackTrace(); } return null; } public Object getColumnAt(int x) { return ((TopicGridModel) getModel()).getColumnObjectAt(x); } public Topic getTopicAt(MouseEvent e) { if(e == null) return null; return getTopicAt(getTablePoint(e)); } public Topic getTopicAt(Point point) { if(point == null) return null; return getTopicAt(point.y, point.x); } public Topic getTopicAt(int y, int x) { Object object = getValueAt(y, x); if(object instanceof Topic) { return (Topic) object; } if(object instanceof TopicGuiWrapper) { TopicGuiWrapper wrapper = (TopicGuiWrapper) object; if(wrapper != null) return wrapper.topic; } return null; } public Topic _getTopicAt(int col, int row) { return gridData.get(new T2<>(col, row)); } public void _setTopicAt(Topic t, int col, int row) { if(t != null) { gridData.put(new T2<>(col, row), t); } else { gridData.remove(new T2<>(col, row)); } } @Override public void mouseClicked(java.awt.event.MouseEvent e) { this.mouseEvent = e; if(e != null) { if(e.isPopupTrigger()) { JPopupMenu pm = UIBox.makePopupMenu(getPopupStruct(), this); pm.show(e.getComponent(), e.getX(), e.getY()); e.consume(); } } } @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 e) { mouseClicked(e); } @Override public void mouseReleased(java.awt.event.MouseEvent e) { mouseClicked(e); } @Override public void actionPerformed(ActionEvent e) { if(e == null) return; boolean shouldRepaint = false; boolean shouldUpdateEverything = false; String c = e.getActionCommand(); if(c != null) { c = c.toLowerCase(); if("cut".equals(c)) { cut(); shouldRepaint = true; } else if("copy".equals(c)) { copy(); } else if("paste".equals(c)) { paste(); shouldRepaint = true; } else if("clear selected".equals(c)) { clearSelectedCells(); shouldRepaint = true; } else if("clear all".equals(c)) { clearAllCells(); shouldRepaint = true; } else if("insert rows".equals(c)) { insertRows(); shouldRepaint = true; } else if("delete rows".equals(c)) { deleteRows(); shouldRepaint = true; } else if("insert columns".equals(c)) { insertColumns(); shouldRepaint = true; } else if("delete columns".equals(c)) { deleteColumns(); shouldRepaint = true; } // ***** EXPAND ***** else if("expand instances".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0 && (e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandInstances(LEFT); } else if((e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandInstances(RIGHT); } else if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { expandInstances(UP); } else { expandInstances(DOWN); } shouldRepaint = true; } else if("expand classes".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0 && (e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandClasses(LEFT); } else if((e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandClasses(RIGHT); } else if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { expandClasses(UP); } else { expandClasses(DOWN); } shouldRepaint = true; } else if("expand superclasses".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0 && (e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandSuperclasses(LEFT); } else if((e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandSuperclasses(RIGHT); } else if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { expandSuperclasses(UP); } else { expandSuperclasses(DOWN); } shouldRepaint = true; } else if("expand subclasses".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0 && (e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandSubclasses(LEFT); } else if((e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandSubclasses(RIGHT); } else if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { expandSubclasses(UP); } else { expandSubclasses(DOWN); } shouldRepaint = true; } else if("expand association types".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0 && (e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandAssociationTypes(LEFT); } else if((e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandAssociationTypes(RIGHT); } else if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { expandAssociationTypes(UP); } else { expandAssociationTypes(DOWN); } shouldRepaint = true; } else if("expand associated topics".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0 && (e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandAssociatedTopics(LEFT); } else if((e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandAssociatedTopics(RIGHT); } else if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { expandAssociatedTopics(UP); } else { expandAssociatedTopics(DOWN); } shouldRepaint = true; } else if("expand association roles".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0 && (e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandAssociationRoles(LEFT); } else if((e.getModifiers() & ActionEvent.ALT_MASK) != 0) { expandAssociationRoles(RIGHT); } else if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { expandAssociationRoles(UP); } else { expandAssociationRoles(DOWN); } shouldRepaint = true; } // ***** MAKE ASSOCIATIONS ***** else if("make class-instance chain".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { makeClassInstanceChains(rotateCV(getSelectedTopicsNormalized())); } else { makeClassInstanceChains(getSelectedTopicsNormalized()); } shouldUpdateEverything = true; } else if("make class-instances using tree layout".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { makeClassInstancesUsingTreeLayout(rotateCV(getSelectedTopicsNormalized())); } else { makeClassInstancesUsingTreeLayout(getSelectedTopicsNormalized()); } shouldUpdateEverything = true; } else if("make associations using wandora layout".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { makeAssociationsUsingWandoraLayout(flipVertical(rotateCV(getSelectedTopicsNormalized()))); } else { makeAssociationsUsingWandoraLayout(getSelectedTopicsNormalized()); } shouldUpdateEverything = true; } else if("make associations using ltm layout".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { makeAssociationsUsingLTMLayout(rotateCV(getSelectedTopicsNormalized())); } else { makeAssociationsUsingLTMLayout(getSelectedTopicsNormalized()); } shouldUpdateEverything = true; } else if("make associations using rdf triplet layout".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { makeAssociationsUsingRDFLayout(rotateCV(getSelectedTopicsNormalized())); } else { makeAssociationsUsingRDFLayout(getSelectedTopicsNormalized()); } shouldUpdateEverything = true; } else if("make associations using player layout".equals(c)) { if((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) { makeAssociationsUsingPlayerLayout(rotateCV(getSelectedTopicsNormalized())); } else { makeAssociationsUsingPlayerLayout(getSelectedTopicsNormalized()); } shouldUpdateEverything = true; } // ****** ROTATE AND FLIP TOPICS ***** else if("flip vertical".equals(c)) { Topic[][] selection = getSelectedTopicsNormalized(); int[] origo = getSelectionOrigo(); clearSelectedCells(); pasteAt(origo, flipVertical(selection)); shouldRepaint = true; } else if("flip horizontal".equals(c)) { Topic[][] selection = getSelectedTopicsNormalized(); int[] origo = getSelectionOrigo(); clearSelectedCells(); pasteAt(origo, flipHorizontal(selection)); shouldRepaint = true; } else if("rotate cv".equals(c)) { Topic[][] selection = getSelectedTopicsNormalized(); int[] origo = getSelectionOrigo(); clearSelectedCells(); pasteAt(origo, rotateCV(selection)); shouldRepaint = true; } else if("rotate ccv".equals(c)) { Topic[][] selection = getSelectedTopicsNormalized(); int[] origo = getSelectionOrigo(); clearSelectedCells(); pasteAt(origo, rotateCCV(selection)); shouldRepaint = true; } else if("sort rows".equals(c)) { Topic[][] selection = getSelectedTopicsNormalized(); int[] origo = getSelectionOrigo(); pasteAt(origo, sortRows(selection)); shouldRepaint = true; } // ****** EXPORT AND IMPORT ***** else if("export grid...".equals(c)) { save(); shouldRepaint = true; } else if("import grid...".equals(c)) { load(); shouldRepaint = true; } else if("merge grid...".equals(c)) { merge(); shouldRepaint = true; } } wandora.addUndoMarker(); if(shouldUpdateEverything) { wandora.doRefresh(); } else if(shouldRepaint) { repaint(); } } public void expandInstances(int direction) { TopicMap tm = wandora.getTopicMap(); List<int[]> selectedCells = getSelectedCells(); if(selectedCells != null && !selectedCells.isEmpty()) { for(int[] cell : selectedCells) { try { Topic t = getTopicAt(cell[0], cell[1]); if(t != null) { Collection<Topic> instances = tm.getTopicsOfType(t); paste(instances, cell[1], cell[0], direction); } } catch(Exception e) { } } } } public void expandClasses(int direction) { List<int[]> selectedCells = getSelectedCells(); if(selectedCells != null && !selectedCells.isEmpty()) { for(int[] cell : selectedCells) { try { Topic t = getTopicAt(cell[0], cell[1]); if(t != null) { Collection<Topic> classes = t.getTypes(); paste(classes, cell[1], cell[0], direction); } } catch(Exception e) { } } } } public void expandAssociationTypes(int direction) { List<int[]> selectedCells = getSelectedCells(); if(selectedCells != null && !selectedCells.isEmpty()) { for(int[] cell : selectedCells) { try { Topic t = getTopicAt(cell[0], cell[1]); if(t != null) { Collection<Topic> associationTypes = new LinkedHashSet<>(); Collection<Association> associations = t.getAssociations(); for(Association a : associations) { associationTypes.add(a.getType()); } paste(associationTypes, cell[1], cell[0], direction); } } catch(Exception e) { } } } } public void expandAssociationRoles(int direction) { List<int[]> selectedCells = getSelectedCells(); if(selectedCells != null && !selectedCells.isEmpty()) { for(int[] cell : selectedCells) { try { Topic t = getTopicAt(cell[0], cell[1]); if(t != null) { Collection<Topic> associationRoles = new LinkedHashSet<>(); Collection<Association> associations = t.getAssociations(); for(Association a : associations) { Collection<Topic> roles = a.getRoles(); for(Topic role : roles) { if(t.mergesWithTopic(a.getPlayer(role))) { associationRoles.add( role ); } } } paste(associationRoles, cell[1], cell[0], direction); } } catch(Exception e) { } } } } public void expandAssociatedTopics(int direction) { try { Topic associationType = wandora.showTopicFinder(wandora, "Select association type topic"); if(associationType != null) { Topic role = wandora.showTopicFinder(wandora, "Select role topic"); if(role != null) { expandAssociatedTopics(direction, associationType, role); } } } catch(Exception e) { wandora.handleError(e); } } public void expandAssociatedTopics(int direction, Topic associationType, Topic role) { List<int[]> selectedCells = getSelectedCells(); if(selectedCells != null && !selectedCells.isEmpty()) { for(int[] cell : selectedCells) { try { Topic t = getTopicAt(cell[0], cell[1]); if(t != null) { Collection<Topic> associatedTopics = new LinkedHashSet<>(); Collection<Association> associations = t.getAssociations(associationType); for(Association a : associations) { Topic associatedTopic = a.getPlayer(role); if(associatedTopic != null) { // A special case when topic plays given role in association. if(associatedTopic.mergesWithTopic(t)) { Collection<Topic> roles = a.getRoles(); boolean shouldAdd = false; for(Topic r : roles) { if(!r.mergesWithTopic(role) && t.mergesWithTopic(a.getPlayer(r))) { shouldAdd = true; } } if(shouldAdd) { associatedTopics.add( associatedTopic ); } } else { associatedTopics.add( associatedTopic ); } } } paste(associatedTopics, cell[1], cell[0], direction); } } catch(Exception e) { } } } } public void expandSuperclasses(int direction) { try { TopicMap tm = wandora.getTopicMap(); Topic associationType = tm.getTopic(new Locator(XTMPSI.SUPERCLASS_SUBCLASS)); if(associationType != null) { Topic role = tm.getTopic(new Locator(XTMPSI.SUPERCLASS)); if(role != null) { expandAssociatedTopics(direction, associationType, role); } } } catch(Exception e) { wandora.handleError(e); } } public void expandSubclasses(int direction) { try { TopicMap tm = wandora.getTopicMap(); Topic associationType = tm.getTopic(new Locator(XTMPSI.SUPERCLASS_SUBCLASS)); if(associationType != null) { Topic role = tm.getTopic(new Locator(XTMPSI.SUBCLASS)); if(role != null) { expandAssociatedTopics(direction, associationType, role); } } } catch(Exception e) { wandora.handleError(e); } } public void paste(Collection<Topic> topics, int column, int row, int direction) { if(topics == null || topics.isEmpty()) return; switch(direction) { case LEFT: { pasteLeft(column, row, topics); break; } case UP: { pasteUp(column, row, topics); break; } case RIGHT: { pasteRight(column, row, topics); break; } case DOWN: { pasteDown(column, row, topics); break; } } } private void pasteDown(int column, int row, Collection<Topic> topics) { for(Topic t : topics) { _setTopicAt(t, ++row, column); } } private void pasteUp(int column, int row, Collection<Topic> topics) { for(Topic t : topics) { _setTopicAt(t, --row, column); } } private void pasteRight(int column, int row, Collection<Topic> topics) { for(Topic t : topics) { _setTopicAt(t, row, ++column); } } private void pasteLeft(int column, int row, Collection<Topic> topics) { for(Topic t : topics) { _setTopicAt(t, row, --column); } } public void pasteAt(int[] o, Topic[][] topics) { if(o != null && o.length == 2 && topics != null) { for(int r=0; r<topics.length; r++) { for(int c=0; c<topics[r].length; c++) { _setTopicAt(topics[r][c], o[0]+r, o[1]+c); } } } } public void pasteAt(int[] o, Topic[] topics) { if(o != null && o.length == 2 && topics != null) { for(int r=0; r<topics.length; r++) { _setTopicAt(topics[r], o[0]+r, o[1]); } } } public void pasteAt(int[] o, List<Topic> topics) { if(o != null && o.length == 2 && topics != null) { int r = 0; for(Topic t : topics) { _setTopicAt(t, o[0]+r, o[1]); r++; } } } // ------------------------------------------------------------------------- // --------------------------------------------------- MAKE ASSOCIATIONS --- // ------------------------------------------------------------------------- public void makeClassInstanceChains(Topic[][] data) { if(data != null && data.length > 0) { for(int i=0; i<data.length; i++) { Topic[] row = data[i]; if(row != null) { Topic classTopic = null; for(int j=0; j<row.length; j++) { Topic t = row[j]; if(classTopic != null) { try { t.addType(classTopic); } catch(Exception e) {} } classTopic = t; } } } } } public void makeClassInstancesUsingTreeLayout(Topic[][] data) { if(data != null && data.length > 0) { Topic[] hierarchy = new Topic[1000]; for(int i=0; i<data.length; i++) { Topic[] row = data[i]; if(row != null) { for(int j=0; j<row.length; j++) { Topic t = row[j]; if(t != null) { for(int k=j-1; k>=0; k--) { Topic ct = hierarchy[k]; if(ct != null) { try { t.addType(ct); break; } catch(Exception e) {} } } hierarchy[j] = t; for(int k=j+1; k<1000; k++) { hierarchy[k] = null; } } } } } } } public void makeAssociationsUsingWandoraLayout(Topic[][] data) { int associationCount = 0; TopicMap tm = wandora.getTopicMap(); if(data != null && data.length > 2) { Topic associationType = null; Topic[] roles = null; try { associationType = data[0][0]; if(associationType != null) { roles = data[1]; if(roles != null) { for(int i=2; i<data.length; i++) { Topic[] players = data[i]; if(players != null && players.length == roles.length) { Association a = tm.createAssociation(associationType); if(a != null) { boolean hasPlayers = false; for(int j=0; j<roles.length; j++) { try { Topic role = roles[j]; Topic player = players[j]; if(role != null && player != null) { a.addPlayer(player, role); hasPlayers = true; } } catch(Exception e) { e.printStackTrace(); } } if(hasPlayers) { associationCount++; } else { a.remove(); } } } } } } } catch(Exception e) { e.printStackTrace(); } } else { System.out.println("Has less than three rows. Can't build an association."); } System.out.println("Created "+associationCount+" associations."); } public void makeAssociationsUsingLTMLayout(Topic[][] data) { int associationCount = 0; TopicMap tm = wandora.getTopicMap(); if(data != null && data.length > 0) { for(int i=0; i<data.length; i++) { Topic[] associationData = data[i]; if(associationData != null && associationData.length > 0) { Topic associationType = associationData[0]; if(associationType != null) { try { Association a = tm.createAssociation(associationType); boolean hasPlayers = false; for(int j=1; j+1<associationData.length; j=j+2) { try { Topic role = associationData[j+1]; Topic player = associationData[j]; if(role != null && player != null) { a.addPlayer(player, role); hasPlayers = true; } } catch(Exception e) { e.printStackTrace(); } } if(hasPlayers) { associationCount++; } else { a.remove(); } } catch(Exception e) { e.printStackTrace(); } } } } } else { System.out.println("Has no rows. Can't build an association."); } System.out.println("Created "+associationCount+" associations."); } public void makeAssociationsUsingRDFLayout(Topic[][] data) { int associationCount = 0; TopicMap tm = wandora.getTopicMap(); if(data != null && data.length > 0) { for(int i=0; i<data.length; i++) { Topic[] associationData = data[i]; if(associationData != null && associationData.length > 2) { Topic subject = associationData[0]; Topic predicate = associationData[1]; Topic object = associationData[2]; if(subject != null && predicate != null && object != null) { Association a = null; try { a = tm.createAssociation(predicate); Topic subjectRole = tm.createTopic(); subjectRole.addSubjectIdentifier(new Locator(SimpleRDFImport.subjectTypeSI)); Topic objectRole = tm.createTopic(); objectRole.addSubjectIdentifier(new Locator(SimpleRDFImport.objectTypeSI)); a.addPlayer(subject, subjectRole); a.addPlayer(object, objectRole); associationCount++; } catch(Exception e) { try { if(a != null) a.remove(); } catch(Exception ex) {} e.printStackTrace(); } } } } } else { System.out.println("Has no rows. Can't build an association."); } System.out.println("Created "+associationCount+" associations."); } public void makeAssociationsUsingPlayerLayout(Topic[][] data) { int associationCount = 0; TopicMap tm = wandora.getTopicMap(); if(data != null && data.length > 0) { for(int i=0; i<data.length; i++) { Topic[] associationData = data[i]; if(associationData != null && associationData.length > 0) { Association a = null; try { Topic defaultAssociationType = tm.createTopic(); defaultAssociationType.addSubjectIdentifier(new Locator("http://wandora.org/si/core/default-association")); a = tm.createAssociation(defaultAssociationType); associationCount++; for(int j=0; j<associationData.length; j++) { Topic player = associationData[j]; if(player != null) { Topic role = tm.createTopic(); role.addSubjectIdentifier(new Locator("http://wandora.org/si/core/default-role-"+(j+1))); a.addPlayer(player, role); } } } catch(Exception e) { e.printStackTrace(); } } } } else { System.out.println("Has no rows. Can't build an association."); } System.out.println("Created "+associationCount+" associations."); } // ------------------------------------------------------------------------- // ---------------------------------------------------------- ARRAY MODS --- // ------------------------------------------------------------------------- public Topic[][] sortRows(Topic[][] data) { if(data != null) { data = rotateCV(data); for(int i=0; i<data.length; i++) { for(int j=0; j<data[i].length-1; j++) { for(int k=j+1; k<data[i].length; k++) { if(compareTopics(data[i][j],data[i][k]) > 0) { Topic t = data[i][j]; data[i][j] = data[i][k]; data[i][k] = t; } } } } data = rotateCV(data); } return data; } public Topic[][] sortColumns(Topic[][] data) { if(data != null) { for(int i=0; i<data.length; i++) { for(int j=0; j<data[i].length-1; j++) { for(int k=j+1; k<data[i].length; k++) { if(compareTopics(data[i][j],data[i][k]) > 0) { Topic t = data[i][j]; data[i][j] = data[i][k]; data[i][k] = t; } } } } } return data; } private int compareTopics(Topic t1, Topic t2) { if(t1 == null && t2 == null) return 0; if(t1 != null && t2 == null) return 1; if(t1 == null && t2 != null) return -1; if(t1 != null && t2 != null) { String s1 = TopicToString.toString(t1); String s2 = TopicToString.toString(t2); if(s1 == null && s2 == null) return 0; if(s1 != null && s2 == null) return 1; if(s1 == null && s2 != null) return -1; if(s1 != null && s2 != null) { return s1.compareTo(s2); } } return 0; } private Topic[][] rotateCCV(Topic[][] data) { Topic[][] newData = null; if(data != null) { int maxLen = 0; for(int i=0; i<data.length; i++) { if(maxLen < data[i].length) maxLen = data[i].length; } newData = new Topic[maxLen][data.length]; for(int i=0; i<data.length; i++) { for(int j=0; j<data[i].length; j++) { newData[maxLen-j-1][i] = data[i][j]; } for(int j=data[i].length; j<maxLen; j++) { newData[maxLen-j-1][i] = null; } } } return newData; } private Topic[][] rotateCV(Topic[][] data) { Topic[][] newData = null; if(data != null) { int maxLen = 0; for(int i=0; i<data.length; i++) { if(maxLen < data[i].length) maxLen = data[i].length; } newData = new Topic[maxLen][data.length]; for(int i=0; i<data.length; i++) { for(int j=0; j<data[i].length; j++) { newData[j][data.length-i-1] = data[i][j]; } for(int j=data[i].length; j<maxLen; j++) { newData[j][data.length-i-1] = null; } } } return newData; } private Topic[][] flipDiagonally(Topic[][] data) { Topic[][] newData = null; if(data != null) { int maxLen = 0; for(int i=0; i<data.length; i++) { if(maxLen < data[i].length) maxLen = data[i].length; } newData = new Topic[maxLen][data.length]; for(int i=0; i<data.length; i++) { for(int j=0; j<data[i].length; j++) { newData[j][i] = data[i][j]; } for(int j=data[i].length; j<maxLen; j++) { newData[j][i] = null; } } } return newData; } private Topic[][] flipHorizontal(Topic[][] data) { Topic[][] newData = null; if(data != null) { int maxLen = 0; for(int i=0; i<data.length; i++) { if(maxLen < data[i].length) maxLen = data[i].length; } newData = new Topic[data.length][maxLen]; for(int i=0; i<data.length; i++) { for(int j=0; j<data[i].length; j++) { newData[i][maxLen-j-1] = data[i][j]; } for(int j=data[i].length; j<maxLen; j++) { newData[i][maxLen-j-1] = null; } } } return newData; } private Topic[][] flipVertical(Topic[][] data) { Topic[][] newData = null; if(data != null) { newData = new Topic[data.length][]; for(int i=0; i<data.length; i++) { newData[data.length-i-1] = new Topic[data[i].length]; for(int j=0; j<data[i].length; j++) { newData[data.length-i-1][j] = data[i][j]; } } } return newData; } // ------------------------------------------------------------------------- // ----------------------------------------------------------------- DND --- // ------------------------------------------------------------------------- public static Component dragSourceComponent = null; private class TopicGridTransferHandler extends TransferHandler { private static final long serialVersionUID = 1L; @Override public boolean canImport(TransferHandler.TransferSupport support) { if(!support.isDrop()) return false; return support.isDataFlavorSupported(DnDHelper.topicDataFlavor) || support.isDataFlavorSupported(DataFlavor.stringFlavor) || support.isDataFlavorSupported(DnDHelper.topicArrayDataFlavor) || support.isDataFlavorSupported(DnDHelper.topicGridDataFlavor); } @Override protected Transferable createTransferable(JComponent c) { dragSourceComponent = TopicGrid.this; Transferable trans = DnDHelper.makeTopicTransferable(TopicGrid.this); return trans; } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY_OR_MOVE; } @Override public boolean importData(TransferHandler.TransferSupport support) { if(!support.isDrop()) return false; try { int action = support.getDropAction(); DropLocation dropLocation = support.getDropLocation(); Point tablePoint = getTablePoint(dropLocation.getDropPoint()); int dropColumn = tablePoint.x; int dropRow = tablePoint.y; TopicMap tm=Wandora.getWandora().getTopicMap(); if(support.isDataFlavorSupported(DnDHelper.topicGridDataFlavor)) { //System.out.println("Pasted topic grid"); Transferable trans = support.getTransferable(); Object transData = trans.getTransferData(DnDHelper.topicGridDataFlavor); if(transData == null) return false; if(transData instanceof Topic[][]) { Topic[][] topics = (Topic[][]) transData; if(action == MOVE && TopicGrid.this.equals(dragSourceComponent)) { clearSelectedCells(); } pasteAt(new int[] {dropRow,dropColumn}, topics); } moveSelection(new int[] { dropRow,dropColumn } ); } else { List<Topic> topics=DnDHelper.getTopicList(support, tm, true); if(topics==null) return false; pasteAt(new int[] {dropRow,dropColumn}, topics); } Wandora.getWandora().doRefresh(); return true; } catch(TopicMapException tme){ tme.printStackTrace(); } catch(Exception ce){ ce.printStackTrace(); } return false; } @Override protected void exportDone(JComponent c, Transferable t, int action) { dragSourceComponent = null; } } // --------------------------------------------------------- SAVE & LOAD --- public void save() { StringBuilder data = new StringBuilder(""); for(T2<Integer,Integer> coord : gridData.keySet()) { if(coord != null) { Topic t = gridData.get(coord); if(t != null) { try { data.append(coord.e1); data.append("\t"); data.append(coord.e2); data.append("\t"); data.append(t.getOneSubjectIdentifier().toExternalForm()); data.append("\n"); } catch (TopicMapException ex) { ex.printStackTrace(); } } } } SimpleFileChooser chooser = UIConstants.getWandoraProjectFileChooser(); chooser.setDialogTitle("Save topic grid data"); if(chooser.open(wandora, SimpleFileChooser.SAVE_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { File f = IObox.addFileExtension(chooser.getSelectedFile(), "txt"); if(f.exists()) { int overWrite = WandoraOptionPane.showConfirmDialog(wandora, "Overwrite existing file '"+f.getName()+"'?", "Overwrite file?", WandoraOptionPane.YES_NO_OPTION); if(overWrite == WandoraOptionPane.NO_OPTION) return; } try { IObox.saveFile(f, data.toString()); } catch (IOException ex) { ex.printStackTrace(); } } } public void load() { SimpleFileChooser chooser = UIConstants.getWandoraProjectFileChooser(); chooser.setDialogTitle("Load topic grid data"); if(chooser.open(wandora, SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); if(f.exists()) { try { String data = IObox.loadFile(f); HashMap<T2<Integer,Integer>, Topic> newGridData = parse(data); gridData = newGridData; } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } } public void merge() { SimpleFileChooser chooser = UIConstants.getWandoraProjectFileChooser(); chooser.setDialogTitle("Merge topic grid data"); if(chooser.open(wandora, SimpleFileChooser.OPEN_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); if(f.exists()) { try { String data = IObox.loadFile(f); HashMap<T2<Integer,Integer>, Topic> newGridData = parse(data); for(T2<Integer,Integer> c : newGridData.keySet()) { gridData.put(c, newGridData.get(c)); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } } public HashMap<T2<Integer,Integer>, Topic> parse(String data) { TopicMap tm = wandora.getTopicMap(); HashMap<T2<Integer,Integer>, Topic> newGridData = new HashMap<>(); StringTokenizer dataLines = new StringTokenizer(data, "\n"); while(dataLines.hasMoreTokens()) { String dataLine = dataLines.nextToken(); StringTokenizer topicData = new StringTokenizer(dataLine, "\t"); if(topicData.countTokens() == 3) { String e1 = topicData.nextToken(); String e2 = topicData.nextToken(); String si = topicData.nextToken(); try { int e1i = Integer.parseInt(e1); int e2i = Integer.parseInt(e2); Topic t = tm.getTopic(si); if(t != null && !t.isRemoved()) { newGridData.put(new T2<>(e1i, e2i), t); } else { System.out.println("Couldn't find a topic for subject identifier '"+si+"'. Skipping topic."); } } catch(Exception e) { e.printStackTrace(); } } } return newGridData; } }
73,832
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LocatorTableRowSorter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/LocatorTableRowSorter.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.table; import java.util.Comparator; import javax.swing.table.TableRowSorter; import org.wandora.topicmap.Locator; /** * * @author akivela */ public class LocatorTableRowSorter extends TableRowSorter { public LocatorTableRowSorter(LocatorTableModel dm) { super(dm); } @Override public Comparator<?> getComparator(int column) { return new Comparator() { public int compare(Object o1, Object o2) { if(o1 == null || o2 == null) return 0; if(o1 instanceof Locator && o2 instanceof Locator) { try { String l1 = ((Locator) o1).toExternalForm(); String l2 = ((Locator) o2).toExternalForm(); return l1.compareTo(l2); } catch(Exception e) { return 0; } } else if(o1 instanceof String && o2 instanceof String) { try { int d = ((String) o1).compareTo((String) o2); return d; } catch(Exception e) {} return 0; } else { return 0; } } }; } @Override public boolean useToString(int column) { return false; } }
2,283
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MixedTopicTableModel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/MixedTopicTableModel.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.table; import javax.swing.table.DefaultTableModel; import org.wandora.application.Wandora; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class MixedTopicTableModel extends DefaultTableModel { private static final long serialVersionUID = 1L; private Object[] cols; private Object[][] data; public MixedTopicTableModel(Object[][] d, Object[] columnObjects) { data = d; cols = columnObjects; } @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 && rowIndex < getRowCount() && columnIndex < getColumnCount()) { return data[rowIndex][columnIndex]; } } catch (Exception e) { Wandora.getWandora().handleError(e); } return null; } @Override public String getColumnName(int columnIndex){ try { if(cols != null && columnIndex >= 0 && cols.length > columnIndex && cols[columnIndex] != null) { if(cols[columnIndex] instanceof Topic) return Wandora.getWandora().getTopicGUIName((Topic)cols[columnIndex]); else return cols[columnIndex].toString(); // return cols[columnIndex].getBaseName(); } return ""; } catch (Exception e) { Wandora.getWandora().handleError(e); } return "ERROR"; } @Override public Class getColumnClass(int c) { if(data != null && data[0][c] instanceof Topic) { return Topic.class; } return String.class; } @Override public boolean isCellEditable(int row,int col){ return false; } }
2,881
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTableRowSorter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicTableRowSorter.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/>. * * * TopicTableRowSorter.java * */ package org.wandora.application.gui.table; import java.util.Comparator; import javax.swing.table.TableRowSorter; import org.wandora.application.gui.TopicGuiWrapper; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class TopicTableRowSorter extends TableRowSorter { private static final long serialVersionUID = 1L; private TopicTable table = null; public TopicTableRowSorter(TopicTable table, TopicTableModel dm) { super(dm); this.table = table; } @Override public void sort() { super.sort(); } @Override public Comparator<?> getComparator(int column) { return new Comparator() { public int compare(Object o1, Object o2) { if(o1 == null || o2 == null) return 0; if(o1 instanceof TopicGuiWrapper) { o1 = ((TopicGuiWrapper) o1).topic; } if(o2 instanceof TopicGuiWrapper) { o2 = ((TopicGuiWrapper) o2).topic; } if(o1 instanceof Topic && o2 instanceof Topic) { try { String n1 = TopicToString.toString((Topic) o1); String n2 = TopicToString.toString((Topic) o2); // System.out.println("comparing topics: "+n1+" and "+n2+""); return n1.compareTo(n2); } catch(Exception e) { return 0; } } else if(o1 instanceof String && o2 instanceof String) { try { int d = ((String) o1).compareTo((String) o2); // System.out.println("comparing strings: "+o1+" and "+o2+""); return d; } catch(Exception e) {} return 0; } else { return 0; } } }; } @Override public boolean useToString(int column) { return false; } }
3,084
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OperationTableModel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/OperationTableModel.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/>. * * * OperationTableModel.java * */ package org.wandora.application.gui.table; import javax.swing.table.DefaultTableModel; import org.wandora.topicmap.undowrapper.UndoOperation; /** * * @author akivela */ public class OperationTableModel extends DefaultTableModel { private static final long serialVersionUID = 1L; private UndoOperation[] ops = null; public OperationTableModel(UndoOperation[] operations) { this.ops = operations; } @Override public int getColumnCount() { return 6; } @Override public int getRowCount() { if(ops != null) return ops.length; return 0; } @Override public Object getValueAt(int rowIndex, int columnIndex) { try { if(ops != null && rowIndex >= 0 && rowIndex < getRowCount()) { switch(columnIndex) { case 0: { String i = ""+ops[rowIndex].getOperationNumber(); while(i.length()<5) i="0"+i; return i; } case 1: { return ops[rowIndex].getUndoLabel(); } case 2: { return ops[rowIndex].getRedoLabel(); } case 3: { return ops[rowIndex].getDescription(); } case 4: { return ""+ops[rowIndex].getClass().toString(); } case 5: { return ""+ops[rowIndex].isMarker(); } } } } catch (Exception e) {} return "[ERROR]"; } @Override public String getColumnName(int columnIndex){ try { switch(columnIndex) { case 0: { return "index"; } case 1: { return "undo label"; } case 2: { return "redo label"; } case 3: { return "description"; } case 4: { return "class"; } case 5: { return "is marker"; } } return ""; } catch (Exception e) {} return "[ERROR]"; } @Override public boolean isCellEditable(int row, int col){ return false; } public boolean isMarker(int row) { if(ops != null && row >= 0 && row < getRowCount()) { return ops[row].isMarker(); } return false; } }
3,623
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicGridCellRenderer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicGridCellRenderer.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/>. * * * TopicTableCellRenderer.java * * Created on 16. lokakuuta 2005, 22:05 * */ package org.wandora.application.gui.table; import java.awt.Color; import java.awt.Component; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import org.wandora.application.Wandora; import org.wandora.application.gui.TopicGuiWrapper; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class TopicGridCellRenderer extends DefaultTableCellRenderer implements TableCellRenderer { private static final long serialVersionUID = 1L; private Wandora wandora = null; private Topic topic; private TopicGrid topicGrid; public TopicGridCellRenderer(TopicGrid grid) { topicGrid = grid; wandora = Wandora.getWandora(); } @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); try { if(value == null || value instanceof Topic) { topic = (Topic) value; } else if(value instanceof TopicGuiWrapper) { TopicGuiWrapper topicWrapper = (TopicGuiWrapper) value; topic = topicWrapper.topic; } if(!isSelected && !hasFocus) { Color hilight = wandora.topicHilights.get(topic); if(hilight != null) c.setForeground(hilight); else { Color layerColor = wandora.topicHilights.getLayerColor(topic); if(layerColor != null) c.setForeground(layerColor); else c.setForeground(Color.BLACK); } } else if(topic != null && topic.isRemoved()) { c.setForeground(Color.RED); } if(c instanceof JLabel) { JLabel label = (JLabel) c; label.setBorder(UIConstants.defaultTableCellLabelBorder); if(topic != null) { String topicName = TopicToString.toString(topic); label.setText(topicName); } else { label.setText(""); } } } catch(Exception e) { e.printStackTrace(); } return c; } }
3,480
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AssociationTable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/AssociationTable.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/>. * * * AssociationTable.java * * Created on August 12, 2004, 11:15 AM */ package org.wandora.application.gui.table; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import javax.swing.DropMode; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.TransferHandler; import org.wandora.application.Wandora; import org.wandora.application.WandoraMenuManager; import org.wandora.application.gui.DnDHelper; 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.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.ClipboardBox; /** * @author olli, akivela */ public class AssociationTable extends TopicTable { private static final long serialVersionUID = 1L; private Wandora wandora; private Association[] associations; private Topic[][] tableTopics; private Topic[] columnTopics; private Topic topic; boolean hideTopicColumn = true; private Topic associationTypeTopic = null; /** Creates a new instance of AssociationTable */ public AssociationTable(Collection<Association> as, Wandora w, Topic topic) throws TopicMapException { super(w); this.wandora = w; this.topic=topic; Collection<Topic> roles=new LinkedHashSet<>(); Iterator<Association> iter=as.iterator(); while(iter.hasNext()){ Association a=iter.next(); roles.addAll(a.getRoles()); associationTypeTopic = a.getType(); } roles=TMBox.sortTopics(roles,null); associations = (Association[]) as.toArray( new Association[0] ); columnTopics=(Topic[])roles.toArray(new Topic[0]); tableTopics = new Topic[associations.length][columnTopics.length]; Topic role = null; Topic player = null; int len = associations.length; for(int i=0; i<len; i++) { Association a=associations[i]; for(int j=0; j<columnTopics.length; j++) { role=columnTopics[j]; player=a.getPlayer(role); tableTopics[i][j]=player; // may be null } } initialize(tableTopics, columnTopics); this.setTransferHandler(new AssociationTableTransferHandler()); this.setDropMode(DropMode.ON); } @Override public Object[] getPopupStruct() { return getPopupStruct(WandoraMenuManager.getAssociationsPopupStruct()); } // ------------------------------------------------------------------------- public Topic getAssociationTypeTopic() { return associationTypeTopic; } public void selectAssociations(Association[] associations) { if(associations == null || associations.length == 0) return; for(Association a : associations) { selectAssociation(a); } } public void selectAssociation(Association association) { int r = associations.length; int c = this.getColumnCount(); Association tableAssociation = null; for(int y=0; y<r; y++) { tableAssociation = associations[y]; try { if(tableAssociation != null) { if(tableAssociation.equals(association)) { for(int x=0; x<c; x++) { this.selectCell(x,y); } return; } } } catch(Exception e) { e.printStackTrace(); } } } public void selectAssociations(Map<Association,List<Topic>> selection) { if(selection == null || selection.isEmpty()) return; Set<Association> as = selection.keySet(); for(Association a : as) { selectAssociation(a, selection.get(a)); } } public void selectAssociation(Association association, List<Topic> roles) { int r = associations.length; int c = columnTopics.length; Association tableAssociation = null; for(int y=0; y<r; y++) { tableAssociation = associations[y]; try { if(tableAssociation != null) { if(tableAssociation.equals(association)) { for(int x=0; x<c; x++) { if(roles.contains(columnTopics[x])) { this.selectCell(convertColumnIndexToModel(x),y); } } return; } } } catch(Exception e) { e.printStackTrace(); } } } // ------------------------------------------------------------------------- public Collection<Association> getSelectedAssociations() { List<int[]> selected = getSelectedCells(); List<Association> selectedAssociations = new ArrayList<>(); Association a = null; if(!selected.isEmpty()) { for(int[] cell : selected) { int row = cell[0]; a = associations[convertRowIndexToModel(row)]; if(!selectedAssociations.contains(a)) { selectedAssociations.add(a); } } } else { selectedAssociations.addAll( getAllAssociations() ); } return selectedAssociations; } public Collection<Association> getAllAssociations() { List<Association> allAssociations = new ArrayList<>(); allAssociations.addAll(Arrays.asList(associations)); return allAssociations; } public Map<Association,List<Topic>> getSelectedAssociationsWithSelectedPlayers() { Map<Association,List<Topic>> selection = new LinkedHashMap<>(); List<Topic> players = null; Collection<int[]> selectedCells = getSelectedCells(); for(int[] cell : selectedCells) { Association a = associations[cell[0]]; Topic player = getTopicAt(cell[0], cell[1]); players = selection.get(a); if(players == null) players = new ArrayList<>(); players.add(player); selection.put(a, players); } return selection; } public Map<Association,List<Topic>> getSelectedAssociationsWithSelectedRoles() { Map<Association,List<Topic>> selection = new LinkedHashMap<>(); List<Topic> roles = null; Collection<int[]> selectedCells = getSelectedCells(); for(int[] cell : selectedCells) { Association a = associations[cell[0]]; Topic role = columnTopics[cell[1]]; roles = selection.get(a); if(roles == null) roles = new ArrayList<>(); roles.add(role); selection.put(a, roles); } return selection; } // ------------------------------------------------------------------------- private boolean autoCreateTopicsInPaste = false; @Override public void paste() { TopicMap tm = Wandora.getWandora().getTopicMap(); Map<Association,List<Topic>> selectedAssociationsAndRoles = getSelectedAssociationsWithSelectedRoles(); 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) { if(tm != null) { boolean identifierIsURL = false; try { 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 != null) { for(Association a : selectedAssociationsAndRoles.keySet()) { if(a != null && !a.isRemoved()) { Association newa = tm.createAssociation(a.getType()); Collection<Topic> selectedRoles = selectedAssociationsAndRoles.get(a); for(Topic r : a.getRoles()) { if(!selectedRoles.contains(r)) { newa.addPlayer(a.getPlayer(r), r); } } for(Topic r : selectedRoles) { newa.addPlayer(pastedTopic, r); } } } } } } } catch(Exception e) { } } } // ------------------------------------------------------------------------- // --------------------------------------------------------- DRAG & DROP --- // ------------------------------------------------------------------------- private class AssociationTableTransferHandler extends TransferHandler { private static final long serialVersionUID = 1L; @Override public boolean canImport(TransferSupport support) { if(!support.isDrop()) return false; return support.isDataFlavorSupported(DnDHelper.topicDataFlavor) || support.isDataFlavorSupported(DataFlavor.stringFlavor); } @Override protected Transferable createTransferable(JComponent c) { int[] rows=getSelectedRows(); DnDHelper.WandoraTransferable ret=DnDHelper.makeTopicTableTransferable(AssociationTable.this); List<Association> selectedAssociations=new ArrayList<>(); for(int i=0;i<rows.length;i++){ selectedAssociations.add(associations[rows[i]]); } ret.setAssociations(selectedAssociations.toArray( new Association[] {} )); return ret; } @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=AssociationTable.this.wandora.getTopicMap(); List<Topic> topics=DnDHelper.getTopicList(support, tm, true); if(topics==null) return false; JTable.DropLocation location=(JTable.DropLocation)support.getDropLocation(); int row=location.getRow(); if(row==-1) return false; row=convertRowIndexToModel(row); int col=location.getColumn(); if(col==-1) return false; col=convertColumnIndexToModel(col); Association rowAssociation=associations[row]; Topic associationType=rowAssociation.getType(); for(Topic t : topics){ Association a=tm.createAssociation(associationType); for(int i=0;i<columnTopics.length;i++){ if(i==col){ a.addPlayer(t,columnTopics[i]); } else{ Topic player=rowAssociation.getPlayer(columnTopics[i]); a.addPlayer(player,columnTopics[i]); } } } AssociationTable.this.wandora.doRefresh(); } catch(TopicMapException tme){tme.printStackTrace();} catch(Exception ce){} return false; } } }
15,725
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LocatorTableSorter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/LocatorTableSorter.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/>. * * * LocatorTableSorter.java * * Created on 1. elokuuta 2006, 19:03 * */ package org.wandora.application.gui.table; import javax.swing.table.JTableHeader; import javax.swing.table.TableModel; import org.wandora.utils.swing.TableSorter; /** * * @author akivela */ public class LocatorTableSorter extends TableSorter { private static final long serialVersionUID = 1L; public LocatorTableSorter() { super(); } public LocatorTableSorter(TableModel tableModel) { super(tableModel); } public LocatorTableSorter(TableModel tableModel, JTableHeader tableHeader) { super(tableModel, tableHeader); } }
1,477
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicTable.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/>. * * * TopicTable.java * * Created on 14. lokakuuta 2005, 10:59 */ package org.wandora.application.gui.table; import java.awt.Dimension; import java.awt.Point; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.List; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.LinkedHashSet; import javax.swing.JComponent; import javax.swing.JPopupMenu; import javax.swing.ListSelectionModel; import javax.swing.RowSorter; import javax.swing.TransferHandler; import javax.swing.event.RowSorterEvent; 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.simple.SimpleTable; import org.wandora.application.gui.topicstringify.TopicToString; import org.wandora.application.tools.DuplicateTopics; import org.wandora.application.tools.SplitTopics; import org.wandora.application.tools.SplitTopicsWithBasename; import org.wandora.application.tools.navigate.OpenTopic; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.utils.ClipboardBox; import org.wandora.utils.Textbox; import org.wandora.utils.swing.anyselectiontable.TableSelectionModel; /** * * @author akivela */ public class TopicTable extends SimpleTable implements MouseListener, ActionListener, Clipboardable { private static final long serialVersionUID = 1L; private Wandora wandora = null; private MouseEvent mouseEvent; public TopicTable(Wandora w) { super(); this.wandora = w; this.setUpdateSelectionOnSort(true); this.setDragEnabled(true); this.setTransferHandler(new TopicTableTransferHandler()); } // ------------------------------------------------------------------------- public void initialize(Collection<Topic> tableTopics) { initialize(tableTopics.toArray( new Topic[] {} ), ""); } public void initialize(Collection<Topic> tableTopics, Object columnTopic) { initialize(tableTopics.toArray( new Topic[] {} ), columnTopic); } public void initialize(Topic[] tableTopics, Object columnTopic) { Topic[][] extendedTableTopics = new Topic[tableTopics.length][1]; for(int i=0; i<tableTopics.length; i++) { extendedTableTopics[i][0] = tableTopics[i]; } initialize(extendedTableTopics, new Object[] { columnTopic } ); } public void initialize(Topic[][] tableTopics, Object[] columnObjects) { try { if(tableTopics == null || columnObjects == null) return; setDefaultRenderer(Topic.class, new TopicTableCellRenderer(this)); TopicTableModel model = new TopicTableModel(tableTopics, columnObjects); this.setModel(model); TopicTableRowSorter rowSorter = new TopicTableRowSorter(this, model); this.setRowSorter(rowSorter); rowSorter.setSortsOnUpdates(true); this.addMouseListener(this); this.getTableHeader().setPreferredSize(new Dimension(100, DEFAULT_ROW_HEIGHT)); this.getTableHeader().addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mousePressed(java.awt.event.MouseEvent e) { mouseClicked(e); } @Override public void mouseReleased(java.awt.event.MouseEvent e) { mouseClicked(e); } @Override public void mouseClicked(java.awt.event.MouseEvent e) { mouseEvent = e; if(e.isPopupTrigger()) { Point loc = getTablePoint(mouseEvent); Object o = getColumnAt(loc.x); if(o != null && o instanceof Topic) { JPopupMenu rolePopup = UIBox.makePopupMenu(getHeaderPopupStruct(), wandora); rolePopup.show(e.getComponent(),e.getX(),e.getY()); } e.consume(); } } }); } catch(Exception e) { wandora.handleError(e); } } // ------------------------------------------------------------------------- @Override public void sorterChanged(RowSorterEvent e) { List<int[]> modelCells = new ArrayList<>(); if(e.getType().equals(RowSorterEvent.Type.SORTED)) { List<int[]> selectedCells = getSelectedCells(); if(selectedCells != null && !selectedCells.isEmpty()) { modelCells = new ArrayList<>(); for(int[] cell : selectedCells) { int i = e.convertPreviousRowIndexToModel(cell[0]); cell[0] = (i != -1 ? i : cell[0]); modelCells.add(cell); } } } super.sorterChanged(e); if(e.getType().equals(RowSorterEvent.Type.SORTED)) { if(modelCells != null && !modelCells.isEmpty()) { clearSelection(); List<int[]> viewCells = new ArrayList<>(); for(int[] cell : modelCells) { cell[0] = convertRowIndexToView(cell[0]); cell[1] = convertColumnIndexToView(cell[1]); viewCells.add(cell); } selectCells(viewCells); } } } // ------------------------------------------------------------------------- protected Object[] getHeaderPopupStruct() { Object header = this.getTableHeader(); return new Object[] { "Open topic", new OpenTopic(), "Open topic in", WandoraMenuManager.getOpenInMenu(), "---", "Duplicate topic", new DuplicateTopics(), "Split topic", new Object[] { "Split topic with subject identifiers", new SplitTopics(), "Split topic with base name...", new SplitTopicsWithBasename(), }, "---", "Add to topic", WandoraMenuManager.getDefaultAddToTopicMenuStruct(wandora, header), "Delete from topic", WandoraMenuManager.getDefaultDeleteFromTopicMenuStruct(wandora, header), "---", "Copy", WandoraMenuManager.getDefaultCopyMenuStruct(wandora, header), "Copy also", WandoraMenuManager.getDefaultCopyAlsoMenuStruct(wandora, header), "Paste", WandoraMenuManager.getDefaultPasteMenuStruct(wandora, header), "Paste also", WandoraMenuManager.getDefaultPasteAlsoMenuStruct(wandora, header), "---", "Subject locators", WandoraMenuManager.getDefaultSLMenuStruct(wandora, header), "Subject identifiers", WandoraMenuManager.getDefaultSIMenuStruct(wandora, header), "Base names", WandoraMenuManager.getDefaultBasenameMenuStruct(wandora, header), "Variant names", WandoraMenuManager.getDefaultVariantNameMenuStruct(wandora, header), "Associations", WandoraMenuManager.getDefaultAssociationMenuStruct(wandora, header), "Occurrences", WandoraMenuManager.getDefaultOccurrenceMenuStruct(wandora, header), }; } protected Object[] getPopupStruct() { return new Object[] { "Open topic", new OpenTopic(), "Open topic in", WandoraMenuManager.getOpenInMenu(), "---", "Select", WandoraMenuManager.getDefaultSelectMenuStruct(wandora, this), "Topics", WandoraMenuManager.getDefaultTopicMenuStruct(wandora, this), }; } protected Object[] getPopupStruct(Object[] subStruct) { int i=0; Object[] popupStruct = new Object[] { "Open topic", new OpenTopic(), "Open topic in", WandoraMenuManager.getOpenInMenu(), "---", "Select", WandoraMenuManager.getDefaultSelectMenuStruct(wandora, this), "Topics", WandoraMenuManager.getDefaultTopicMenuStruct(wandora, this), }; Object[] newPopupStruct = new Object[popupStruct.length + subStruct.length]; for(; i<popupStruct.length; i++) { newPopupStruct[i] = popupStruct[i]; } for(int subi=0; subi<subStruct.length; subi++) { newPopupStruct[i+subi] = subStruct[subi]; } return newPopupStruct; } // ------------------------------------------------------------------------- public void selectTopics(Topic[] topics) { if(topics == null || topics.length == 0) return; Set<Topic> topicHash = new LinkedHashSet<>(); for(int i=0; i<topics.length; i++) { topicHash.add(topics[i]); } int c = this.getColumnCount(); int r = this.getRowCount(); Topic tableTopic = null; for(int x=0; x<c; x++) { for(int y=0; y<r; y++) { tableTopic = this.getTopicAt(y, x); try { if(tableTopic != null && !tableTopic.isRemoved()) { if(topicHash.contains(tableTopic)) { selectCell(x, y); } } } catch(Exception e) { e.printStackTrace(); } } } } public void selectTopic(Topic topic) { int c = this.getColumnCount(); int r = this.getRowCount(); Topic tableTopic = null; for(int x=0; x<c; x++) { for(int y=0; y<r; y++) { tableTopic = this.getTopicAt(y, x); try { if(tableTopic != null && !tableTopic.isRemoved()) { if(tableTopic.mergesWithTopic(topic)) { selectCell(x, y); } } } catch(Exception e) { e.printStackTrace(); } } } } // ------------------------------------------------------------------------- @Override public String getToolTipText(MouseEvent e) { Point p = getTablePoint(e); Topic t = getTopicAt(p); String tooltipText = TopicToString.toString(t); return Textbox.makeHTMLParagraph(tooltipText, 60); } public void toggleSortOrder(int s) { RowSorter sorter = getRowSorter(); if(sorter != null) { sorter.toggleSortOrder(s); } } @Override public void cut() { copy(); } @Override public void paste() { } @Override public void copy() { ClipboardBox.setClipboard(getCopyString()); } public String getCopyString() { StringBuilder copyString = new StringBuilder(""); try { Object[][] selectedValues = getSelectedValues(); if(selectedValues.length > 0) { for(int col=0; col<selectedValues.length; col++) { boolean rowHasContent = false; StringBuilder rawString = new StringBuilder(""); for(int row=0; row<selectedValues[col].length; row++) { if(selectedValues[col][row] != null) { rawString.append(TopicToString.toString((Topic) selectedValues[col][row])); rowHasContent = true; } if(rowHasContent && row+1<selectedValues[col].length) { rawString.append("\t"); } } if(rowHasContent) { copyString.append(rawString); copyString.append("\n"); }; } } else { Point loc = getTablePoint(mouseEvent); Topic t = getTopicAt(loc); copyString.append(TopicToString.toString(t)); } } catch(Exception tme){ wandora.handleError(tme); } return copyString.toString(); } public Point getTablePoint() { return getTablePoint(mouseEvent); } public Point getTablePoint(java.awt.event.MouseEvent e) { if(e == null) return null; try { java.awt.Point p=e.getPoint(); int y=rowAtPoint(p); int x=columnAtPoint(p); return new Point(x, y); } catch (Exception ex) { wandora.handleError(ex); return null; } } public List<int[]> getSelectedCells() { List<int[]> selected = new ArrayList<>(); TableSelectionModel selection = getTableSelectionModel(); int colCount = this.getColumnCount(); int rowCount = this.getRowCount(); //System.out.println("----"); for(int c=0; c<colCount; c++) { int cc = convertColumnIndexToModel(c); ListSelectionModel columnSelectionModel = selection.getListSelectionModelAt(cc); if(columnSelectionModel != null && !columnSelectionModel.isSelectionEmpty()) { for(int r=0; r<rowCount; r++) { if(columnSelectionModel.isSelectedIndex(r)) { selected.add( new int[] { r, c } ); //System.out.println("found cell "+cc+","+r); } } } } return selected; } public Object[][] getSelectedValues() { List<int[]> selectedCells = getSelectedCells(); int rlen = 0; int clen = 0; for(int[] cell : selectedCells) { if(clen < cell[0]) clen = cell[0]; if(rlen < cell[1]) rlen = cell[1]; } Object[][] selectedValues = new Object[clen+1][rlen+1]; for(int[] cell : selectedCells) { selectedValues[cell[0]][cell[1]] = getValueAt( cell[0], cell[1] ); } return selectedValues; } public Topic[] getSelectedTopics() { List<Topic> topics = new ArrayList<>(); List<int[]> selectedCells = getSelectedCells(); for(int[] cell : selectedCells) { Topic t = getTopicAt(cell[0], cell[1]); try { if( t != null && !t.isRemoved() ) { topics.add( t ); } } catch(Exception e) { e.printStackTrace(); } } if(topics.isEmpty()) { Point loc = getTablePoint(); Topic t = getTopicAt(loc); try { if(t != null && !t.isRemoved() ) { topics.add( t ); } } catch(Exception e) { e.printStackTrace(); } } return topics.toArray( new Topic[] {} ); } public Topic getSelectedHeaderTopic() { if(mouseEvent != null) { int c = this.getTableHeader().columnAtPoint(mouseEvent.getPoint()); int realc = convertColumnIndexToModel(c); Object o = ((TopicTableModel) getModel()).getColumnObjectAt(realc); if(o instanceof Topic) return (Topic) o; } 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 { if(x >= 0 && x < getModel().getColumnCount() && y >= 0 && y < getModel().getRowCount()) { int cx = convertColumnIndexToModel(x); int cy = convertRowIndexToModel(y); return getModel().getValueAt(cy, cx); } } catch (Exception e) { e.printStackTrace(); } return null; } public Object getColumnAt(int x) { return ((TopicTableModel) getModel()).getColumnObjectAt(x); } public Topic getTopicAt(MouseEvent e) { if(e == null) return null; return getTopicAt(getTablePoint(e)); } public Topic getTopicAt(Point point) { if(point == null) return null; return getTopicAt(point.y, point.x); } public Topic getTopicAt(int y, int x) { Object object = getValueAt(y, x); if(object instanceof Topic) { return (Topic) object; } if(object instanceof TopicGuiWrapper) { TopicGuiWrapper wrapper = (TopicGuiWrapper) object; if(wrapper != null) return wrapper.topic; } return null; } @Override public int convertRowIndexToModel(int row) { return getRowSorter().convertRowIndexToModel(row); } @Override public int convertRowIndexToView(int row) { return getRowSorter().convertRowIndexToView(row); } @Override public int convertColumnIndexToModel(int col) { return super.convertColumnIndexToModel(col); } @Override public int convertColumnIndexToView(int col) { return super.convertColumnIndexToView(col); } // ------------------------------------------------------------------------- public void refreshGUI() { try { wandora.doRefresh(); } catch(Exception ce) { //ce.printStackTrace(); } } // ------------------------------------------------------------------------- @Override public void mouseClicked(java.awt.event.MouseEvent e) { this.mouseEvent = e; if(e.getClickCount()>=2){ wandora.applyChangesAndOpen(getTopicAt(e)); } if(e.isPopupTrigger()) { JPopupMenu popup = UIBox.makePopupMenu(getPopupStruct(), wandora); popup.show(e.getComponent(), e.getX(), e.getY()); e.consume(); } } @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) { this.mouseEvent = e; mouseClicked(mouseEvent); } @Override public void mouseReleased(java.awt.event.MouseEvent e) { this.mouseEvent = e; mouseClicked(mouseEvent); } @Override public void actionPerformed(ActionEvent e) { } 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; } // ------------------------------------------------------------------------- // ----------------------------------------------------------------- DND --- // ------------------------------------------------------------------------- private class TopicTableTransferHandler extends TransferHandler { @Override public boolean canImport(TransferSupport support) { return false; } @Override protected Transferable createTransferable(JComponent c) { return DnDHelper.makeTopicTableTransferable(TopicTable.this); } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY_OR_MOVE; } @Override public boolean importData(TransferSupport support) { return false; } } }
21,737
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
OperationTableRenderer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/OperationTableRenderer.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/>. * * * OperationTableRenderer.java * * Created on 2013-04-28. * */ package org.wandora.application.gui.table; import java.awt.Color; import java.awt.Component; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import org.wandora.application.gui.UIConstants; /** * * @author akivela */ public class OperationTableRenderer extends DefaultTableCellRenderer implements TableCellRenderer { private static final long serialVersionUID = 1L; private OperationTable table; private OperationTableModel model; public OperationTableRenderer(OperationTable t) { this.table = t; this.model = table.getOperationDataModel(); } @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); try { if(model.isMarker(row)) { c.setBackground(UIConstants.defaultActiveBackground); } else { c.setBackground(Color.WHITE); } } catch(Exception e){ e.printStackTrace(); // TODO EXCEPTION; // uriLabel.setText("*** Exception occurred while initializing locator table label!"); } return c; } }
2,278
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicTableHeader.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/table/TopicTableHeader.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/>. * * * TopicTableHeader.java * * Created on 2. elokuuta 2006, 11:13 * */ package org.wandora.application.gui.table; import javax.swing.table.JTableHeader; /** * * @author akivela */ public class TopicTableHeader extends JTableHeader { private static final long serialVersionUID = 1L; /** Creates a new instance of TopicTableHeader */ public TopicTableHeader() { } }
1,202
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PreviewWrapper.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/PreviewWrapper.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/>. * * * PreviewWrapper.java * * Created on 29. toukokuuta 2006, 14:55 * */ package org.wandora.application.gui.previews; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.util.HashMap; import java.util.Map; import javax.swing.JPanel; import org.wandora.topicmap.Locator; /** * * @author akivela */ public class PreviewWrapper extends JPanel { private static final long serialVersionUID = 1L; private static Map<Object,PreviewWrapper> previewWrappers = null; private PreviewPanel currentPanel = null; private Component currentUI = null; private Locator currentLocator = null; private PreviewWrapperInitializer initializer = null; /** * To create a new preview wrapper, call static method getPreviewWrapper * with the caller as an argument. Created preview wrapper is caller * specific and same preview wrapped is returned for the same caller. This * behavior prevents the preview restarting after small changes in the * topic panels. */ private PreviewWrapper() { this.setLayout(new BorderLayout()); } public static PreviewWrapper getPreviewWrapper(Object owner) { if(previewWrappers == null) { previewWrappers = new HashMap<>(); } PreviewWrapper previewWrapper = previewWrappers.get(owner); if(previewWrapper == null) { previewWrapper = new PreviewWrapper(); previewWrappers.put(owner, previewWrapper); } return previewWrapper; } public static void removePreviewWrapper(Object owner) { if(previewWrappers != null) { if(previewWrappers.containsKey(owner)) { previewWrappers.remove(owner); } else { System.out.println("Found no preview wrapper "+owner); } } } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public void stop() { if(initializer != null) { if(initializer.isAlive()) { System.out.println("Setting the preview initializer aborted."); initializer.setAborted(); } } if(currentPanel != null) { // System.out.println("Stopping preview wrapper."); currentPanel.stop(); } currentPanel = null; currentLocator = null; removeAll(); } public void setURL(final Locator subjectLocator) { if(subjectLocator != null && subjectLocator.equals(currentLocator)) { return; } forceSetURL(subjectLocator); } public void forceSetURL(final Locator subjectLocator) { if(currentPanel != null) { currentPanel.stop(); currentPanel.finish(); } currentPanel = null; currentUI = null; removeAll(); currentLocator = subjectLocator; if(subjectLocator == null) return; if(subjectLocator.toExternalForm().equals("")) return; currentUI = PreviewUtils.previewLoadingMessage(this); // All the rest of building the preview happens in a separate class // extending a thread. This way the application doesn't freeze // if the preview initialization takes longer. initializer = new PreviewWrapperInitializer(subjectLocator, this); initializer.start(); } // ------------------------------------------------------------------------- @Override public Dimension getPreferredSize() { if(currentUI != null) { return currentUI.getPreferredSize(); } else { //return super.getPreferredSize(); return new Dimension(0,0); } } @Override public Dimension getMinimumSize() { if(currentUI != null) { return currentUI.getMinimumSize(); } else { //return super.getMinimumSize(); return new Dimension(0,0); } } /** ------------------------------------------------------------------------ * PreviewWrapperInitializer is a Thread that solves the preview viewer class, * instantiates preview viewer and initialized it. Downloading and initializing * the preview in a thread of it's own, Wandora's user interface doesn't * block and freeze if it takes longer. Notice, the thread exits once the * preview is ready. If the user stops (exits) the preview for some reason, * the isAborted variable is set true and the thread does as little as it can. * The thread is never really killed (forced to abort) though. This is because * the preview may become unstable if the initialization is stopped carelessly. */ protected class PreviewWrapperInitializer extends Thread { private final Locator subjectLocator; private final PreviewWrapper previewWrapper; private boolean isAborted; public PreviewWrapperInitializer(Locator locator, PreviewWrapper wrapper) { subjectLocator = locator; previewWrapper = wrapper; isAborted = false; } public void setAborted() { isAborted = true; } @Override public void run() { if(!isAborted) { try { currentPanel = PreviewFactory.create(subjectLocator); if(!isAborted) { if(currentPanel != null) { String locatorString = subjectLocator.toExternalForm(); if(locatorString.length() > 50) locatorString = locatorString.substring(0,50)+"..."; System.out.println("Created preview "+currentPanel.getClass()+" for "+locatorString); } else { currentUI = PreviewUtils.previewNoPreview(previewWrapper, subjectLocator); } } } catch(Exception e) { if(!isAborted) { currentUI = PreviewUtils.previewError(previewWrapper, "Creating preview failed.", e); } } catch(Error err) { if(!isAborted) { currentUI = PreviewUtils.previewError(previewWrapper, "Creating preview failed.", err); } } } if(currentPanel != null && !isAborted) { currentUI = currentPanel.getGui(); if(currentUI != null && !isAborted) { removeAll(); add(currentUI, BorderLayout.CENTER); setPreferredSize(currentUI.getPreferredSize()); } } revalidate(); repaint(); } } }
8,111
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PreviewFactory.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/PreviewFactory.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/>. * * * PreviewFactory.java */ package org.wandora.application.gui.previews; import org.wandora.application.Wandora; import org.wandora.application.gui.previews.formats.ApplicationC64; import org.wandora.application.gui.previews.formats.ApplicationPDF; import org.wandora.application.gui.previews.formats.ApplicationXML; import org.wandora.application.gui.previews.formats.ApplicationZ80; import org.wandora.application.gui.previews.formats.ApplicationZMachine; import org.wandora.application.gui.previews.formats.ApplicationZip; import org.wandora.application.gui.previews.formats.AudioFlac; import org.wandora.application.gui.previews.formats.AudioMP3v2; import org.wandora.application.gui.previews.formats.AudioMidi; import org.wandora.application.gui.previews.formats.AudioMod; import org.wandora.application.gui.previews.formats.AudioOgg; import org.wandora.application.gui.previews.formats.AudioSid; import org.wandora.application.gui.previews.formats.AudioWav; import org.wandora.application.gui.previews.formats.Image; import org.wandora.application.gui.previews.formats.Text; import org.wandora.application.gui.previews.formats.TextHTML; import org.wandora.application.gui.previews.formats.TextRTF; import org.wandora.application.gui.previews.formats.VideoMp4; import org.wandora.topicmap.Locator; /** * * @author anttirt, akivela */ public class PreviewFactory { /** * Creates a PreviewPanel used to show a preview for a locator, usually the * subject locator. Resolving a suitable preview for the locator is hard coded * into the method as a simple if-then statement. This may change in future * releases of the application. More dynamic preview resolver would be better. * All PreviewPanel classes contain a static method canView that tells if * the class can view the locator. Usually canView methods delegates the * test to the PreviewUtils.isOfType method. */ public static PreviewPanel create(final Locator locator) throws Exception { final Wandora wandora = Wandora.getWandora(); final String urlString = locator.toExternalForm(); PreviewPanel previewPanel = null; if(AudioMidi.canView(urlString)) { previewPanel = new AudioMidi(urlString); } else if(AudioFlac.canView(urlString)) { previewPanel = new AudioFlac(urlString); } else if(AudioOgg.canView(urlString)) { previewPanel = new AudioOgg(urlString); } else if(AudioSid.canView(urlString)) { previewPanel = new AudioSid(urlString); } else if(AudioMod.canView(urlString)) { previewPanel = new AudioMod(urlString); } else if(AudioWav.canView(urlString)) { previewPanel = new AudioWav(urlString); } else if(AudioMP3v2.canView(urlString)) { previewPanel = new AudioMP3v2(urlString); } else if(PreviewUtils.hasJavaFX() && VideoMp4.canView(urlString)) { previewPanel = new VideoMp4(urlString); } else if(Image.canView(urlString)) { previewPanel = new Image(urlString); } else if(ApplicationZMachine.canView(urlString)) { previewPanel = new ApplicationZMachine(urlString); } else if(ApplicationPDF.canView(urlString)) { previewPanel = new ApplicationPDF(urlString); } else if(ApplicationZ80.canView(urlString)) { previewPanel = new ApplicationZ80(urlString); } else if(ApplicationC64.canView(urlString)) { previewPanel = new ApplicationC64(urlString); } else if(TextRTF.canView(urlString)) { previewPanel = new TextRTF(urlString); } else if(TextHTML.canView(urlString)) { previewPanel = new TextHTML(urlString); } else if(ApplicationXML.canView(urlString)) { previewPanel = new ApplicationXML(urlString); } else if(Text.canView(urlString)) { previewPanel = new Text(urlString); } else if(ApplicationZip.canView(urlString)) { previewPanel = new ApplicationZip(urlString); } // If created panel is heavy-weight, wrap it into an AWRWrapper. if(previewPanel != null && previewPanel.isHeavy()) { return new AWTWrapper(previewPanel); } else { return previewPanel; } } }
5,315
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PreviewUtils.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/PreviewUtils.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.previews; import static org.wandora.utils.Option.none; import static org.wandora.utils.Option.some; import java.awt.BorderLayout; import java.awt.Desktop; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.ConnectException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.HashMap; import java.util.Map; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JPanel; import org.apache.tika.Tika; 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.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.topicmap.Locator; import org.wandora.utils.DataURL; import org.wandora.utils.Functional.Fn0; import org.wandora.utils.Functional.Fn1; import org.wandora.utils.IObox; import org.wandora.utils.Option; public class PreviewUtils { public static final Icon ICON_ZOOM_IN = UIBox.getIcon(0xf00e); public static final Icon ICON_ZOOM_OUT = UIBox.getIcon(0xf010); public static final Icon ICON_ZOOM_RESET = UIBox.getIcon(0xf002); public static final Icon ICON_COPY_IMAGE = UIBox.getIcon(0xf03e); public static final Icon ICON_COPY_LOCATION = UIBox.getIcon(0xf0c5); public static final Icon ICON_COPY_SELECTION = UIBox.getIcon(0xf0c5); public static final Icon ICON_OPEN_EXT = UIBox.getIcon(0xf14c); public static final Icon ICON_SAVE = UIBox.getIcon(0xf0c7); public static final Icon ICON_PRINT = UIBox.getIcon(0xf02f); public static final Icon ICON_PLAY = UIBox.getIcon(0xf04b); public static final Icon ICON_STOP = UIBox.getIcon(0xf04d); public static final Icon ICON_PAUSE = UIBox.getIcon(0xf04c); public static final Icon ICON_BACKWARD = UIBox.getIcon(0xf04a); public static final Icon ICON_FORWARD = UIBox.getIcon(0xf04e); public static final Icon ICON_START = UIBox.getIcon(0xf048); // In player go to start. public static final Icon ICON_END = UIBox.getIcon(0xf051); // In player go to end. public static final Icon ICON_PREVIOUS = UIBox.getIcon(0xf053); public static final Icon ICON_NEXT = UIBox.getIcon(0xf054); public static final Icon ICON_CONFIGURE = UIBox.getIcon(0xf013); public static final Icon ICON_INFO = UIBox.getIcon(0xf129); public static final Icon ICON_RESTART = UIBox.getIcon(0xf021); public static final Icon ICON_RELOAD_LOCATOR = UIBox.getIcon(0xf015); public static final Icon ICON_SET_BASENAME = UIBox.getIcon(0xf006); public static final Icon ICON_SET_DISPLAY_NAME = UIBox.getIcon(0xf006); public static final Icon ICON_SET_OCCURRENCE = UIBox.getIcon(0xf006); private static final Fn1<SimpleFileChooser, String> makeNamedChooser = new Fn1<SimpleFileChooser, String>() { @Override public SimpleFileChooser invoke(String path) { return new SimpleFileChooser(path); }}; private static final Fn0<SimpleFileChooser> makeChooser = new Fn0<SimpleFileChooser>() { @Override public SimpleFileChooser invoke() { return new SimpleFileChooser(); }}; public static InputStream makeInputStream(final ByteBuffer buffer) { return new InputStream() { @Override public synchronized int read() throws IOException { return buffer.hasRemaining() ? buffer.get() : -1; } @Override public int read(byte[] b, int off, int len) throws IOException { final int rv = Math.min(len, buffer.remaining()); buffer.get(b, off, rv); return rv == 0 ? -1 : rv; } }; } public static Option<String> getOption(final Map<String, String> options, final String key) { final String opt = options.get(key); if(opt != null) return some(opt); return none(); } // Transforms a string containing a path like "/home/antti/foo.bar" // into a URI containing "file:///home/antti/foo.bar". // If a conversion isn't possible, returns none() public static Fn1<Option<URI>, String> makeFileURI = new Fn1<Option<URI>, String>() { @Override public Option<URI> invoke(final String path) { try { //return some(new URI("file://" + path)); return some(new URI(path)); } catch(URISyntaxException e) { return none(); } } }; public static boolean startsWithAny(String str, String... args) { if(str != null) { for(String s : args) { if(str.startsWith(s)) { return true; } } } return false; } public static boolean endsWithAny(String str, String... args) { if(str != null) { for(String s : args) { if(str.endsWith(s)) return true; } } return false; } public static Option<String> choosePath( final Map<String, String> options, final JComponent dlgParent, final String optionsPrefix) { //try { final SimpleFileChooser chooser = new SimpleFileChooser(); if (chooser.open(dlgParent, SimpleFileChooser.SAVE_DIALOG) != SimpleFileChooser.APPROVE_OPTION) { return Option.none(); } //final String path = chooser.getSelectedFile().getCanonicalPath(); //options.put(optionsPrefix + "currentDirectory", chooser.getCurrentDirectory().getCanonicalPath()); return Option.some(chooser.getSelectedFile().toURI().toString()); /* } catch(IOException e) { // TODO: bad uri syntax, should log it; // currently the whole operation will just fail silently } return Option.none(); */ } /* { try { SimpleFileChooser chooser= new SimpleFileChooser(path); if (chooser.open(dlgParent, SimpleFileChooser.SAVE_DIALOG) != JFileChooser.APPROVE_OPTION) { return Option.none(); } path = chooser.getSelectedFile().getCanonicalPath(); if(options != null) options.put(optionsPrefix + "currentDirectory", chooser.getCurrentDirectory().getCanonicalPath()); return Option.some(path); } catch(IOException e) { // TODO: bad uri syntax, should log it; // currently the whole operation will just fail silently } return Option.none(); } */ // ------------------------------------------------------------------------- public static void forkExternalPlayer(String locator) { if(locator != null && locator.length() > 0) { if(!DataURL.isDataURL(locator)) { System.out.println("Spawning viewer for \""+locator+"\""); try { Desktop desktop = Desktop.getDesktop(); desktop.browse(new URI(locator)); } catch(IOException ioe) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Due to Java's security restrictions Wandora can't open some local URLs "+ "in external application. Copy and paste the locator manually to browser's "+ "address field to view the locator.", "Can't open the locator in external application", WandoraOptionPane.WARNING_MESSAGE); } catch(Exception e) { e.printStackTrace(); } } else { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Due to Java's security restrictions Wandora can't open the DataURI "+ "in external application. Copy and paste the locator manually to browser's "+ "address field to view the locator.", "Can't open the locator in external application", WandoraOptionPane.WARNING_MESSAGE); } } } // ------------------------------------------------------------------------- public static void saveToFile(String locator) { Wandora wandora = Wandora.getWandora(); SimpleFileChooser chooser = UIConstants.getFileChooser(); chooser.setDialogTitle("Save locator to file"); try { chooser.setSelectedFile(new File(locator.substring(locator.lastIndexOf(File.pathSeparator)+1))); } catch(Exception e) {} if(chooser.open(wandora, SimpleFileChooser.SAVE_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); try { if(DataURL.isDataURL(locator)) { DataURL.saveToFile(locator, file); } else if(locator.startsWith("file:")) { Files.copy(new File(new URL(URLDecoder.decode(locator, "UTF-8")).getFile()).toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING); } else { IObox.moveUrl(new URL(locator), file); } } catch(Exception e) { System.out.println("Exception '" + e.toString() + "' occurred while saving file '" + file.getPath() + "'."); } } } public static JPanel previewError(JPanel parent, String msg) { return previewError(parent, msg, (String) null); } public static JPanel previewError(JPanel parent, String msg, Error e) { if(e != null) { e.printStackTrace(); return previewError(parent, msg, e.toString()); } else { return previewError(parent, msg); } } public static JPanel previewError(JPanel parent, String msg, Exception e) { if(e != null) { e.printStackTrace(); return previewError(parent, msg, e.toString()); } else { return previewError(parent, msg); } } public static JPanel previewError(JPanel parent, String msg, String e) { JPanel errorPanel = new JPanel(); errorPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 20,20)); errorPanel.setBorder(BorderFactory.createLineBorder(java.awt.Color.RED, 4)); StringBuilder labelText = new StringBuilder("<html><center>"); if(msg != null) labelText.append(msg); if(e != null) { labelText.append("<br>"); labelText.append(e); } labelText.append("</center></html>"); SimpleLabel label = new SimpleLabel(); label.setText(labelText.toString()); label.setHorizontalAlignment(SimpleLabel.CENTER); errorPanel.add(label); if(parent != null) { parent.removeAll(); parent.add(errorPanel, BorderLayout.CENTER); parent.revalidate(); parent.repaint(); } return errorPanel; } public static JPanel previewLoadingMessage(JPanel parent) { JPanel loadingPanel = new JPanel(); loadingPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 20,20)); StringBuilder labelText = new StringBuilder("<html><center>"); labelText.append("Wait while loading and initializing the preview..."); labelText.append("</center></html>"); SimpleLabel label = new SimpleLabel(); label.setText(labelText.toString()); label.setHorizontalAlignment(SimpleLabel.CENTER); label.setIcon(UIBox.getIcon(0xf110)); loadingPanel.add(label); if(parent != null) { parent.removeAll(); parent.add(loadingPanel, BorderLayout.CENTER); parent.revalidate(); parent.repaint(); } return loadingPanel; } public static JPanel previewNoPreview(final PreviewWrapper previewWrapper, final Locator locator) { JPanel messagePanel = new JPanel(); messagePanel.setLayout(new BorderLayout()); JPanel labelPanel = new JPanel(); labelPanel.setLayout(new FlowLayout(FlowLayout.CENTER,20,20)); StringBuilder labelText = new StringBuilder("<html><center>"); labelText.append("Don't know how to view the locator."); labelText.append("</center></html>"); SimpleLabel label = new SimpleLabel(); label.setText(labelText.toString()); label.setHorizontalAlignment(SimpleLabel.CENTER); label.setIcon(UIBox.getIcon(0xf071)); label.setBounds(20,20,20,20); labelPanel.add(label); messagePanel.add(labelPanel, BorderLayout.NORTH); if(hasJavaFX()) { JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER,10,10)); SimpleButton button = new SimpleButton("Try webview any way"); button.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mimetypeCache.put(locator.toExternalForm(), "text/html"); previewWrapper.forceSetURL(locator); } catch(Exception ex) { ex.printStackTrace(); } } } ); buttonPanel.add(button); messagePanel.add(buttonPanel, BorderLayout.SOUTH); } if(previewWrapper != null) { previewWrapper.removeAll(); previewWrapper.add(messagePanel, BorderLayout.CENTER); previewWrapper.revalidate(); previewWrapper.repaint(); } return messagePanel; } private static HashMap<String,String> mimetypeCache = new HashMap(); private static int mimetypeCacheMaxSize = 9999; public static boolean isOfType(String url, String[] mimeTypes, String[] extensions) { if(url != null) { if(DataURL.isDataURL(url)) { // The url is a data-url and has explicit mimetype. try { DataURL dataURL = new DataURL(url); String mimeType = dataURL.getMimetype(); if(mimeType != null && mimeTypes != null) { String lowerCaseMimeType = mimeType.toLowerCase(); for(String testMimeType : mimeTypes) { if(lowerCaseMimeType.startsWith(testMimeType)) { return true; } } } } catch(Exception e) { // Ignore --> Can't view } } else { if(extensions != null && extensions.length > 0) { // Look at the given file extension list and test... String lowerCaseUrl = url.toLowerCase(); for(String extension : extensions) { if(extension != null) { if(!extension.startsWith(".")) { extension = "."+extension; } if(endsWithAny(lowerCaseUrl, extension)) { return true; } } } } // Extensions didn't work. Now look again the mime types and // deeper inside the url content. if(mimeTypes != null && mimeTypes.length > 0) { try { String urlDecoded = URLDecoder.decode(url, "utf-8"); URL realUrl = new URL(urlDecoded); if(realUrl != null) { String lowerCaseMimeType = null; if(mimetypeCache.containsKey(url)) { lowerCaseMimeType = mimetypeCache.get(url); } else { Tika tika = new Tika(); String mimeType = tika.detect(realUrl); lowerCaseMimeType = mimeType.toLowerCase(); if(mimetypeCache.size() > mimetypeCacheMaxSize) { mimetypeCache.clear(); } mimetypeCache.put(url, lowerCaseMimeType); } if(lowerCaseMimeType != null) { // System.out.println("Tika detected mimetype: "+lowerCaseMimeType); for(String testMimeType : mimeTypes) { if(lowerCaseMimeType.startsWith(testMimeType)) { return true; } } } } } catch(ConnectException ce) { mimetypeCache.put(url, null); System.out.println("ConnectException occurred while detecting preview's type: "+ce.toString()); } catch(FileNotFoundException fnfe) { mimetypeCache.put(url, null); System.out.println("FileNotFoundException occurred while detecting preview's type: "+fnfe.toString()); } catch(IllegalArgumentException iae) { mimetypeCache.put(url, null); System.out.println("IllegalArgumentException occurred while detecting preview's type: "+iae.toString()); } catch(Exception e) { System.out.println("PreviewUtils.canView fails after an exception: "+e.toString()); } catch(Error err) { System.out.println("PreviewUtils.canView fails after an error: "+err.toString()); } } } } return false; } public static boolean hasJavaFX() { try { Class jfxPanel = Class.forName("javafx.embed.swing.JFXPanel"); return true; } catch (ClassNotFoundException e) { return false; } } }
20,539
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PreviewPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/PreviewPanel.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/>. * * * PreviewPanel.java */ package org.wandora.application.gui.previews; import java.awt.Component; /** * * @author akivela */ public interface PreviewPanel { /** * Called whenever the PreviewPanel should stop i.e. exit. This is usually * called whenever the user closes the preview by closing the topic or by * opening another topic. The PreviewPanel should release all resources while * stopping. This method is usually called from the PreviewWrapper's stop * method. */ public void stop(); public void finish(); /** * Is called to get the actual preview component. Wandora places the preview * component into the user interface of the application. Usually the returned * component is JPanel containing various other components such as images and * buttons. This method is usually called from the PreviewWrapper. Running * the method has no time limit. PreviewWrapper views a loading message and * uses a separate thread to call the getGui, preventing the application to * freeze. */ public Component getGui(); /** * This is a deprecated method to tell the preview is a heavy weight * AWT component. These days Java can mix heavy weight and swing component, * and the isHeavy is not that important any more. Notice, returning a true * value actually triggers some additional wrapping for the component returned * by the getGui method. See AWTWrapper class for details. */ public boolean isHeavy(); }
2,351
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AWTWrapper.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/AWTWrapper.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.previews; import java.awt.Component; import java.awt.Dimension; import java.awt.Panel; import java.awt.Point; import java.awt.Rectangle; import javax.swing.JPanel; import javax.swing.JViewport; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.wandora.application.Wandora; import org.wandora.application.gui.topicpanels.traditional.AbstractTraditionalTopicPanel; /** * * @author anttirt */ public class AWTWrapper extends JPanel implements PreviewPanel { private static final long serialVersionUID = 1L; private Panel heavyContainer; private PreviewPanel innerPanel; private Dimension prefSize; private Wandora wandora; public AWTWrapper(PreviewPanel inner) { innerPanel = inner; setLayout(null); heavyContainer = new java.awt.Panel(); add(heavyContainer); heavyContainer.add((Component)innerPanel); setSize(innerPanel.getGui().getPreferredSize()); heavyContainer.setSize(getSize()); heavyContainer.repaint(); wandora = Wandora.getWandora(); final JViewport vp = wandora.getViewPort(); cl = new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { Rectangle viewRec = vp.getViewRect(); try { Point p = getTopDistance(); viewRec.x -= p.x; viewRec.y -= p.y; resizeHeavy(viewRec); } catch(Exception ex) { System.err.println(ex.toString()); } } }; prefSize = innerPanel.getGui().getPreferredSize(); setSize(prefSize); setPreferredSize(prefSize); setMinimumSize(prefSize); setMaximumSize(prefSize); heavyContainer.setBounds(new Rectangle(0, 0, getWidth(), getHeight())); heavyContainer.repaint(); wandora.getViewPort().addChangeListener(cl); } @Override public boolean isHeavy() { return true; } private void resizeHeavy(Rectangle newRec) { final Rectangle myBounds = new Rectangle(0, 0, prefSize.width, prefSize.height); if(newRec.contains(myBounds)) { heavyContainer.setBounds(myBounds); } else { final Rectangle heavyBounds = newRec.intersection(myBounds); heavyContainer.setBounds(heavyBounds); innerPanel.getGui().setLocation(-heavyBounds.x, -heavyBounds.y); } } private Point getTopDistance() throws Exception { Component c = this; Point ret = new Point(); while(!AbstractTraditionalTopicPanel.class.isInstance(c)) { ret.x += c.getX(); ret.y += c.getY(); c = c.getParent(); if(c == null) throw new Exception("Couldn't find a topic panel in the parent chain!"); } return ret; } private final ChangeListener cl; @Override public void stop() { innerPanel.stop(); } @Override public void finish() { innerPanel.finish(); heavyContainer.remove((Component)innerPanel); wandora.getViewPort().removeChangeListener(cl); innerPanel = null; } @Override public Component getGui() { return this; } }
4,315
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TextRTF.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/TextRTF.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.previews.formats; import java.awt.Color; import java.awt.Cursor; import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.text.rtf.RTFEditorKit; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.utils.DataURL; /** * * @author akivela */ public class TextRTF extends Text { public TextRTF(String locator) { super(locator); } @Override protected JComponent getTextComponent(String locator) throws Exception { RTFEditorKit rtf = new RTFEditorKit(); JEditorPane textComponent = new JEditorPane(); textComponent.setEditorKit(rtf); textComponent.setBackground(Color.WHITE); if(locator.startsWith("file:")) { FileInputStream in = new FileInputStream(new URL(locator).getFile()); rtf.read(in, textComponent.getDocument(), 0); } else if(DataURL.isDataURL(locator)) { DataURL dataUrl = new DataURL(locator); ByteArrayInputStream in = new ByteArrayInputStream(dataUrl.getData()); rtf.read(in, textComponent.getDocument(), 0); } else { InputStream in = new URL(locator).openStream(); rtf.read(in, textComponent.getDocument(), 0); } textComponent.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); textComponent.setEditable(false); textComponent.setCaretPosition(0); return textComponent; } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "text/rtf", "application/rtf" }, new String[] { "rtf" } ); } }
2,773
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApplicationZip.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/ApplicationZip.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.previews.formats; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; 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.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.application.tools.extractors.files.SimpleFileExtractor; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import org.wandora.utils.IObox; import org.wandora.utils.MimeTypes; /** * * @author akivela */ public class ApplicationZip implements PreviewPanel, ActionListener { private final String locator; JPanel ui = null; JTable table = null; public ApplicationZip(String zipLocator) { this.locator = zipLocator; } @Override public void stop() { } @Override public void finish() { } @Override public JPanel getGui() { if(ui == null) { ui = new JPanel(); ui.setLayout(new BorderLayout(8,8)); JPanel tablePaneWrapper = new JPanel(); tablePaneWrapper.setLayout(new BorderLayout()); tablePaneWrapper.setPreferredSize(new Dimension(640, 300)); tablePaneWrapper.setMaximumSize(new Dimension(640, 300)); tablePaneWrapper.setSize(new Dimension(640, 300)); try { table = new ZipTable(locator); JScrollPane scrollPane = new SimpleScrollPane(table); tablePaneWrapper.add(scrollPane, BorderLayout.CENTER); JPanel toolbarWrapper = new JPanel(); toolbarWrapper.add(getJToolBar()); ui.add(tablePaneWrapper, BorderLayout.CENTER); ui.add(toolbarWrapper, BorderLayout.SOUTH); } catch(Exception e) { PreviewUtils.previewError(ui, "Can't initialize zip viewer. Exception occurred.", e); } } return ui; } @Override public boolean isHeavy() { return false; } protected JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { "Open ext", PreviewUtils.ICON_OPEN_EXT, this, "Copy location", PreviewUtils.ICON_COPY_LOCATION, this, "Save", PreviewUtils.ICON_SAVE, this, "Unzip", PreviewUtils.ICON_SAVE, this, }, this); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c == null) return; if(c.startsWith("Open ext")) { PreviewUtils.forkExternalPlayer(locator); } else if(c.equalsIgnoreCase("Copy location")) { if(locator != null) { ClipboardBox.setClipboard(locator); } } else if(c.startsWith("Save")) { PreviewUtils.saveToFile(locator); } else if(c.startsWith("Unzip")) { unzip(locator); } } // ------------------------------------------------------------------------- private void unzip(String locator) { byte[] buffer = new byte[1024]; try { String savePath = getSavePath(); if(savePath == null) return; ZipInputStream zipInputStream = null; if(DataURL.isDataURL(locator)) { DataURL dataUrl = new DataURL(locator); zipInputStream = new ZipInputStream(dataUrl.getDataStream()); } else { zipInputStream = new ZipInputStream(new URL(locator).openStream()); } //create output directory is not exists File folder = new File(savePath); if(!folder.exists()){ folder.mkdir(); } //get the zipped file list entry ZipEntry zipEntry = zipInputStream.getNextEntry(); while(zipEntry != null) { String fileName = zipEntry.getName(); File newFile = new File(savePath + File.separator + fileName); System.out.println("file unzip : "+ newFile.getAbsoluteFile()); //create all non exists folders //else you will hit FileNotFoundException for compressed folder new File(newFile.getParent()).mkdirs(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zipInputStream.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); zipEntry = zipInputStream.getNextEntry(); } zipInputStream.closeEntry(); zipInputStream.close(); System.out.println("Done"); } catch(Exception ex) { ex.printStackTrace(); } } protected String getSavePath() { SimpleFileChooser chooser = UIConstants.getFileChooser(); chooser.setDialogTitle("Select folder"); chooser.setApproveButtonText("Select"); if(chooser.open(Wandora.getWandora(),SimpleFileChooser.SAVE_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { File selected = chooser.getSelectedFile(); if(selected != null) { if(!selected.isDirectory()) { selected = selected.getParentFile(); } return selected.getAbsolutePath(); } } return null; } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "application/zip", }, new String[] { "zip" } ); } // ------------------------------------------------------------------------- // ------------------------------------------------------------ ZipTable --- // ------------------------------------------------------------------------- public class ZipTable extends JTable implements ActionListener { private ZipTableModel model = null; TableRowSorter rowSorter = null; public ZipTable(String locator) { super(); model = new ZipTableModel(locator); this.setModel(model); rowSorter = new TableRowSorter(model); this.setRowSorter(rowSorter); rowSorter.setSortsOnUpdates(true); JPopupMenu popup = UIBox.makePopupMenu(getPopupStruct(), this); setComponentPopupMenu(popup); this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } public Object[] getPopupStruct() { return new Object[] { "Save to file...", "Save to occurrence...", "Save to topic..." }; } @Override public void actionPerformed(ActionEvent e) { System.out.println("actionPerformed: "+e.getActionCommand()); String command = e.getActionCommand(); if(command != null) { if("Save to file...".equalsIgnoreCase(command)) { int[] selectedRows = this.getSelectedRows(); saveToFile(selectedRows); } else if("Save to occurrence...".equalsIgnoreCase(command)) { int[] selectedRows = this.getSelectedRows(); saveToOccurrence(selectedRows); } else if("Save to topic...".equalsIgnoreCase(command)) { int[] selectedRows = this.getSelectedRows(); saveToTopic(selectedRows); } } } // --------------------------------------------------------------------- private void saveToFile(int[] rows) { if(rows != null) { String savePath = null; if(rows.length > 1) { savePath = getSavePath(); if(savePath == null) { return; } } for(int i=0; i<rows.length; i++) { int selectedRow = rows[i]; ZipTableRow zipTableRow = model.getZipTableRowAt(selectedRow); if(zipTableRow != null) { byte[] zipData = model.getData(zipTableRow.filename); if(zipData != null) { saveToFile(savePath, zipTableRow.filename, zipData); } } } } } private void saveToFile(String savePath, String originalFilename, byte[] data) { Wandora wandora = Wandora.getWandora(); try { if(savePath == null) { SimpleFileChooser chooser = UIConstants.getFileChooser(); chooser.setDialogTitle("Save file"); String originalFilenamePart = originalFilename.substring(originalFilename.lastIndexOf(File.pathSeparator)+1); chooser.setSelectedFile(new File(originalFilenamePart)); if(chooser.open(wandora,SimpleFileChooser.SAVE_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { IObox.saveBFile(chooser.getSelectedFile().getAbsolutePath(), data); } } else { String saveFilename = savePath+File.pathSeparator+originalFilename; IObox.createPathFor(new File(saveFilename)); IObox.saveBFile(saveFilename, data); } } catch(Exception e) { wandora.handleError(e); } } // --------------------------------------------------------------------- private void saveToOccurrence(int[] rows) { if(rows != null) { for(int i=0; i<rows.length; i++) { int selectedRow = rows[i]; ZipTableRow zipTableRow = model.getZipTableRowAt(selectedRow); if(zipTableRow != null) { byte[] zipData = model.getData(zipTableRow.filename); if(zipData != null) { saveToOccurrence(zipTableRow.filename, zipData); } } } } } private void saveToOccurrence(String filename, byte[] data) { Wandora wandora = Wandora.getWandora(); try { Topic topic = wandora.getOpenTopic(); if(topic != null) { Topic type = wandora.showTopicFinder(wandora, "Select occurrence type for "+filename); if(type == null) return; Topic scope = wandora.showTopicFinder(wandora, "Select occurrence scope for "+filename); if(scope == null) return; int makeDataUrl = WandoraOptionPane.showConfirmDialog(wandora, "Make data url occurrence for '"+filename+"'?", "Make data url occurrence?", WandoraOptionPane.YES_NO_OPTION); if(makeDataUrl == WandoraOptionPane.YES_OPTION) { DataURL dataUrl = new DataURL(data); String mimetype = MimeTypes.getMimeType(filename); if(mimetype != null) { dataUrl.setMimetype(mimetype); } topic.setData(type, scope, dataUrl.toExternalForm()); } else { topic.setData(type, scope, new String(data)); } wandora.doRefresh(); } } catch(Exception e) { wandora.handleError(e); } } // --------------------------------------------------------------------- private void saveToTopic(int[] rows) { if(rows != null) { for(int i=0; i<rows.length; i++) { int selectedRow = rows[i]; ZipTableRow zipTableRow = model.getZipTableRowAt(selectedRow); if(zipTableRow != null) { byte[] zipData = model.getData(zipTableRow.filename); if(zipData != null) { saveToTopic(zipTableRow.filename, zipData); } } } } } private void saveToTopic(String filename, byte[] data) { Wandora wandora = Wandora.getWandora(); try { TopicMap topicMap = wandora.getTopicMap(); DataURL dataUrl = new DataURL(data); String mimetype = MimeTypes.getMimeType(filename); if(mimetype != null) { dataUrl.setMimetype(mimetype); } SimpleFileExtractor simpleFileExtractor = new SimpleFileExtractor(); simpleFileExtractor._extractTopicsFrom(dataUrl.toExternalForm(), topicMap); wandora.doRefresh(); } catch(Exception e) { wandora.handleError(e); } } // --------------------------------------------------------------------- public class ZipTableModel extends DefaultTableModel { ArrayList<ZipTableRow> zipData; int numberOfFields = 6; DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String locator = null; public ZipTableModel(String locator) { this.locator = locator; this.zipData = createModel(locator); } @Override public int getColumnCount() { return numberOfFields; } @Override public Class getColumnClass(int col) { switch(col) { case 0: return String.class; case 1: return String.class; case 2: return Long.class; case 3: return Long.class; case 4: return String.class; case 5: return String.class; } return String.class; } @Override public int getRowCount() { if(zipData != null) return zipData.size(); return 0; } public ZipTableRow getZipTableRowAt(int rowIndex) { try { return zipData.get(rowIndex); } catch(Exception e) { e.printStackTrace(); } return null; } @Override public Object getValueAt(int rowIndex, int columnIndex) { try { if(zipData != null && rowIndex >= 0 && columnIndex >= 0 && columnIndex < getColumnCount() && rowIndex < getRowCount()) { ZipTableRow zipDataRow = zipData.get(rowIndex); switch(columnIndex) { case 0: return zipDataRow.filename; case 1: return zipDataRow.isFolder ? "Folder" : "File"; case 2: return zipDataRow.compressedSize; case 3: return zipDataRow.size; case 4: return zipDataRow.creationTime == 0 ? "" : dateFormatter.format(new Date(zipDataRow.creationTime)); case 5: return zipDataRow.modifiedTime == 0 ? "" : dateFormatter.format(new Date(zipDataRow.modifiedTime)); } } } catch (Exception e) {} return ""; } @Override public String getColumnName(int columnIndex) { switch(columnIndex) { case 0: return "Filename"; case 1: return "Type"; case 2: return "Compressed size"; case 3: return "Size"; case 4: return "Creation time"; case 5: return "Modified time"; } return ""; } @Override public boolean isCellEditable(int row,int col){ return false; } private ArrayList<ZipTableRow> createModel(String locator) { ArrayList<ZipTableRow> zipModel = new ArrayList<ZipTableRow>(); ZipInputStream zipInputStream = null; try { if(DataURL.isDataURL(locator)) { DataURL dataUrl = new DataURL(locator); zipInputStream = new ZipInputStream(dataUrl.getDataStream()); } else { zipInputStream = new ZipInputStream(new URL(locator).openStream()); } ZipEntry zipEntry = zipInputStream.getNextEntry(); while(zipEntry != null) { ZipTableRow zipTableRow = new ZipTableRow(); zipTableRow.filename = zipEntry.getName(); zipTableRow.compressedSize = zipEntry.getCompressedSize(); zipTableRow.size = zipEntry.getSize(); zipTableRow.time = zipEntry.getTime(); if(zipEntry.getCreationTime() != null) { zipTableRow.creationTime = zipEntry.getCreationTime().toMillis(); } if(zipEntry.getLastModifiedTime() != null) { zipTableRow.modifiedTime = zipEntry.getLastModifiedTime().toMillis(); } zipTableRow.isFolder = zipEntry.isDirectory(); zipModel.add(zipTableRow); zipInputStream.closeEntry(); zipEntry = zipInputStream.getNextEntry(); } } catch(Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if(zipInputStream != null) { try { zipInputStream.close(); } catch(Exception e) {} } } return zipModel; } public byte[] getData(String entryName) { ZipInputStream zipInputStream = null; byte[] entryData = null; try { if(DataURL.isDataURL(locator)) { DataURL dataUrl = new DataURL(locator); zipInputStream = new ZipInputStream(dataUrl.getDataStream()); } else { zipInputStream = new ZipInputStream(new URL(locator).openStream()); } ZipEntry zipEntry = zipInputStream.getNextEntry(); while(zipEntry != null && entryData == null) { String zipEntryName = zipEntry.getName(); if(zipEntryName.equals(entryName)) { int n = 0; byte[] buf = new byte[1024]; ByteArrayOutputStream out = new ByteArrayOutputStream(); while ((n = zipInputStream.read(buf, 0, 1024)) > -1) { out.write(buf, 0, n); } out.close(); zipInputStream.closeEntry(); entryData = out.toByteArray(); } zipEntry = zipInputStream.getNextEntry(); } } catch(Exception e) { e.printStackTrace(); } try { zipInputStream.close(); } catch(Exception e) {} return entryData; } } public class ZipTableRow { public String filename = null; public long compressedSize = 0; public long size = 0; public long time = 0; public long creationTime = 0; public long modifiedTime = 0; public boolean isFolder = false; } } }
23,534
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AudioOgg.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/AudioOgg.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.previews.formats; import org.wandora.application.gui.previews.PreviewUtils; /** * * @author akivela */ public class AudioOgg extends AudioAbstract { public AudioOgg(String locator) { super(locator); } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "audio/ogg", "application/ogg", }, new String[] { "ogg", "ogx" } ); } }
1,515
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApplicationZMachine.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/ApplicationZMachine.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.previews.formats; import static org.wandora.application.gui.previews.PreviewUtils.startsWithAny; import java.awt.BorderLayout; import java.awt.Component; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.StringTokenizer; import javax.swing.JComponent; import javax.swing.JPanel; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import org.zmpp.swingui.PanelMachineFactory; import org.zmpp.swingui.ZmppPanel; import org.zmpp.vm.Machine; /** * Uses and is based on Wei-ju Wu's ZMMP (The Z-machine Preservation) Project. * * @author akivela */ public class ApplicationZMachine implements ActionListener, PreviewPanel { private String locator = null; private JPanel ui = null; private ZmppPanel gamePanel = null; private Machine machine = null; public ApplicationZMachine(String loc) { this.locator = loc; } public void runStory(String locator) { PanelMachineFactory factory = null; // First get a game factory with the locator. The factory is always // PanelMachineFactory but the instantiation varies and depends on the // locator. Locator can be either a file, an url or a dataurl. try { if(DataURL.isDataURL(locator)) { DataURL storyDataURL = new DataURL(locator); byte[] storyData = storyDataURL.getData(); if(storyDataURL.getMimetype().contains("application/x-blorb")) { factory = new PanelMachineFactory(storyData); // storyData == blorb } else { factory = new PanelMachineFactory(storyData, null); } } else if(locator.startsWith("file:")) { File storyFile = new File((new URL(locator)).toURI()); if(storyFile.isFile() && storyFile.exists()) { String filename = storyFile.getName(); if(filename.endsWith("zblorb") || filename.endsWith("zlb")) { factory = new PanelMachineFactory(storyFile); // storyFile == blorb } else { File blorbfile = searchForResources(storyFile); factory = new PanelMachineFactory(storyFile, blorbfile); } } } else { if(locator.endsWith("zblorb") || locator.endsWith("zlb")) { factory = new PanelMachineFactory(null, new URL(locator)); } else { factory = new PanelMachineFactory(new URL(locator), null); } } } catch(MalformedURLException mfue) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Illegal URL used as a Z Machine source.", "Illegal URL", WandoraOptionPane.WARNING_MESSAGE); } catch(Exception e) { e.printStackTrace(); } // Now we should have a valid game factory. Create ui and start the game. if(factory != null) { try { machine = factory.buildMachine(); gamePanel = factory.getUI(); gamePanel.startMachine(); } catch(IOException ioe) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Could not read the Z Machine source.", "Read error", WandoraOptionPane.WARNING_MESSAGE); } catch(Exception e) { e.printStackTrace(); } } else { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "Could not initialize game.", "Story file error", WandoraOptionPane.WARNING_MESSAGE); } } /** * Tries to find a resource file in Blorb format. * * @param storyfile the storyfile * @return the blorb file if one exists or null */ private static File searchForResources(File storyfile) { StringTokenizer tok = new StringTokenizer(storyfile.getName(), "."); String prefix = tok.nextToken(); String dir = storyfile.getParent(); String blorbpath1 = ((dir != null) ? dir + System.getProperty("file.separator") : "") + prefix + ".blb"; String blorbpath2 = ((dir != null) ? dir + System.getProperty("file.separator") : "") + prefix + ".blorb"; File blorbfile1 = new File(blorbpath1); if (blorbfile1.exists()) return blorbfile1; File blorbfile2 = new File(blorbpath2); if (blorbfile2.exists()) return blorbfile2; return null; } private JPanel makeUI() { JPanel ui = new JPanel(); JPanel controllerPanel = new JPanel(); controllerPanel.add(getJToolBar(), BorderLayout.CENTER); if(gamePanel == null) { try { runStory(locator); } catch(Exception e) { e.printStackTrace(); } } JPanel gameWrapperPanel = new JPanel(); if(gamePanel != null) gameWrapperPanel.add(gamePanel, BorderLayout.CENTER); ui.setLayout(new BorderLayout(8,8)); ui.add(gameWrapperPanel, BorderLayout.CENTER); ui.add(controllerPanel, BorderLayout.SOUTH); return ui; } protected JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { // "Restart", PreviewUtils.ICON_RESTART, this, // "Info", PreviewUtils.ICON_INFO, this, "Preferences", PreviewUtils.ICON_CONFIGURE, this, "Copy location", PreviewUtils.ICON_COPY_LOCATION, this, "Open ext", PreviewUtils.ICON_OPEN_EXT, this, "Save", PreviewUtils.ICON_SAVE, this, }, this); } @Override public void stop() { if(machine != null) { System.out.println("Stopping machine!"); /* Input in = machine.getInput(); if(in != null) { in.close(); } Output out = machine.getOutput(); if(out != null) { out.close(); } Cpu cpu = machine.getCpu(); if(cpu != null) { cpu.setRunning(false); } */ } } @Override public void finish() { if(machine != null) { System.out.println("Finishing machine!"); /* Input in = machine.getInput(); if(in != null) { in.close(); } Output out = machine.getOutput(); if(out != null) { out.close(); } Cpu cpu = machine.getCpu(); if(cpu != null) { cpu.setRunning(false); } */ } } @Override public Component getGui() { if(ui == null) { ui = makeUI(); } return ui; } @Override public boolean isHeavy() { return false; } @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if(startsWithAny(cmd, "Preferences")) { EventQueue.invokeLater(new Runnable() { public void run() { if(gamePanel != null) { gamePanel.editPreferences(Wandora.getWandora()); } } }); } else if(startsWithAny(cmd, "Info")) { EventQueue.invokeLater(new Runnable() { public void run() { if(gamePanel != null) { gamePanel.aboutGame(Wandora.getWandora()); } } }); } else if(startsWithAny(cmd, "Restart")) { EventQueue.invokeLater(new Runnable() { public void run() { if(machine != null) { machine.restart(); } } }); } else if(startsWithAny(cmd, "Stop")) { EventQueue.invokeLater(new Runnable() { public void run() { if(machine != null) { machine.restart(); } } }); } else if(startsWithAny(cmd, "Open ext")) { if(locator != null) { PreviewUtils.forkExternalPlayer(locator); } } else if(startsWithAny(cmd, "Copy location")) { if(locator != null) { ClipboardBox.setClipboard(locator); } } else if(startsWithAny(cmd, "Save")) { if(locator != null) { PreviewUtils.saveToFile(locator); } } } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "application/x-zmachine", "application/x-zmachine-1", "application/x-zmachine-2", "application/x-zmachine-3", "application/x-zmachine-4", "application/x-zmachine-5", "application/x-zmachine-6", "application/x-zmachine-7", "application/x-zmachine-8", "application/x-blorb" }, new String[] { "z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8", "zblorb", "zlb" } ); } }
11,537
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AudioMP3v2.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/AudioMP3v2.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.previews.formats; import org.wandora.application.gui.previews.PreviewUtils; /** * * @author akivela */ public class AudioMP3v2 extends AudioAbstract { public AudioMP3v2(String locator) { super(locator); } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "audio/mpeg", "audio/x-mpeg-3", "audio/mpeg3" }, new String[] { "mp3" } ); } }
1,527
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApplicationXML.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/ApplicationXML.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/>. * * * ApplicationXML.java * * */ package org.wandora.application.gui.previews.formats; import java.awt.Cursor; import java.awt.Font; import java.awt.event.ActionListener; import javax.swing.JComponent; import javax.swing.JTextPane; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; /** * * @author akivela */ public class ApplicationXML extends Text implements ActionListener, PreviewPanel { /** Creates a new instance of ApplicationXML */ public ApplicationXML(String locator) { super(locator); } @Override protected JComponent getTextComponent(String locator) throws Exception { JTextPane textComponent = new JTextPane(); textComponent.setText(getContent(locator)); textComponent.setFont(new Font("monospaced", Font.PLAIN, 12)); textComponent.setEditable(false); textComponent.setCaretPosition(0); textComponent.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); return textComponent; } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "application/xml", "text/xml" }, new String[] { "xml" } ); } }
2,277
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AudioMP3.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/AudioMP3.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/>. * * * AudioMP3.java * * */ package org.wandora.application.gui.previews.formats; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.JPanel; import javax.swing.JPopupMenu; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import javazoom.jl.player.Player; /** * * @author akivela */ public class AudioMP3 extends JPanel implements Runnable, MouseListener, ActionListener, PreviewPanel { private static final String OPTIONS_PREFIX = "gui.audioMP3PreviewPanel."; Map<String, String> options; String audioLocator; Dimension panelDimensions; BufferedImage bgImage; boolean isPlaying = false; Player player = null; /** Creates a new instance of AudioMP3 */ public AudioMP3(String audioLocator) { this.audioLocator = audioLocator; initialize(); } @Override public boolean isHeavy() { return false; } public void initialize() { this.options = Wandora.getWandora().getOptions().asMap(); this.addMouseListener(this); bgImage = UIBox.getImage("gui/icons/doctype/doctype_audio_mp3.png"); panelDimensions = new Dimension(100, 100); this.setPreferredSize(panelDimensions); this.setMaximumSize(panelDimensions); this.setMinimumSize(panelDimensions); repaint(); revalidate(); updateAudioMenu(); } @Override public void paint(Graphics g) { super.paint(g); if(bgImage != null) { g.drawImage(bgImage,0,0,this); } } @Override public void finish() { isPlaying = false; if(player != null) player.close(); } @Override public void stop() { isPlaying = false; if(player != null) player.close(); } @Override public JPanel getGui() { return this; } public void run() { try { isPlaying = true; playMP3(audioLocator); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } private void playMP3(String audioLocator) throws Exception { if(DataURL.isDataURL(audioLocator)) { DataURL dataURL = new DataURL(audioLocator); player = new Player(new ByteArrayInputStream(dataURL.getData())); } else { URL audioURL = new URL(audioLocator); player = new Player(audioURL.openStream()); } player.play(); } public void play() { if(!isPlaying) { if(audioLocator != null && audioLocator.length() > 0) { Thread audioThread = new Thread(this); audioThread.start(); } } } @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { if(mouseEvent.getButton() == MouseEvent.BUTTON1 && mouseEvent.getClickCount() >= 2) { play(); } } @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 updateAudioMenu() { if(audioLocator != null && audioLocator.length() > 0) { this.setComponentPopupMenu(getImageMenu()); } else { this.setComponentPopupMenu(null); } } public JPopupMenu getImageMenu() { Object[] menuStructure = new Object[] { "Play", "Stop", "---", "Copy audio location", "---", "Open in external player...", "---", "Save audio as...", }; return UIBox.makePopupMenu(menuStructure, this); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c == null) return; if(c.startsWith("Play")) { play(); } else if(c.startsWith("Stop")) { isPlaying = false; if(player != null) { player.close(); } } else if(c.startsWith("Open in external")) { PreviewUtils.forkExternalPlayer(audioLocator); } else if(c.equalsIgnoreCase("Copy audio location")) { if(audioLocator != null) { ClipboardBox.setClipboard(audioLocator); } } else if(c.startsWith("Save audio")) { PreviewUtils.saveToFile(audioLocator); } } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "audio/mpeg", "audio/x-mpeg-3", "audio/mpeg3" }, new String[] { "mp3", "m3a" } ); } }
7,135
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AudioMidi.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/AudioMidi.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/>. * * * AudioMidi.java * * Created on 29. toukokuuta 2006, 14:33 * */ package org.wandora.application.gui.previews.formats; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MetaEventListener; import javax.sound.midi.MetaMessage; import javax.sound.midi.MidiChannel; import javax.sound.midi.MidiSystem; import javax.sound.midi.MidiUnavailableException; import javax.sound.midi.Sequence; import javax.sound.midi.Sequencer; import javax.sound.midi.Synthesizer; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JPopupMenu; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; /** * * @author akivela */ public class AudioMidi implements ActionListener, MetaEventListener, PreviewPanel { private static final String OPTIONS_PREFIX = "gui.audioMidiPreviewPanel."; //Wandora admin; private Map<String, String> options; private String audioLocator; private Dimension panelDimensions; private BufferedImage bgImage; private boolean isPlaying = false; private Sequencer sequencer = null; private int volume = 100; private JPanel ui = null; public AudioMidi(String audioLocator) { this.audioLocator = audioLocator; initialize(); } @Override public boolean isHeavy() { return false; } public void initialize() { this.options = Wandora.getWandora().getOptions().asMap(); } @Override public void finish() { isPlaying = false; if(sequencer != null) sequencer.stop(); } @Override public JPanel getGui() { if(ui == null) { ui = makeUI(); } return ui; } @Override public void stop() { isPlaying = false; if(sequencer != null) sequencer.stop(); } protected JPanel makeUI() { if(ui == null) { ui = new JPanel(); JPanel controllerPanel = new JPanel(); controllerPanel.add(getJToolBar(), BorderLayout.CENTER); ui.setLayout(new BorderLayout(8,8)); ui.add(controllerPanel, BorderLayout.SOUTH); updateAudioMenu(); } return ui; } protected JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { "Play", PreviewUtils.ICON_PLAY, this, "Stop", PreviewUtils.ICON_STOP, this, "---", "Copy location", PreviewUtils.ICON_COPY_LOCATION, this, "Open ext", PreviewUtils.ICON_OPEN_EXT, this, "Save as", PreviewUtils.ICON_SAVE, this, }, this); } public void play() { if(!isPlaying) { if(audioLocator != null && audioLocator.length() > 0) { try { sequencer = MidiSystem.getSequencer(); sequencer.open(); Sequence sequence = null; if(DataURL.isDataURL(audioLocator)) { DataURL dataURL = new DataURL(audioLocator); sequence = MidiSystem.getSequence(new ByteArrayInputStream(dataURL.getData())); } else { URL audioURL = new URL(audioLocator); sequence = MidiSystem.getSequence(audioURL); } if(sequence != null) { sequencer.setSequence(sequence); sequencer.addMetaEventListener(this); // Start playing. sequencer.start(); } } catch (MidiUnavailableException e) { PreviewUtils.previewError(ui, "Midi is unavailable.", e); } catch (MalformedURLException e) { PreviewUtils.previewError(ui, "Midi locator is malformed.", e); } catch (IOException e) { PreviewUtils.previewError(ui, "Unable to read locator resource.", e); } catch (InvalidMidiDataException e) { PreviewUtils.previewError(ui, "Midi resource contains bad data.", e); } } } } @Override public void meta(MetaMessage event) { if (event.getType() == 47) { isPlaying = false; } } public void setVolume(int gain) { try { if(sequencer != null) { Synthesizer synthesizer = null; if(sequencer instanceof Synthesizer) { synthesizer = (Synthesizer) sequencer; } else { synthesizer = MidiSystem.getSynthesizer(); } if(synthesizer != null) { MidiChannel[] channels = synthesizer.getChannels(); for (int i=0; i<channels.length; i++) { channels[i].controlChange(7, (int)(gain * 1.27)); // gain == 0..100 } volume = gain; } } } catch(Exception e) { e.printStackTrace(); } } // ------------------------------------------------------------------------- public void updateAudioMenu() { if(ui != null) { if(audioLocator != null && audioLocator.length() > 0) { ui.setComponentPopupMenu(getImageMenu()); } else { ui.setComponentPopupMenu(null); } } } public JPopupMenu getImageMenu() { Object[] menuStructure = new Object[] { "Play", "Stop", /* "Set volume", new Object[] { (volume == 100 ? "X" : "O") + " Volume 100%", (volume == 75 ? "X" : "O") + " Volume 75%", (volume == 50 ? "X" : "O") + " Volume 50%", (volume == 25 ? "X" : "O") + " Volume 25%", }, */ "---", "Copy locator", "---", "Open in external player...", "---", "Save to file...", }; return UIBox.makePopupMenu(menuStructure, this); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c == null) return; if(PreviewUtils.startsWithAny(c, "Play")) { play(); } else if(PreviewUtils.startsWithAny(c, "Stop")) { isPlaying = false; if(sequencer != null) sequencer.stop(); } else if(PreviewUtils.startsWithAny(c, "Open in external", "Open ext")) { PreviewUtils.forkExternalPlayer(audioLocator); } else if(PreviewUtils.startsWithAny(c, "Copy locator")) { if(audioLocator != null) { ClipboardBox.setClipboard(audioLocator); } } else if(PreviewUtils.startsWithAny(c, "Save to file", "Save as")) { PreviewUtils.saveToFile(audioLocator); } else if(PreviewUtils.startsWithAny(c, "Volume 100%")) { setVolume(100); } else if(PreviewUtils.startsWithAny(c, "Volume 75%")) { setVolume(75); } else if(PreviewUtils.startsWithAny(c, "Volume 50%")) { setVolume(50); } else if(PreviewUtils.startsWithAny(c, "Volume 25%")) { setVolume(25); } } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "audio/midi", "application/x-midi", }, new String[] { ".mid", ".midi", ".rmf" } ); } }
9,549
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AudioWav.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/AudioWav.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/>. * * * AudioWav.java * * Created on 29. toukokuuta 2006, 14:33 * */ package org.wandora.application.gui.previews.formats; import static org.wandora.application.gui.previews.PreviewUtils.startsWithAny; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JPopupMenu; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; /** * * @author akivela */ public class AudioWav extends JPanel implements Runnable, MouseListener, ActionListener, PreviewPanel { private static final String OPTIONS_PREFIX = "gui.audioSamplePreviewPanel."; private Map<String, String> options; private String audioLocator; private boolean isPlaying = false; private SourceDataLine player = null; private JPanel wrapperPanel = null; private WaveformPanel waveformPanel = null; private long frameLength = 0; /** Creates a new instance of AudioSample */ public AudioWav(String audioLocator) { this.audioLocator = audioLocator; initialize(); } @Override public boolean isHeavy() { return false; } public void initialize() { this.options = Wandora.getWandora().getOptions().asMap(); JPanel controllerPanel = new JPanel(); controllerPanel.add(getJToolBar(), BorderLayout.CENTER); waveformPanel = new WaveformPanel(audioLocator); this.addMouseListener(this); this.setLayout(new BorderLayout()); this.add(waveformPanel, BorderLayout.CENTER); wrapperPanel = new JPanel(); wrapperPanel.setLayout(new BorderLayout(8,8)); wrapperPanel.add(this, BorderLayout.CENTER); wrapperPanel.add(controllerPanel, BorderLayout.SOUTH); repaint(); revalidate(); updateAudioMenu(); } @Override public void finish() { isPlaying = false; if(waveformPanel != null) { waveformPanel.stop(); } if(player != null) { player.stop(); player.flush(); } } @Override public void stop() { isPlaying = false; if(waveformPanel != null) { waveformPanel.stop(); } if(player != null) { player.stop(); player.flush(); } } @Override public JPanel getGui() { return wrapperPanel; } @Override public void run() { try { isPlaying = true; playSample(audioLocator); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (LineUnavailableException e) { e.printStackTrace(); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } isPlaying = false; } private void playSample(String audioLocator) throws Exception { AudioInputStream audioStream = null; if(DataURL.isDataURL(audioLocator)) { DataURL dataURL = new DataURL(audioLocator); audioStream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(dataURL.getData())); } else { URL audioURL = new URL(audioLocator); audioStream = AudioSystem.getAudioInputStream(audioURL); } AudioFormat format = audioStream.getFormat(); frameLength = audioStream.getFrameLength(); // Create line SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class, format); player = (SourceDataLine) AudioSystem.getLine(info); player.addLineListener((LineListener) waveformPanel); player.open(format); player.start(); byte[] audioBuffer = new byte[player.getBufferSize()]; int numRead = 0; int offset = 0; while(isPlaying && (numRead = audioStream.read(audioBuffer)) >= 0) { offset = 0; while (offset < numRead) { offset += player.write(audioBuffer, offset, numRead-offset); } } player.drain(); player.stop(); } public void play() { if(!isPlaying) { if(audioLocator != null && audioLocator.length() > 0) { Thread audioThread = new Thread(this); audioThread.start(); } } } public long getFramePosition() { if(player != null && isPlaying) { int fp = player.getFramePosition(); return fp; } return 0; } public long getFrameLength() { return frameLength; } @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { if(mouseEvent.getButton() == MouseEvent.BUTTON1 && mouseEvent.getClickCount() >= 2) { play(); } } @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 updateAudioMenu() { if(audioLocator != null && audioLocator.length() > 0) { this.setComponentPopupMenu(getImageMenu()); } else { this.setComponentPopupMenu(null); } } public JPopupMenu getImageMenu() { Object[] menuStructure = new Object[] { "Play", "Stop", "---", "Open in external player...", "---", "Copy audio location", "---", "Save audio as...", }; return UIBox.makePopupMenu(menuStructure, this); } private JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { "Play", PreviewUtils.ICON_PLAY, this, // "Pause", PreviewUtils.ICON_PAUSE, this, "Stop", PreviewUtils.ICON_STOP, this, "Copy location", PreviewUtils.ICON_COPY_LOCATION, this, "Open ext", PreviewUtils.ICON_OPEN_EXT, this, "Save as", PreviewUtils.ICON_SAVE, this, }, this); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c == null) return; if(startsWithAny(c, "Play")) { play(); } else if(startsWithAny(c, "Stop")) { isPlaying = false; if(player != null) { player.drain(); player.stop(); } } else if(startsWithAny(c, "Open in external", "Open ext")) { PreviewUtils.forkExternalPlayer(audioLocator); } else if(startsWithAny(c, "Copy audio location", "Copy location")) { if(audioLocator != null) { ClipboardBox.setClipboard(audioLocator); } } else if(startsWithAny(c, "Save")) { PreviewUtils.saveToFile(audioLocator); } } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "audio/x-aiff", "audio/basic", "audio/x-wav" }, new String[] { "aif", /*"mp3", */ "wav", "au" } ); } // ------------------------------------------------------------------------- // ------------------------------------------------------- WaveformPanel --- // ------------------------------------------------------------------------- public class WaveformPanel extends JPanel implements Runnable, LineListener, ComponentListener { private int[][] waveformData = null; private int[][][] waveformView = null; private String audioLocator = null; private Font infoFont = new Font(Font.SANS_SERIF, Font.PLAIN, 15); private Thread waveformThread = null; private long framePosition = 0; private long frameLength = 0; private AudioFormat format = null; private boolean isRunning = false; private boolean requiresRefresh = true; public WaveformPanel(String audioLocator) { this.addComponentListener(this); this.audioLocator = audioLocator; isRunning = true; waveformThread = new Thread(this); waveformThread.start(); } public void stop() { isRunning = false; } @Override public void run() { try { AudioInputStream audioStream = null; if(DataURL.isDataURL(audioLocator)) { DataURL dataURL = new DataURL(audioLocator); audioStream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(dataURL.getData())); } else { URL audioURL = new URL(audioLocator); audioStream = AudioSystem.getAudioInputStream(audioURL); } format = audioStream.getFormat(); frameLength = audioStream.getFrameLength(); byte[] waveformRawData = new byte[(int) frameLength*format.getFrameSize()]; int bytesRead = audioStream.read(waveformRawData); waveformData = sortAudioBytes(waveformRawData, format); if(audioStream != null) { audioStream.close(); } } catch(Exception e) { e.printStackTrace(); } while(isRunning) { try { long newFramePosition = getFramePosition(); if(newFramePosition != framePosition) { framePosition = newFramePosition; requiresRefresh = true; } if(requiresRefresh) { repaint(); requiresRefresh = false; } Thread.sleep(50); } catch(Exception e) { } } } private int[][] sortAudioBytes(byte[] raw, AudioFormat format) { int numChannels = format.getChannels(); int[][] waveform = new int[numChannels][(int) frameLength]; int sampleIndex = 0; boolean isBigEndian = format.isBigEndian(); boolean isSigned = true; if(format.getSampleSizeInBits() == 8) { for(int t=0; t<raw.length;) { for(int channel=0; channel<numChannels; channel++) { int sample = 0; if(isSigned) { sample = (raw[t] << 8) ; } else { sample = ((raw[t] ^ 0x80) << 8); } waveform[channel][sampleIndex] = sample; t = t+1; } sampleIndex++; } } else if(format.getSampleSizeInBits() == 16) { for(int t=0; t<raw.length;) { for(int channel=0; channel<numChannels; channel++) { int low = (int) raw[t]; int high = (int) raw[t+1]; int sample = 0; if(isBigEndian) { sample = (low << 8) | (high & 0x00ff); } else { sample = (low & 0x00ff) | (high << 8); } waveform[channel][sampleIndex] = sample; t = t+2; } sampleIndex++; } } else if(format.getSampleSizeInBits() == 24) { for(int t=0; t<raw.length;) { for(int channel=0; channel<numChannels; channel++) { int low = (int) raw[t]; int mid = (int) raw[t+1]; int high = (int) raw[t+2]; int sample = 0; if(isBigEndian) { sample = (low << 16) | ((mid & 0xFF) << 8) | (high & 0x00ff); } else { sample = (low & 0x00ff) | ((mid & 0xFF) << 8) | (high << 16); } waveform[channel][sampleIndex] = sample; t = t+3; } sampleIndex++; } } else if(format.getSampleSizeInBits() == 32) { for(int t=0; t<raw.length;) { for(int channel=0; channel<numChannels; channel++) { int low = (int) raw[t]; int mid1 = (int) raw[t+1]; int mid2 = (int) raw[t+2]; int high = (int) raw[t+3]; int sample = 0; if(isBigEndian) { sample = (low << 24) | ((mid1 & 0xFF) << 16) | ((mid2 & 0xFF) << 8) | (high & 0x00ff); } else { sample = (low & 0x00ff) | ((mid1 & 0xFF) << 8) | ((mid1 & 0xFF) << 16) | (high << 24); } waveform[channel][sampleIndex] = sample; t = t+4; } sampleIndex++; } } return waveform; } private void makeWaveformView() { int w = this.getWidth(); int h = this.getHeight(); int numberOfChannels = waveformData.length; waveformView = new int[numberOfChannels][w][2]; for(int channel=0; channel<numberOfChannels; channel++) { int step = waveformData[channel].length / w; if(step == 0) step = 1; int o = (channel+1) * h/numberOfChannels - (h/numberOfChannels)/2; int y = 0; for(int x=0; x<w; x++) { int xstep = x*step; int max = waveformData[channel][xstep]; int min = waveformData[channel][xstep]; for(int s=1; s<step; s++) { if(waveformData[channel][xstep+s] > max) { max = waveformData[channel][xstep+s]; } if(waveformData[channel][xstep+s] < min) { min = waveformData[channel][xstep+s]; } } int ymax = o + (max / (256*numberOfChannels)); int ymin = o + (min / (256*numberOfChannels)); waveformView[channel][x][0] = ymin; waveformView[channel][x][1] = ymax; } } } @Override public void update(LineEvent event) { if(isPlaying) { //framePosition = event.getFramePosition(); //repaint(); } } @Override public void paint(Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.WHITE); g.setFont(infoFont); if(waveformData == null) { String text = "Preparing waveform"; byte[] textBytes = text.getBytes(); FontMetrics fontMetrics = g.getFontMetrics(infoFont); int w = fontMetrics.bytesWidth(textBytes, 0, 0); int h = fontMetrics.getHeight(); g.drawString(text, getWidth()/2-w/2, getHeight()/2-h/2); } else if(waveformView == null) { makeWaveformView(); } if(waveformView != null) { int h = this.getHeight(); int numberOfChannels = waveformData.length; int w = waveformView[0].length; for(int channel=0; channel<numberOfChannels; channel++) { int o = (channel+1) * h/numberOfChannels - (h/numberOfChannels)/2; w = waveformView[channel].length; g.drawLine(0, o, w, o); for(int x=0; x<w; x++) { int ymax = waveformView[channel][x][0]; int ymin = waveformView[channel][x][1]; g.drawLine(x, ymin, x, ymax); } } if(framePosition > 0 && frameLength > 0) { int playPositionOnScreen = (int) ((framePosition * w) / frameLength); g.drawLine(playPositionOnScreen, 0, playPositionOnScreen, h); } } } @Override public Dimension getMinimumSize() { return new Dimension(320, 256); } @Override public Dimension getPreferredSize() { return new Dimension(320, 256); } @Override public Dimension getMaximumSize() { return new Dimension(320, 256); } @Override public void componentResized(ComponentEvent e) { makeWaveformView(); requiresRefresh = true; } @Override public void componentMoved(ComponentEvent e) { makeWaveformView(); requiresRefresh = true; } @Override public void componentShown(ComponentEvent e) { makeWaveformView(); requiresRefresh = true; } @Override public void componentHidden(ComponentEvent e) { //makeWaveformView(); //requiresRefresh = true; } } }
20,755
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AudioMod.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/AudioMod.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.previews.formats; import org.wandora.application.gui.previews.PreviewUtils; /** * @author akivela */ public class AudioMod extends AudioAbstract { public AudioMod(String locator) { super(locator); } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "audio/mod", "audio/xm", "audio/wow", "audio/it", "audio/stm", "audio/s3m", "audio/xm" }, new String[] { "mod", "wow", "it", "stm", "s3m", "xm" } ); } }
1,706
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AudioFlac.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/AudioFlac.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.previews.formats; import org.wandora.application.gui.previews.PreviewUtils; /** * * @author akivela */ public class AudioFlac extends AudioAbstract { public AudioFlac(String locator) { super(locator); } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "audio/x-flac", }, new String[] { "flac" } ); } }
1,455
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AudioMidiv2.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/AudioMidiv2.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.previews.formats; import org.wandora.application.gui.previews.PreviewUtils; /** * @author akivela */ public class AudioMidiv2 extends AudioAbstract { public AudioMidiv2(String locator) { super(locator); } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "audio/midi", "application/x-midi", }, new String[] { ".mid", ".midi", ".rmf" } ); } }
1,552
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Image.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/Image.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/>. * * * Image.java * * Created on 17. toukokuuta 2006, 16:38 * */ package org.wandora.application.gui.previews.formats; import static java.awt.event.InputEvent.CTRL_MASK; import static java.awt.event.KeyEvent.VK_C; import static java.awt.event.KeyEvent.VK_MINUS; import static java.awt.event.KeyEvent.VK_PLUS; import static org.wandora.application.gui.previews.PreviewUtils.startsWithAny; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.File; import javax.imageio.ImageIO; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.KeyStroke; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.UIConstants; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.application.gui.simple.SimpleFileChooser; import org.wandora.utils.ClipboardBox; import org.wandora.utils.Options; /** * * @author akivela */ public class Image extends JPanel implements Runnable, MouseListener, KeyListener, ImageObserver, ActionListener, Printable, PreviewPanel { private static final String OPTIONS_PREFIX = "gui.imagePreviewPanel."; private static final double ZOOMFACTOR = 1.1; private String imageLocator; private BufferedImage image; private BufferedImage scaledImage; private Dimension panelDimensions; private Wandora wandora; private Options options; private double zoomFactor = 1.0; private JPanel wrapperPanel = null; @Override public boolean isHeavy() { return false; } public Image(String imageLocator) { this.wandora = Wandora.getWandora(); this.imageLocator = imageLocator; this.addMouseListener(this); this.addKeyListener(this); setImageSize(1.0); if(wandora != null) { options = wandora.options; if(options != null) { String zoomFactorString = options.get(OPTIONS_PREFIX + "imageSize"); if(zoomFactorString != null) { try { setImageSize(Double.parseDouble(zoomFactorString)); } catch(Exception e) {} } } } // setURL(imageLocator); reset(); JPanel controllerPanel = new JPanel(); controllerPanel.add(getJToolBar(), BorderLayout.CENTER); JPanel imagePanel = new JPanel(); imagePanel.add(this, BorderLayout.CENTER); wrapperPanel = new JPanel(); wrapperPanel.setLayout(new BorderLayout(8,8)); wrapperPanel.add(imagePanel, BorderLayout.CENTER); wrapperPanel.add(controllerPanel, BorderLayout.SOUTH); } private void reset() { if(imageLocator != null && imageLocator.length() > 0) { Thread imageThread = new Thread(this); imageThread.start(); } else { run(); } } public void setImageSize(double newZoomFactor) { if(newZoomFactor > 0.1 && newZoomFactor < 10) { if(options != null) options.put(OPTIONS_PREFIX + "imageSize", newZoomFactor); zoomFactor = newZoomFactor; reset(); } } @Override public void finish() { // Nothing here... } @Override public void stop() {} @Override public Component getGui() { return wrapperPanel; } @Override public void run() { if(imageLocator != null && imageLocator.length() > 0) { image = UIBox.getThumbForLocator(imageLocator, wandora.wandoraHttpAuthorizer); } if(image != null) { int targetWidth = (int) (image.getWidth() * zoomFactor); int targetHeight = (int) (image.getHeight() * zoomFactor); scaledImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_ARGB); Graphics g = scaledImage.createGraphics(); if(g != null) { if(g instanceof Graphics2D) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawImage(image, 0,0, targetWidth, targetHeight, this); g2.dispose(); } else { g.drawImage(image, 0,0, targetWidth, targetHeight, this); } } panelDimensions = new Dimension(targetWidth, targetHeight); } else { panelDimensions = new Dimension(2, 2); } this.setPreferredSize(panelDimensions); this.setMaximumSize(panelDimensions); this.setMinimumSize(panelDimensions); updateImageMenu(); repaint(); revalidate(); } public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { if((infoflags & ImageObserver.ALLBITS) != 0) { repaint(); revalidate(); return false; } return true; } @Override public void paint(Graphics g) { super.paint(g); if(scaledImage != null && panelDimensions != null) { //System.out.println(" image x =" + imageDimensions.width + ", y=" + imageDimensions.height ); g.drawImage(scaledImage,0,0,scaledImage.getWidth(), scaledImage.getHeight(), this); } } // ------------------------------------------------------------------------- @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { if(mouseEvent.getButton() == MouseEvent.BUTTON1 && mouseEvent.getClickCount() >= 2) { PreviewUtils.forkExternalPlayer(imageLocator); } } @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.requestFocus(); } @Override public void mouseReleased(java.awt.event.MouseEvent mouseEvent) { } // --------------------------------------------- @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if(keyCode == KeyEvent.VK_MINUS) { setImageSize(zoomFactor / ZOOMFACTOR); } else if(keyCode == KeyEvent.VK_PLUS) { setImageSize(zoomFactor * ZOOMFACTOR); } else if(keyCode == KeyEvent.VK_C && e.isControlDown()) { if(image != null) { ClipboardBox.setClipboard(image); } } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } // ------------------------------------------------------------------------- private JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { "Zoom in", PreviewUtils.ICON_ZOOM_IN, this, "Zoom out", PreviewUtils.ICON_ZOOM_OUT, this, "Reset size", PreviewUtils.ICON_ZOOM_RESET, this, "---", "Copy image", PreviewUtils.ICON_COPY_IMAGE, this, "Copy location", PreviewUtils.ICON_COPY_LOCATION, this, "Open ext", PreviewUtils.ICON_OPEN_EXT, this, "Save", PreviewUtils.ICON_SAVE, this, // f019 "Print", PreviewUtils.ICON_PRINT, this, }, this); } // ------------------------------------------------------------------------- public void updateImageMenu() { if(image != null) { this.setComponentPopupMenu(getImageMenu()); } else { this.setComponentPopupMenu(null); } } public JPopupMenu getImageMenu() { Object[] menuStructure = new Object[] { "Open in external viewer...", "---", "Zoom", new Object[] { "Zoom in", KeyStroke.getKeyStroke(VK_PLUS, 0), "Zoom out", KeyStroke.getKeyStroke(VK_MINUS, 0), "---", "25 %", "50 %", "100 %", "150 %", "200 %", }, /* "Scale", new Object[] { (scaleToFit ? "X " : "O ") + "Scale to fit", (!scaleToFit ? "X " : "O ") + "No scaling", }, */ "---", "Copy image", KeyStroke.getKeyStroke(VK_C, CTRL_MASK), "Copy image location", "---", "Save image as...", "Print image...", }; return UIBox.makePopupMenu(menuStructure, this); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c == null) return; if(startsWithAny(c, "Open in external", "Open ext")) { PreviewUtils.forkExternalPlayer(imageLocator); } else if(startsWithAny(c, "25")) { setImageSize(0.25); } else if(startsWithAny(c, "50")) { setImageSize(0.5); } else if(startsWithAny(c, "100")) { setImageSize(1.0); } else if(startsWithAny(c, "150")) { setImageSize(1.5); } else if(startsWithAny(c, "200")) { setImageSize(2.0); } else if(startsWithAny(c, "Zoom in")) { setImageSize(zoomFactor * 1.1); } else if(startsWithAny(c, "Zoom out")) { setImageSize(zoomFactor / 1.1); } else if(startsWithAny(c, "Reset size")) { setImageSize(1.0); } else if(startsWithAny(c, "Copy image")) { if(image != null) { ClipboardBox.setClipboard(image); } } else if(startsWithAny(c, "Copy location")) { if(imageLocator != null) { ClipboardBox.setClipboard(imageLocator); } } else if(startsWithAny(c, "Save")) { if(image != null) { save(); } } else if(startsWithAny(c, "Print")) { if(image != null) { print(); } } } // ----------------------------------------------------------------- SAVE --- public void save() { Wandora wandora = Wandora.getWandora(this); SimpleFileChooser chooser = UIConstants.getFileChooser(); chooser.setDialogTitle("Save image file"); try { chooser.setSelectedFile(new File(imageLocator.substring(imageLocator.lastIndexOf(File.pathSeparator)+1))); } catch(Exception e) {} if(chooser.open(wandora,SimpleFileChooser.SAVE_DIALOG)==SimpleFileChooser.APPROVE_OPTION) { save(chooser.getSelectedFile()); } } public void save(File imageFile) { if(imageFile != null) { try { String format = solveImageFormat(imageFile.getName()); ImageIO.write(image, format, imageFile); } catch(Exception e) { System.out.println("Exception '" + e.toString() + "' occurred while saving file '" + imageFile.getPath() + "'."); } } } public String solveImageFormat() { return solveImageFormat(imageLocator); } public String solveImageFormat(String fileName) { String fileFormat = "jpg"; try { fileFormat = fileName.substring(fileName.lastIndexOf('.')+1); if(fileFormat == null || fileFormat.length() == 0) { fileFormat = "jpg"; } } catch(Exception e) {} return fileFormat; } // ------------------------------------------------------------ PRINTING --- public void print() { PrinterJob printJob = PrinterJob.getPrinterJob(); printJob.setPrintable(this); if (printJob.printDialog()) { try { printJob.print(); } catch(PrinterException pe) { System.out.println("Error printing: " + pe); } } } @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); } } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "image" }, new String[] { "gif", "jpg", "jpeg", "tif", "tiff", "bmp", "png" } ); } }
15,120
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApplicationC64.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/ApplicationC64.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.previews.formats; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.net.URL; import java.util.Properties; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.application.tools.extractors.files.SimpleFileExtractor; import org.wandora.topicmap.TopicMap; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import de.joergjahnke.c64.core.C1541; import de.joergjahnke.c64.core.C64; import de.joergjahnke.c64.extendeddevices.EmulatorUtils; import de.joergjahnke.c64.swing.C64Canvas; import de.joergjahnke.common.extendeddevices.WavePlayer; import de.joergjahnke.common.vmabstraction.sunvm.SunVMResourceLoader; /** * * @author akivela */ public class ApplicationC64 implements ActionListener, PreviewPanel, ComponentListener { private String locator = null; private String imageData = null; // disk image private WavePlayer wavePlayer = null; private C64Canvas c64canvas = null; private C64 c64 = null; private JPanel c64wrapper = null; private JPanel ui = null; private static Properties settings = new Properties(); //private final HashMap<Integer,String> attachedImages = new HashMap(); private int sizeScaler = 1; // 1,2,3 private int joystickPort = 0; // 0,1 private int driveEmulationMode; private int mouseEmulationMode; private boolean automaticTurboMode = false; private String userInput = ""; public ApplicationC64(String locator) { this.locator = locator; } @Override public void stop() { stopC64(); } @Override public void finish() { stopC64(); } private void stopC64() { if(c64 != null) { c64.getVIC().reset(); c64.getSID().reset(); c64.getKeyboard().reset(); c64.getIECBus().reset(); c64.getCPU().reset(); c64.getCIA(0).reset(); c64.getCIA(1).reset(); c64.stop(); wavePlayer.stop(); c64 = null; } } @Override public Component getGui() { if(ui == null) { ui = new JPanel(); ui.setLayout(new BorderLayout(8,8)); c64wrapper = new JPanel(); try { if(c64canvas == null) { this.c64canvas = new C64Canvas(); this.c64canvas.addComponentListener(this); // create C64 instance and inform the canvas about this instance this.c64 = new C64(new SunVMResourceLoader()); this.c64canvas.setC64(c64); // create a player that observes the SID and plays its sound wavePlayer = new WavePlayer(this.c64.getSID()); this.c64.getSID().addObserver(wavePlayer); this.c64.setActiveDrive(0); this.c64.setThrottlingEnabled(true); setDriveEmulation(C1541.COMPATIBLE_EMULATION); setMouseUsage(C64Canvas.MOUSE_AS_FIRE_BUTTON); } JPanel toolbarWrapper = new JPanel(); toolbarWrapper.add(getJToolBar()); c64wrapper.add(c64canvas); ui.add(c64wrapper, BorderLayout.CENTER); ui.add(toolbarWrapper, BorderLayout.SOUTH); // start the emulation new Thread(this.c64).start(); attach(locator); autoloadProgram(); runProgram(); } catch(Exception e) { PreviewUtils.previewError(ui, "Can't initialize text viewer. Exception occurred.", e); } } return ui; } protected JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { getMenuButton(), }, this); } public JButton getMenuButton() { final JButton button = UIBox.makeDefaultButton(); button.setIcon(UIBox.getIcon(0xf0c9)); button.setToolTipText("C64 preview options."); button.setBorder(null); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { getOptionsMenu().show(button, e.getX(), e.getY()); } }); return button; } private static final Icon selectedIcon = UIBox.getIcon("gui/icons/checked2.png"); private static final Icon unselectedIcon = UIBox.getIcon("gui/icons/empty.png"); public JPopupMenu getOptionsMenu() { Object[] menuStruct = new Object[] { "Open subject locator in ext", PreviewUtils.ICON_OPEN_EXT, "Copy subject locator", PreviewUtils.ICON_COPY_LOCATION, "Save subject locator resource...", PreviewUtils.ICON_SAVE, "---", "Reify snapshot", "Reify screen capture", "---", "Type text...", "Enter a special C64 key...", "---", "Joystick", new Object[] { "Use joystick port 1", joystickPort == 0 ? selectedIcon : unselectedIcon, "Use joystick port 2", joystickPort == 1 ? selectedIcon : unselectedIcon, "---", "Mouse emulates joystick button only", mouseEmulationMode == C64Canvas.MOUSE_AS_FIRE_BUTTON ? selectedIcon : unselectedIcon, "Mouse emulates virtual joystick", mouseEmulationMode == C64Canvas.MOUSE_FOR_VIRTUAL_JOYSTICK ? selectedIcon : unselectedIcon, "No joystick emulation", mouseEmulationMode == C64Canvas.MOUSE_NO_USAGE ? selectedIcon : unselectedIcon, }, /* "Turbo mode", new Object[] { "Auto turbo mode", "Turbo mode on", "Turbo mode off" }, */ "Floppy drive mode", new Object[] { "Fast emulation", driveEmulationMode == C1541.FAST_EMULATION ? selectedIcon : unselectedIcon, "Balanced emulation", driveEmulationMode == C1541.BALANCED_EMULATION ? selectedIcon : unselectedIcon, "Compatible emulation", driveEmulationMode == C1541.COMPATIBLE_EMULATION ? selectedIcon : unselectedIcon, }, "Display size", new Object[] { "1x", sizeScaler == 1 ? selectedIcon : unselectedIcon, "2x", sizeScaler == 2 ? selectedIcon : unselectedIcon, "3x", sizeScaler == 3 ? selectedIcon : unselectedIcon, }, "---", "Pause", c64.isPaused() ? selectedIcon : unselectedIcon, "Reset", "---", "About" }; JPopupMenu optionsPopup = UIBox.makePopupMenu(menuStruct, this); return optionsPopup; } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c == null) return; if(c64 == null) return; if(c64canvas == null) return; System.out.println("ApplicationC64 action '"+c+"'."); if("Open subject locator in ext".equalsIgnoreCase(c)) { PreviewUtils.forkExternalPlayer(locator); } else if("Copy subject locator".equalsIgnoreCase(c)) { if(locator != null) { ClipboardBox.setClipboard(locator); } } else if("Save subject locator resource...".equalsIgnoreCase(c)) { PreviewUtils.saveToFile(locator); } else if("Reify snapshot".equalsIgnoreCase(c)) { DataURL snapshot = makeSnapshot(); if(snapshot != null) { saveToTopic(snapshot); } } else if("Reify screen capture".equalsIgnoreCase(c)) { DataURL screenCapture = makeScreenCapture(); if(screenCapture != null) { saveToTopic(screenCapture); } } else if("Type text...".equalsIgnoreCase(c)) { c64.pause(); userInput = WandoraOptionPane.showInputDialog(Wandora.getWandora(), "Enter input text", userInput, "Input text"); c64.resume(); if(userInput != null && userInput.length() == 0) { c64.getKeyboard().textTyped(userInput); } } else if("Enter a special C64 key...".equalsIgnoreCase(c)) { // show a dialog to let the user select the special key final String[] specialKeys = { "Run", "Break", "Commodore", "Pound" }; final Object key = JOptionPane.showInputDialog( Wandora.getWandora(), "Select a key", "Special keys", JOptionPane.PLAIN_MESSAGE, null, specialKeys, null); if(key != null) { this.c64.getKeyboard().keyTyped(key.toString().toUpperCase()); } } else if("1x".equalsIgnoreCase(c)) { setScaling(1); } else if("2x".equalsIgnoreCase(c)) { setScaling(2); } else if("3x".equalsIgnoreCase(c)) { setScaling(3); } else if("Display size".equalsIgnoreCase(c)) { sizeScaler += 1; if(sizeScaler > 3) sizeScaler = 1; setScaling(sizeScaler); } else if("Joystick port".equalsIgnoreCase(c)) { setActiveJoystick(joystickPort == 0 ? 1 : 0); } else if("Use joystick port 1".equalsIgnoreCase(c)) { setActiveJoystick(0); } else if("Use joystick port 2".equalsIgnoreCase(c)) { setActiveJoystick(1); } else if("Mouse emulates joystick button only".equalsIgnoreCase(c)) { setMouseUsage(C64Canvas.MOUSE_AS_FIRE_BUTTON); } else if("Mouse emulates virtual joystick".equalsIgnoreCase(c)) { setMouseUsage(C64Canvas.MOUSE_FOR_VIRTUAL_JOYSTICK); } else if("No joystick emulation".equalsIgnoreCase(c)) { setMouseUsage(C64Canvas.MOUSE_NO_USAGE); } else if("Fast emulation".equalsIgnoreCase(c)) { setDriveEmulation(C1541.FAST_EMULATION); } else if("Balanced emulation".equalsIgnoreCase(c)) { setDriveEmulation(C1541.BALANCED_EMULATION); } else if("Compatible emulation".equalsIgnoreCase(c)) { setDriveEmulation(C1541.COMPATIBLE_EMULATION); } else if("Auto turbo mode".equalsIgnoreCase(c)) { setTurboMode(true, true); } else if("Turbo mode on".equalsIgnoreCase(c)) { setTurboMode(true, false); } else if("Turbo mode off".equalsIgnoreCase(c)) { setTurboMode(false, false); } else if("Reset".equalsIgnoreCase(c)) { c64.reset(); } else if("Pause".equalsIgnoreCase(c)) { if(c64.isPaused()) c64.resume(); else c64.pause(); } else if("Resume".equalsIgnoreCase(c)) { c64.resume(); } else if("About".equalsIgnoreCase(c)) { StringBuilder aboutBuilder = new StringBuilder(""); aboutBuilder.append("Wandora's C64 emulation support is based on JSwingC64 version 1.10.4 "); aboutBuilder.append("created and copyrighted by Joerg Jahnke 2006-2009 "); aboutBuilder.append("distributed under the license of GNU GPL. \n\n"); aboutBuilder.append("The original Commodore 64 ROM images are included with kind permission of Commodore Internation Corporation."); c64.pause(); WandoraOptionPane.showMessageDialog(Wandora.getWandora(), aboutBuilder.toString(), "About C64 emulation"); c64.resume(); } } private void setScaling(int scale) { sizeScaler = scale; c64canvas.setScaling(scale); c64wrapper.validate(); c64wrapper.repaint(); } private void setActiveJoystick(int port) { joystickPort = port; c64.setActiveJoystick(port); } private void setMouseUsage(int emulationMode) { mouseEmulationMode = emulationMode; c64canvas.setMouseUsage(emulationMode); } private void setDriveEmulation(int emulationMode) { driveEmulationMode = emulationMode; for (int i=0; i<C64.MAX_NUM_DRIVES; ++i) { this.c64.getDrive(i).setEmulationLevel(driveEmulationMode); } } private void setTurboMode(boolean throttling, boolean autoTurbo) { c64.setThrottlingEnabled(throttling); automaticTurboMode = autoTurbo; } // ------------------------------------------------------------------------- @Override public boolean isHeavy() { return false; } public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "application/d64", "application/x-d64", "application/x-cbm-d64", "application/t64", "application/x-t64", "application/x-cbm-t64", "application/x-c64-program", "application/x-c64-snaphot" }, new String[] { ".d64", ".t64", ".prg", ".p00" } ); } // ------------------------------------------------------------------------- private void refreshSize() { if(c64canvas != null) { c64wrapper.setPreferredSize(c64canvas.getPreferredSize()); c64wrapper.setSize(c64canvas.getPreferredSize()); c64wrapper.revalidate(); ui.validate(); } } @Override public void componentResized(ComponentEvent e) { refreshSize(); } @Override public void componentMoved(ComponentEvent e) { refreshSize(); } @Override public void componentShown(ComponentEvent e) { refreshSize(); } @Override public void componentHidden(ComponentEvent e) { refreshSize(); } // ------------------------------------------------------------------------- private void attach(String data) { try { if(DataURL.isDataURL(data)) { DataURL dataUrl = new DataURL(data); if(dataUrl.getMimetype().equalsIgnoreCase("application/x-c64-snaphot")) { c64.pause(); DataInputStream in = new DataInputStream(new BufferedInputStream(dataUrl.getDataStream())); int numberOfDrives = in.readInt(); // attached the previously attached images int driveNo = in.readInt(); int imageDataSize = in.readInt(); byte[] imageDataBytes = new byte[imageDataSize]; in.readFully(imageDataBytes); imageData = new String(imageDataBytes, "UTF-8"); attach(imageData); // load the emulator state c64.deserialize(in); c64.resume(); } else { imageData = data; File tmpFile = dataUrl.createTempFile(); if(tmpFile != null) { System.out.println("disk attached: "+tmpFile.getAbsolutePath()); EmulatorUtils.attachImage(c64, c64.getActiveDrive(), tmpFile.getAbsolutePath()); //attachedImages.put(Integer.valueOf(c64.getActiveDrive()), tmpFile.getAbsolutePath()); } else { PreviewUtils.previewError(ui, "Unable to create temporal file for a dataurl."); } } } else { imageData = data; File imageFile = null; if(data.startsWith("file")) { imageFile = new File(new URL(data).toURI()); } else { DataURL dataUrl = new DataURL(new URL(data)); imageFile = dataUrl.createTempFile(); } String imageFilename = imageFile.getAbsolutePath(); EmulatorUtils.attachImage(c64, c64.getActiveDrive(), imageFilename); } } catch(Exception e) { e.printStackTrace(); } } /** * Detach all images from all drives */ private void detachImages() { // detach images from all drives for (int i = 0; i < C64.MAX_NUM_DRIVES; ++i) { c64.getDrive(i).detachImage(); } } private void autoloadProgram() { this.c64.getKeyboard().textTyped("load \"*\",8,1"); this.c64.getKeyboard().keyTyped("ENTER"); } private void runProgram() { this.c64.getKeyboard().textTyped("run"); this.c64.getKeyboard().keyTyped("ENTER"); } private DataURL makeSnapshot() { this.c64.pause(); DataURL snapshot = null; DataOutputStream out = null; ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); try { out = new DataOutputStream(new BufferedOutputStream(byteOutputStream)); // save attached image out.writeInt(1); out.writeInt(c64.getActiveDrive()); byte[] imageDataBytes = imageData.getBytes("UTF-8"); out.writeInt(imageDataBytes.length); out.write(imageDataBytes); // save current emulator state c64.serialize(out); out.close(); snapshot = new DataURL(byteOutputStream.toByteArray()); snapshot.setMimetype("application/x-c64-snaphot"); } catch (Throwable t) { t.printStackTrace(); try { out.close(); } catch (Exception e) { } } c64.resume(); return snapshot; } private DataURL makeScreenCapture() { try { BufferedImage screenCaptureImage = new BufferedImage(c64canvas.getPreferredSize().width, c64canvas.getPreferredSize().height, BufferedImage.TYPE_INT_RGB); Graphics screenCaptureGraphics = screenCaptureImage.createGraphics(); c64canvas.paintAll(screenCaptureGraphics); DataURL screenCaptureDataUrl = null; screenCaptureDataUrl = new DataURL(screenCaptureImage); return screenCaptureDataUrl; } catch(Exception e) { e.printStackTrace(); } return null; } private void saveToTopic(DataURL dataUrl) { Wandora wandora = Wandora.getWandora(); try { TopicMap topicMap = wandora.getTopicMap(); SimpleFileExtractor simpleFileExtractor = new SimpleFileExtractor(); simpleFileExtractor._extractTopicsFrom(dataUrl.toExternalForm(), topicMap); wandora.doRefresh(); } catch(Exception e) { wandora.handleError(e); } } }
21,692
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TextHTML.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/TextHTML.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/>. * * * TextHTML.java * * Created on 24. lokakuuta 2007, 17:15 * */ package org.wandora.application.gui.previews.formats; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Desktop; import java.awt.Dimension; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.StringWriter; import java.net.URI; import java.net.URL; import java.util.HashSet; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.WandoraToolSet; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.application.tools.DropExtractor; import org.wandora.topicmap.Topic; import org.wandora.topicmap.XTMPSI; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import javafx.application.Platform; import javafx.beans.value.ObservableValue; import javafx.concurrent.Worker; import javafx.embed.swing.JFXPanel; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.web.PopupFeatures; import javafx.scene.web.PromptData; import javafx.scene.web.WebEngine; import javafx.scene.web.WebEvent; import javafx.scene.web.WebView; import javafx.util.Callback; /** * * @author akivela */ public class TextHTML implements MouseListener, ActionListener, PreviewPanel, HyperlinkListener, ComponentListener { private Wandora wandora; private String locator; private FXHTML htmlPane; private JPopupMenu linkPopup = null; private MouseEvent mouseEvent = null; private JPanel ui = null; /** Creates a new instance of TextHTML */ public TextHTML(String locator) { Platform.setImplicitExit(false); this.wandora = Wandora.getWandora(); this.locator = locator; } @Override public void stop() { if(htmlPane != null) { htmlPane.close(); } } @Override public void finish() { if(htmlPane != null) { // htmlPane.close(); } } @Override public JPanel getGui() { // System.out.println("getting ui..."); if(ui == null) { ui = new JPanel(); // ui.addMouseListener(this); ui.setLayout(new BorderLayout(4,4)); ui.setPreferredSize(new Dimension(640, 480+56)); ui.setMinimumSize(new Dimension(640, 480+56)); JPanel htmlWrapper = new JPanel(); htmlWrapper.setBorder(BorderFactory.createLineBorder(Color.GRAY)); htmlWrapper.setLayout(new BorderLayout()); htmlPane = new FXHTML(locator); htmlPane.initialize(); htmlWrapper.add(htmlPane, BorderLayout.CENTER); //htmlPane.addMouseListener(this); //htmlPane.setBorder(BorderFactory.createLineBorder(borderColor)); //updateLinkMenu(); JPanel controllerPanel = new JPanel(); controllerPanel.add(getJToolBar(), BorderLayout.CENTER); ui.add(htmlWrapper, BorderLayout.CENTER); ui.add(controllerPanel, BorderLayout.SOUTH); ui.addComponentListener(this); } ui.revalidate(); ui.repaint(); return ui; } private JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { "Reload", PreviewUtils.ICON_RELOAD_LOCATOR, this, "---", "Open ext", PreviewUtils.ICON_OPEN_EXT, this, "Copy location", PreviewUtils.ICON_COPY_LOCATION, this, "Copy selection", PreviewUtils.ICON_COPY_SELECTION, this, "Copy as image", PreviewUtils.ICON_COPY_IMAGE, this, "Save as", PreviewUtils.ICON_SAVE, this, "---", "Set basename", PreviewUtils.ICON_SET_BASENAME, this, "Set display name", PreviewUtils.ICON_SET_DISPLAY_NAME, this, "Set occurrence", PreviewUtils.ICON_SET_OCCURRENCE, this, }, this); } @Override public boolean isHeavy() { return false; } @Override public void mouseClicked(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; if(mouseEvent.getButton() == MouseEvent.BUTTON1 && mouseEvent.getClickCount() >= 2) { } } @Override public void mouseEntered(java.awt.event.MouseEvent mouseEvent) { this.mouseEvent = mouseEvent; } @Override public void mouseExited(java.awt.event.MouseEvent mouseEvent) { this.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 void updateMenu() { if(locator != null && locator.length() > 0) { JPopupMenu m = getMenu(); if(m != null) { ui.setComponentPopupMenu(m); if(htmlPane != null) htmlPane.setComponentPopupMenu(m); } } else { if(htmlPane != null) htmlPane.setComponentPopupMenu(null); } } public JPopupMenu getMenu() { WandoraToolSet extractTools = wandora.toolManager.getToolSet("extract"); WandoraToolSet.ToolFilter filter = extractTools.new ToolFilter() { @Override public boolean acceptTool(WandoraTool tool) { return (tool instanceof DropExtractor); } @Override public Object[] addAfterTool(final WandoraTool tool) { ActionListener toolListener = new ActionListener() { DropExtractor myTool = (DropExtractor) tool; public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); try { String s = getSelection(); ((DropExtractor) myTool).dropExtract(s); //System.out.println("extracting " + s); //System.out.println("extractor " + myTool); } catch(Exception exx) { wandora.handleError(exx); } } }; return new Object[] { tool.getIcon(), toolListener }; } }; Object[] extractMenu = extractTools.getAsObjectArray(filter); Object[] menuStructure = new Object[] { "Open in external viewer...", "---", "Copy location", "Copy selection", "Copy as image", "Save as...", "---", "For selection", new Object[] { "Make selection basename", "Make selection display name", "Make selection occurrence...", }, "Extract selection", extractMenu, }; return UIBox.makePopupMenu(menuStructure, this); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c == null) return; if(PreviewUtils.startsWithAny(c, "Reload")) { if(htmlPane != null) { htmlPane.reload(); } } else if(PreviewUtils.startsWithAny(c, "Open in external", "Open ext")) { PreviewUtils.forkExternalPlayer(locator); } else if(c.equalsIgnoreCase("Copy location")) { if(locator != null) { ClipboardBox.setClipboard(locator); } } else if(c.equalsIgnoreCase("Copy selection")) { String s = getSelection(); if(s != null && s.length() > 0) { try { ClipboardBox.setClipboard(s); } catch(Exception e) { wandora.handleError(e); } } } else if(c.equalsIgnoreCase("Copy as image")) { int w = htmlPane.getWidth(); int h = htmlPane.getHeight(); BufferedImage htmlPaneImage = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR ); htmlPane.paint(htmlPaneImage.getGraphics()); ClipboardBox.setClipboard(htmlPaneImage); } else if(c.startsWith("Save as")) { PreviewUtils.saveToFile(locator); } else if(PreviewUtils.startsWithAny(c, "Make selection display name", "Make display name")) { String s = getSelection(); if(s != null && s.length() > 0) { try { Topic t = wandora.getOpenTopic(); if(t != null) { Topic type = wandora.showTopicFinder("Select display name language"); if(type == null) return; HashSet scope = new HashSet(); scope.add(type); scope.add(t.getTopicMap().getTopic(XTMPSI.DISPLAY)); t.setVariant(scope, s); wandora.doRefresh(); } } catch(Exception e) { wandora.handleError(e); } } } else if(PreviewUtils.startsWithAny(c, "Make selection basename", "Set basename")) { String s = getSelection(); if(s != null && s.length() > 0) { try { Topic t = wandora.getOpenTopic(); if(t != null) { t.setBaseName(s); wandora.doRefresh(); } } catch(Exception e) { wandora.handleError(e); } } } else if(PreviewUtils.startsWithAny(c, "Make selection occurrence...", "Set occurrence")) { String s = getSelection(); if(s != null && s.length() > 0) { try { Topic type = wandora.showTopicFinder("Select occurrence type"); if(type == null) return; Topic scope = wandora.showTopicFinder("Select occurrence scope"); if(scope == null) return; Topic t = wandora.getOpenTopic(); if(t != null) { t.setData(type, scope, s); wandora.doRefresh(); } } catch(Exception e) { wandora.handleError(e); } } } } public String getSelection() { if(htmlPane != null) { return htmlPane.getSelectedText(); } return ""; } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public void updateLinkMenu() { WandoraToolSet extractTools = wandora.toolManager.getToolSet("extract"); WandoraToolSet.ToolFilter filter = extractTools.new ToolFilter() { @Override public boolean acceptTool(WandoraTool tool) { return (tool instanceof DropExtractor); } @Override public Object[] addAfterTool(final WandoraTool tool) { ActionListener toolListener = new ActionListener() { DropExtractor myTool = (DropExtractor) tool; public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); try { String url = currentHyperLink.toExternalForm(); ((DropExtractor) myTool).dropExtract(new String[] { url }); System.out.println("extracting url " + url); System.out.println("extractor " + myTool); } catch(Exception exx) { wandora.handleError(exx); } } }; return new Object[] { tool.getIcon(), toolListener }; } }; Object[] linkExtractMenu = extractTools.getAsObjectArray(filter); Object[] menuStructure = new Object[] { "Open in external viewer...", "---", "Copy location", "Copy as image", "Save as...", "---", "For selection", new Object[] { "Make link url subject identifier", "Make link url subject locator", }, "Extract link url", linkExtractMenu, }; linkPopup = UIBox.makePopupMenu(menuStructure, this); } public URL currentHyperLink; @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { JEditorPane pane = (JEditorPane) e.getSource(); currentHyperLink = e.getURL(); if(!linkPopup.isVisible()) { System.out.println("link pupup1"); if(mouseEvent != null) { System.out.println("link pupup2"); linkPopup.show(ui, mouseEvent.getX(), mouseEvent.getY()); } } /* if (e instanceof HTMLFrameHyperlinkEvent) { HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e; HTMLDocument doc = (HTMLDocument)pane.getDocument(); doc.processHTMLFrameHyperlinkEvent(evt); } else { try { pane.setPage(e.getURL()); } catch (Throwable t) { t.printStackTrace(); } } **/ } } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "text/html" }, new String[] { "html", "htm" }); } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- public class FXHTML extends JFXPanel { private final String locator; public WebView webView = null; private WebEngine webEngine = null; private boolean informPopupBlocking = true; private boolean informVisibilityChanges = true; private String webSource = null; public FXHTML(final String locator) { this.locator = locator; } public void initialize() { Platform.runLater(new Runnable() { @Override public void run() { initializeFX(); open(locator); } }); } private void initializeFX() { Group group = new Group(); Scene scene = new Scene(group); this.setScene(scene); webView = new WebView(); webView.setScaleX(1.0); webView.setScaleY(1.0); //webView.setFitToHeight(false); //webView.setFitToWidth(false); //webView.setZoom(javafx.stage.Screen.getPrimary().getDpi() / 96); group.getChildren().add(webView); //int w = TextHTML.this.ui.getWidth(); //int h = TextHTML.this.ui.getHeight(); //webView.setMinSize(w, h); //webView.setMaxSize(w, h); //webView.setPrefSize(w, h); // Obtain the webEngine to navigate webEngine = webView.getEngine(); webEngine.setOnVisibilityChanged(new EventHandler<WebEvent<java.lang.Boolean>>() { @Override public void handle(WebEvent<Boolean> t) { // Nothing here } }); webEngine.locationProperty().addListener(new javafx.beans.value.ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) { if(newValue == null) return; if(newValue.endsWith(".pdf")) { try { int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), "Open PDF document in external application?", "Open PDF document in external application?", WandoraOptionPane.YES_NO_OPTION); if(a == WandoraOptionPane.YES_OPTION) { Desktop dt = Desktop.getDesktop(); dt.browse(new URI(newValue)); } } catch(Exception e) {} } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Nothing here } }); } } }); webEngine.titleProperty().addListener(new javafx.beans.value.ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Nothing here } }); } }); webEngine.setOnAlert(new EventHandler<WebEvent<java.lang.String>>() { @Override public void handle(WebEvent<String> t) { if(t != null) { String str = t.getData(); if(str != null && str.length() > 0) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), str, "Javascript Alert", WandoraOptionPane.PLAIN_MESSAGE); } } } }); webEngine.setConfirmHandler(new Callback<String, Boolean>() { @Override public Boolean call(String msg) { int a = WandoraOptionPane.showConfirmDialog(Wandora.getWandora(), msg, "Javascript Alert", WandoraOptionPane.YES_NO_OPTION); return (a == WandoraOptionPane.YES_OPTION); } }); webEngine.setPromptHandler(new Callback<PromptData, String>() { @Override public String call(PromptData data) { String a = WandoraOptionPane.showInputDialog(Wandora.getWandora(), data.getMessage(), data.getDefaultValue(), "Javascript Alert", WandoraOptionPane.QUESTION_MESSAGE); return a; } }); webEngine.setCreatePopupHandler(new Callback<PopupFeatures,WebEngine>() { @Override public WebEngine call(PopupFeatures features) { if(informPopupBlocking) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "A javascript popup has been blocked. Wandora doesn't allow javascript popups in Webview topic panel.", "Javascript popup blocked", WandoraOptionPane.PLAIN_MESSAGE); } informPopupBlocking = false; return null; } }); webEngine.setOnVisibilityChanged(new EventHandler<WebEvent<Boolean>>() { @Override public void handle(WebEvent<Boolean> t) { if(t != null) { Boolean b = t.getData(); if(informVisibilityChanges) { WandoraOptionPane.showMessageDialog(Wandora.getWandora(), "A browser window visibility change has been blocked. Wandora doesn't allow visibility changes of windows in Webview topic panel.", "Javascript visibility chnage blocked", WandoraOptionPane.PLAIN_MESSAGE); informVisibilityChanges = false; } } } }); webEngine.getLoadWorker().stateProperty().addListener( new javafx.beans.value.ChangeListener<Worker.State>() { @Override public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) { if(newState == Worker.State.SCHEDULED) { //System.out.println("Scheduled!"); } if(newState == Worker.State.SUCCEEDED) { Document doc = webEngine.getDocument(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(System.out, "UTF-8"))); StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(stringWriter)); webSource = stringWriter.toString(); } catch (Exception ex) { ex.printStackTrace(); } } else if(newState == Worker.State.CANCELLED) { //System.out.println("Cancelled!"); } else if(newState == Worker.State.FAILED) { String failedToOpenMessage = "<h1>Failed to open URL</h1>"; webEngine.loadContent(failedToOpenMessage); } } } ); } public void open(final String locator) { try { if(DataURL.isDataURL(locator)) { DataURL dataUrl = new DataURL(locator); String data = new String( dataUrl.getData() ); webEngine.loadContent(data); } else if(locator != null && locator.startsWith("file:")) { } else { webEngine.load(locator); } Component c = TextHTML.this.ui.getParent(); if(c != null) { int w = c.getWidth(); webView.setMinSize(w, 480); webView.setMaxSize(w, 480); webView.setPrefSize(w, 480); } else { webView.setMinSize(640, 480); webView.setMaxSize(640, 480); webView.setPrefSize(640, 480); } } catch(Exception e) { e.printStackTrace(); } } public void close() { // System.out.println("TEST1"); Thread runner = new Thread() { @Override public void run() { try { if(webEngine != null) { webEngine.load(null); // System.out.println("TEST2"); } } catch(Exception e) { e.printStackTrace(); } } }; Platform.runLater(runner); do { try { Thread.sleep(100); } catch(Exception ex) { } } while(runner.isAlive()); } public void reload() { Platform.runLater(new Runnable() { @Override public void run() { open(locator); } }); } public String getSelectedText() { //System.out.println("get selected text"); String selection = (String) executeSynchronizedScript("window.getSelection().toString()"); //System.out.println(" and the selection is "+selection); return selection; } private Object scriptReturn = null; public Object executeSynchronizedScript(final String script) { scriptReturn = null; if(script != null && script.length()>0) { Thread runner = new Thread() { @Override public void run() { if(webEngine != null) { scriptReturn = webEngine.executeScript(script); } } }; Platform.runLater(runner); do { try { Thread.sleep(100); } catch(Exception ex) { } } while(runner.isAlive()); } return scriptReturn; } } // ------------------------------------------------------------------------- // --------------------------------------------------- ComponentListener --- // ------------------------------------------------------------------------- @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) { try { if(ui != null) { if(ui.getParent() != null) { Dimension d = new Dimension(640, 480+56); ui.setPreferredSize(d); ui.setMinimumSize(d); ui.setMaximumSize(d); } if(htmlPane != null) { if(htmlPane.webView != null) { Platform.runLater(new Runnable() { @Override public void run() { if(ui != null && htmlPane != null && htmlPane.webView != null) { Component c = ui; if(ui.getParent() != null) c = ui.getParent(); if(c != null) { int w = c.getWidth(); int h = c.getHeight(); if(w > 1 && h > 1) { htmlPane.webView.setMinSize(w, h-56); htmlPane.webView.setMaxSize(w, h-56); htmlPane.webView.setPrefSize(w, h-56); } } } } }); } } ui.revalidate(); ui.repaint(); } } catch(Exception ex) {} } }
31,592
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AudioSid.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/AudioSid.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.previews.formats; import static org.wandora.application.gui.previews.PreviewUtils.startsWithAny; import java.awt.event.ActionEvent; import javax.swing.JComponent; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.previews.PreviewUtils; import de.quippy.javamod.mixer.Mixer; /** * * @author akivela */ public class AudioSid extends AudioAbstract { public AudioSid(String locator) { super(locator); } protected JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { "Play", PreviewUtils.ICON_PLAY, this, "Pause", PreviewUtils.ICON_PAUSE, this, "Stop", PreviewUtils.ICON_STOP, this, "Previous", PreviewUtils.ICON_PREVIOUS, this, "Next", PreviewUtils.ICON_NEXT, this, "Copy location", PreviewUtils.ICON_COPY_LOCATION, this, "Open ext", PreviewUtils.ICON_OPEN_EXT, this, "Save as", PreviewUtils.ICON_SAVE, this, }, this); } @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); Mixer mixer = getMixer(); if(startsWithAny(cmd, "Next")) { if(mixer != null) { if(mixer.isNotSeeking() && mixer.isNotPausingNorPaused()) { long currentTrack = mixer.getMillisecondPosition(); long nextTrack = currentTrack + 1; mixer.setMillisecondPosition(Math.min(mixer.getLengthInMilliseconds(), nextTrack)); } } } else if(startsWithAny(cmd, "Previous")) { if(mixer != null) { if(mixer.isNotSeeking() && mixer.isNotPausingNorPaused()) { long currentTrack = mixer.getMillisecondPosition(); long previousTrack = currentTrack - 1001; mixer.setMillisecondPosition(Math.max(0, previousTrack)); } } } else { super.actionPerformed(e); } } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "audio/x-sidtune", "audio/sidtune", "audio/x-psid", "audio/psid", "audio/prs.sid", "audio/x-sid", "application/sid-commodore-64" }, new String[] { "sid" } ); } }
3,488
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
VideoMp4.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/VideoMp4.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.previews.formats; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseMotionAdapter; import javax.swing.JComponent; import javax.swing.JPanel; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.application.gui.simple.SimpleTimeSlider; import org.wandora.utils.ClipboardBox; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.embed.swing.JFXPanel; import javafx.scene.Cursor; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaPlayer.Status; import javafx.scene.media.MediaView; import javafx.scene.paint.Color; import javafx.util.Duration; /** * * @author akivela */ public class VideoMp4 extends JPanel implements PreviewPanel, ActionListener, ComponentListener { private String mediaUrlString = null; private JFXPanel fxPanel; private MediaPlayer player; private boolean playerReady = false; private Scene scene; private MediaView mediaView; private SimpleTimeSlider progressBar; private Media media; private JPanel errorPanel = null; public VideoMp4(String mediaUrlString) { Platform.setImplicitExit(false); this.mediaUrlString = mediaUrlString; initialize(); } private void initialize() { fxPanel = new JFXPanel(); JPanel fxPanelContainer = new JPanel(); fxPanelContainer.setBackground(java.awt.Color.BLACK); fxPanelContainer.setLayout(new BorderLayout()); fxPanelContainer.add(fxPanel, BorderLayout.CENTER); progressBar = new SimpleTimeSlider(); JPanel progressBarContainer = new JPanel(); progressBarContainer.setLayout(new BorderLayout()); progressBarContainer.add(progressBar, BorderLayout.CENTER); JPanel controllerPanel = new JPanel(); controllerPanel.add(getJToolBar(), BorderLayout.CENTER); this.setLayout(new BorderLayout(4,4)); this.add(fxPanelContainer, BorderLayout.NORTH); this.add(progressBarContainer, BorderLayout.CENTER); this.add(controllerPanel, BorderLayout.SOUTH); errorPanel = null; Platform.runLater(new Runnable() { @Override public void run() { Group root = new Group(); scene = new Scene(root); scene.setCursor(Cursor.HAND); scene.setFill(Color.rgb(0, 0, 0, 1.0)); media = getMediaFor(mediaUrlString); if(media != null) { player = getMediaPlayerFor(media); if(player != null) { progressBar.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent e) { int mouseValue = progressBar.getValueFor(e); player.seek(Duration.seconds(mouseValue)); } }); progressBar.addMouseListener(new MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent e) { int mouseValue = progressBar.getValueFor(e); player.seek(Duration.seconds(mouseValue)); } }); mediaView = new MediaView(player); root.getChildren().add(mediaView); } } fxPanel.setScene(scene); } }); this.addComponentListener(this); } // ------------------------------------------------------------------------- private Media getMediaFor(String mediaLocator) { try { final Media m = new Media(mediaLocator); if(m.getError() == null) { m.setOnError(new Runnable() { public void run() { processError(m.getError()); } }); return m; } else { processError(m.getError()); } } catch(Exception e) { processError(e); } return null; } private MediaPlayer getMediaPlayerFor(Media media) { try { playerReady = false; final MediaPlayer mediaPlayer = new MediaPlayer(media); if(mediaPlayer.getError() == null) { mediaPlayer.setAutoPlay(false); mediaPlayer.currentTimeProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue observable, Object oldValue, Object newValue) { Duration newDuration = (Duration) newValue; progressBar.setValue((int) Math.round(newDuration.toSeconds())); updateTimeLabel(); } }); mediaPlayer.setOnReady(new Runnable() { public void run() { playerReady = true; progressBar.setMinimum(0.0); progressBar.setValue(0.0); progressBar.setMaximum(mediaPlayer.getTotalDuration().toSeconds()); refreshLayout(); } }); mediaPlayer.setOnError(new Runnable() { public void run() { processError(mediaPlayer.getError()); } }); return mediaPlayer; } else { processError(mediaPlayer.getError()); } } catch(Exception e) { processError(e); } return null; } private void processError(Exception e) { String message = "Can't view preview for '"+mediaUrlString+"'."; PreviewUtils.previewError(this, message, e); } private JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { "Play", PreviewUtils.ICON_PLAY, this, "Pause", PreviewUtils.ICON_PAUSE, this, "Stop", PreviewUtils.ICON_STOP, this, "Backward", PreviewUtils.ICON_BACKWARD, this, "Forward", PreviewUtils.ICON_FORWARD, this, // "Start", PreviewUtils.ICON_START, this, // "End", PreviewUtils.ICON_END, this, "Restart", PreviewUtils.ICON_RESTART, this, "---", "Open ext", PreviewUtils.ICON_OPEN_EXT, this, "Copy location", PreviewUtils.ICON_COPY_LOCATION, this, "Save as", PreviewUtils.ICON_SAVE, this, }, this); } private void refreshLayout() { if(playerReady) { if(player != null && fxPanel != null && mediaView != null) { if(player.getMedia() != null) { int w = player.getMedia().getWidth(); int h = player.getMedia().getHeight(); int outerWidth = VideoMp4.this.getWidth(); fxPanel.setSize(w, h); fxPanel.setPreferredSize(new Dimension(w, h)); fxPanel.revalidate(); mediaView.translateXProperty().set(outerWidth/2 - w/2); //progressBar.setPreferredSize(new Dimension(outerWidth, 17)); //progressBar.setMaximumSize(new Dimension(outerWidth, 16)); //progressBar.setMinimumSize(new Dimension(outerWidth, 16)); //progressBar.validate(); this.validate(); } } } } private void updateTimeLabel() { Platform.runLater(new Runnable() { @Override public void run() { if(player != null && progressBar != null) { Duration currentTime = player.getCurrentTime(); progressBar.setValue(currentTime.toSeconds()); } } }); } // ------------------------------------------------------------------------- @Override public void finish() { Platform.runLater(new Runnable() { @Override public void run() { if(player != null) { player.stop(); } } }); } @Override public Component getGui() { return this; } @Override public boolean isHeavy() { return false; } @Override public void stop() { Platform.runLater(new Runnable() { @Override public void run() { if(player != null) { // System.out.println("VideoMp4 stopped."); player.stop(); } } }); } // ------------------------------------------------------------------------- @Override public void actionPerformed(java.awt.event.ActionEvent e) { if(e == null) return; String actionCommand = e.getActionCommand(); System.out.println("Action '"+actionCommand+"' performed at FXMediaPlayer"); if("Play".equalsIgnoreCase(actionCommand)) { Platform.runLater(new Runnable() { @Override public void run() { Status status = player.getStatus(); if(!status.equals(Status.PLAYING)) { player.play(); } } }); } else if("Pause".equalsIgnoreCase(actionCommand)) { Platform.runLater(new Runnable() { @Override public void run() { Status status = player.getStatus(); if(status.equals(Status.PAUSED) || status.equals(Status.READY) || status.equals(Status.STOPPED)) { player.play(); } else if(status.equals(Status.PLAYING)) { player.pause(); } } }); } else if("Stop".equalsIgnoreCase(actionCommand)) { Platform.runLater(new Runnable() { @Override public void run() { player.seek(player.getStartTime()); player.stop(); } }); } else if("Backward".equalsIgnoreCase(actionCommand)) { Platform.runLater(new Runnable() { @Override public void run() { player.seek(player.getCurrentTime().divide(1.5)); } }); } else if("Forward".equalsIgnoreCase(actionCommand)) { Platform.runLater(new Runnable() { @Override public void run() { player.seek(player.getCurrentTime().multiply(1.5)); } }); } else if("Restart".equalsIgnoreCase(actionCommand)) { Platform.runLater(new Runnable() { @Override public void run() { player.play(); player.seek(player.getStartTime()); } }); } else if("Open ext".equalsIgnoreCase(actionCommand)) { PreviewUtils.forkExternalPlayer(mediaUrlString); } else if("Save".equalsIgnoreCase(actionCommand)) { PreviewUtils.saveToFile(mediaUrlString); } else if("Copy location".equalsIgnoreCase(actionCommand)) { if(mediaUrlString != null) { ClipboardBox.setClipboard(mediaUrlString); } } } // ------------------------------------------------------------------------- @Override public void componentResized(ComponentEvent e) { Platform.runLater(new Runnable() { @Override public void run() { refreshLayout(); } }); } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { } @Override public void componentHidden(ComponentEvent e) { } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "video/mp4", "video/x-flv", "video/x-javafx", "application/vnd.apple.mpegurl", "audio/mpegurl", "audio/mp3", "audio/aiff", "audio/x-aiff", "audio/wav", "audio/x-m4a", "video/x-m4v" }, new String[] { "mp4", "flv", "fxm", "m3u8", "mp3", "m3a", "aif", "aiff", "wav", "m4a", "m4v" } ); } }
14,826
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApplicationPDF.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/ApplicationPDF.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/>. * * * ApplicationPDF.java * * Created on 12. lokakuuta 2007, 17:14 * */ package org.wandora.application.gui.previews.formats; import static java.awt.event.InputEvent.CTRL_MASK; import static java.awt.event.InputEvent.SHIFT_MASK; import static java.awt.event.KeyEvent.VK_C; import static java.awt.event.KeyEvent.VK_END; import static java.awt.event.KeyEvent.VK_HOME; import static java.awt.event.KeyEvent.VK_MINUS; import static java.awt.event.KeyEvent.VK_PAGE_DOWN; import static java.awt.event.KeyEvent.VK_PAGE_UP; import static java.awt.event.KeyEvent.VK_PLUS; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.nio.ByteBuffer; import java.nio.file.Files; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.KeyStroke; import javax.swing.MenuElement; import javax.swing.event.MouseInputAdapter; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import org.wandora.utils.Functional.Pr2; import org.wandora.utils.IObox; import com.sun.pdfview.PDFFile; public class ApplicationPDF implements PreviewPanel { private static double ZOOMFACTOR = 0.8; private PDFFile pdfFile; private final ApplicationPDFPanel pdfPanel = new ApplicationPDFPanel(); private JPanel masterPanel = null; private int pageCount; private int currentPage; private final PDFActionListener actionListener = new PDFActionListener(); final JPopupMenu menu = UIBox.makePopupMenu(popupStructure, actionListener); final MenuElement pageNumItem = menu.getSubElements()[0]; final JMenuItem item = ((JMenuItem)pageNumItem.getComponent()); private final Pr2<Integer, Integer> setPageText = new Pr2<Integer, Integer>() { @Override public void invoke(final Integer page,final Integer count) { item.setText("Page " + page + " of " + count); } }; private final String source; public ApplicationPDF(String pdfLocator) { this.source = pdfLocator; currentPage = 0; } private void initialize() throws FileNotFoundException, IOException, MalformedURLException, URISyntaxException, Exception { pdfPanel.addMouseListener(actionListener); pdfPanel.addMouseMotionListener(actionListener); pdfPanel.addKeyListener(actionListener); pdfPanel.setComponentPopupMenu(menu); byte[] pdfBytes = null; if(DataURL.isDataURL(source)) { pdfBytes = new DataURL(source).getData(); } else { URL sourceURL = new URL(source); if("file".equalsIgnoreCase(sourceURL.getProtocol())) { pdfBytes = Files.readAllBytes(new File(sourceURL.toURI()).toPath()); } else { pdfBytes = IObox.fetchUrl(sourceURL); } } if(pdfBytes != null) { pdfFile = new PDFFile(ByteBuffer.wrap(pdfBytes)); if(pdfFile != null) { pageCount = pdfFile.getNumPages(); if(pageCount > 0) { setPageText.invoke(1, pageCount); pdfPanel.changePage(pdfFile.getPage(0)); } else { throw new Exception("PDF has no pages at all. Can't view."); } } } else { throw new Exception("Can't read data out of locator resource."); } } @Override public void stop() { } @Override public void finish() { } @Override public Component getGui() { if(masterPanel == null) { masterPanel = new JPanel(); masterPanel.setLayout(new BorderLayout(8, 8)); try { initialize(); JPanel pdfWrapper = new JPanel(); pdfWrapper.add(pdfPanel, BorderLayout.CENTER); JPanel controllerPanel = new JPanel(); controllerPanel.add(getJToolBar(), BorderLayout.CENTER); masterPanel.add(pdfWrapper, BorderLayout.CENTER); masterPanel.add(controllerPanel, BorderLayout.SOUTH); } catch(URISyntaxException use) { PreviewUtils.previewError(masterPanel, "Malformed locator URI syntax. Can't resolve.", use); } catch(MalformedURLException mue) { PreviewUtils.previewError(masterPanel, "Malformed locator URL. Can't resolve.", mue); } catch(FileNotFoundException fnfe) { PreviewUtils.previewError(masterPanel, "Locator resource not found.", fnfe); } catch(IOException ioe) { PreviewUtils.previewError(masterPanel, "Can't read the locator resource.", ioe); } catch(Exception e) { PreviewUtils.previewError(masterPanel, "Error occurred while initializing the PFD preview.", e); } } return masterPanel; } @Override public boolean isHeavy() { return false; } private JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { FIRST, UIBox.getIcon(0xf049), actionListener, PREV, UIBox.getIcon(0xf048), actionListener, NEXT, UIBox.getIcon(0xf051), actionListener, LAST, UIBox.getIcon(0xf050), actionListener, ZOOM_IN, PreviewUtils.ICON_ZOOM_IN, actionListener, ZOOM_OUT, PreviewUtils.ICON_ZOOM_OUT, actionListener, COPY_IMAGE, PreviewUtils.ICON_COPY_IMAGE, actionListener, COPY_LOCATION, PreviewUtils.ICON_COPY_LOCATION, actionListener, SAVE, PreviewUtils.ICON_SAVE, actionListener, }, actionListener); } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "application/pdf", }, new String[] { "pdf" } ); } // ------------------------------------------------------------------------- private class PDFActionListener extends MouseInputAdapter implements ActionListener, KeyListener { private Point lastPoint; private Dimension offset; public PDFActionListener() { lastPoint = null; offset = new Dimension(0, 0); } private boolean leftBtnDown(MouseEvent e) { final int modifiers = e.getModifiersEx(); return (modifiers & MouseEvent.BUTTON1_DOWN_MASK) != 0; } @Override public void mousePressed(MouseEvent e) { pdfPanel.requestFocus(); if(leftBtnDown(e) && lastPoint == null) { lastPoint = e.getPoint(); } } @Override public void mouseDragged(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { if(!leftBtnDown(e)) { lastPoint = null; } } private int intoRange(final int pageNumber) { if(pageNumber < 0) { return pageCount + (pageNumber % pageCount); } else { return pageNumber % pageCount; } } private void setLastPage() { currentPage = pageCount-1; pdfPanel.changePage(pdfFile.getPage(currentPage + 1)); setPageText.invoke(currentPage + 1, pageCount); } private void setFirstPage() { currentPage = 0; pdfPanel.changePage(pdfFile.getPage(currentPage + 1)); setPageText.invoke(currentPage + 1, pageCount); } private void changePage(final int offset) { currentPage = intoRange(currentPage + offset); pdfPanel.changePage(pdfFile.getPage(currentPage + 1)); setPageText.invoke(currentPage + 1, pageCount); } @Override public void actionPerformed(ActionEvent args) { String c = args.getActionCommand(); if(c == null) return; if(c.equals(OPEN_EXTERNAL) || c.equals(OPEN_EXT)) { PreviewUtils.forkExternalPlayer(source); } else if(c.equals(COPY_LOCATION)) { ClipboardBox.setClipboard(source.toString()); } else if(c.equals(COPY_IMAGE)) { BufferedImage image = new BufferedImage(pdfPanel.getWidth(), pdfPanel.getHeight(), BufferedImage.TYPE_INT_BGR); pdfPanel.paint(image.getGraphics()); ClipboardBox.setClipboard(image); } else if(c.equals(SAVE_AS) || c.equals(SAVE)) { PreviewUtils.saveToFile(source); } else if(c.equals(ZOOM_DEFAULT)) { pdfPanel.setZoom(1.0); } else if(c.equals(ZOOM_50)) { pdfPanel.setZoom(0.5); } else if(c.equals(ZOOM_200)) { pdfPanel.setZoom(2.0); } else if(c.equals(ZOOM_IN)) { pdfPanel.setZoom(pdfPanel.getZoom() / ZOOMFACTOR); } else if(c.equals(ZOOM_OUT)) { pdfPanel.setZoom(pdfPanel.getZoom() * ZOOMFACTOR); } else if(c.equals(NEXT_PAGE) || c.equals(NEXT)) { changePage(1); } else if(c.equals(PREV_PAGE) || c.equals(PREV)) { changePage(-1); } else if(c.equals(JUMP_10_FWD)) { changePage(10); } else if(c.equals(JUMP_10_REV)) { changePage(-10); } else if(c.equals(JUMP_100_FWD)) { changePage(100); } else if(c.equals(JUMP_100_REV)) { changePage(-100); } else if(c.equals(JUMP_HOME) || c.equals(FIRST)) { setFirstPage(); } else if(c.equals(JUMP_END) || c.equals(LAST)) { setLastPage(); } } // --------------------------------------------- @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if(keyCode == KeyEvent.VK_PAGE_UP) { if(e.isShiftDown()) changePage(-10); else if(e.isControlDown()) changePage(-100); else changePage(-1); e.consume(); } else if(keyCode == KeyEvent.VK_PAGE_DOWN) { if(e.isShiftDown()) changePage(10); else if(e.isControlDown()) changePage(100); else changePage(1); e.consume(); } else if(keyCode == KeyEvent.VK_HOME) { setFirstPage(); } else if(keyCode == KeyEvent.VK_END) { setLastPage(); } else if(keyCode == KeyEvent.VK_MINUS) { pdfPanel.setZoom(pdfPanel.getZoom() * ZOOMFACTOR); // ZOOMING OUT } else if(keyCode == KeyEvent.VK_PLUS) { pdfPanel.setZoom(pdfPanel.getZoom() / ZOOMFACTOR); // ZOOMING IN } else if(keyCode == KeyEvent.VK_C && e.isControlDown()) { BufferedImage image = new BufferedImage(pdfPanel.getWidth(), pdfPanel.getHeight(), BufferedImage.TYPE_INT_BGR); pdfPanel.paint(image.getGraphics()); ClipboardBox.setClipboard(image); } } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } } private static final String OPEN_EXT = "Open ext", OPEN_EXTERNAL = "Open in external viewer...", COPY_LOCATION = "Copy location", COPY_IMAGE = "Copy as image", SAVE = "Save", SAVE_AS = "Save media as...", ZOOM_OUT = "Zoom out", ZOOM_IN = "Zoom in", ZOOM_50 = "50%", ZOOM_DEFAULT = "100%", ZOOM_150 = "150%", ZOOM_200 = "200%", NEXT = "Next", NEXT_PAGE = "Next page", PREV = "Previous", PREV_PAGE = "Previous page", JUMP_10_FWD = "10 pages forward", JUMP_10_REV = "10 pages back", JUMP_100_FWD = "100 pages forward", JUMP_100_REV = "100 pages back", FIRST = "First", JUMP_HOME = "First page", LAST = "Last", JUMP_END = "Last page"; private static final Object[] popupStructure = new Object[] { "[No page loaded]", "---", NEXT_PAGE, KeyStroke.getKeyStroke(VK_PAGE_UP, 0), PREV_PAGE, KeyStroke.getKeyStroke(VK_PAGE_UP, 0), "Jump", new Object[] { JUMP_HOME, KeyStroke.getKeyStroke(VK_HOME, 0), JUMP_END, KeyStroke.getKeyStroke(VK_END, 0), "---", JUMP_100_FWD, KeyStroke.getKeyStroke(VK_PAGE_DOWN, CTRL_MASK), JUMP_10_FWD, KeyStroke.getKeyStroke(VK_PAGE_DOWN, SHIFT_MASK), JUMP_10_REV, KeyStroke.getKeyStroke(VK_PAGE_UP, SHIFT_MASK), JUMP_100_REV, KeyStroke.getKeyStroke(VK_PAGE_UP, CTRL_MASK), }, "---", // OFFSET_DEFAULT, "Zoom", new Object[] { ZOOM_IN, KeyStroke.getKeyStroke(VK_PLUS, 0), ZOOM_OUT, KeyStroke.getKeyStroke(VK_MINUS, 0), "---", ZOOM_50, ZOOM_DEFAULT, ZOOM_150, ZOOM_200, }, "---", OPEN_EXTERNAL, COPY_LOCATION, COPY_IMAGE, KeyStroke.getKeyStroke(VK_C, CTRL_MASK), "---", SAVE_AS, }; }
15,647
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Text.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/Text.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.previews.formats; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import java.net.URL; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import org.wandora.utils.IObox; import org.wandora.utils.swing.TextLineNumber; /** * * @author akivela */ public class Text implements ActionListener, PreviewPanel { String locator = null; JPanel ui = null; JEditorPane textPane = null; public Text(String locator) { this.locator = locator; } @Override public void finish() { } @Override public void stop() { } @Override public boolean isHeavy() { return false; } protected JComponent getTextComponent(String locator) throws Exception { JTextPane textComponent = new JTextPane(); textComponent.setText(getContent(locator)); textComponent.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); textComponent.setEditable(false); textComponent.setCaretPosition(0); return textComponent; } @Override public JPanel getGui() { if(ui == null) { ui = new JPanel(); ui.setLayout(new BorderLayout(8,8)); JPanel textPaneWrapper = new JPanel(); textPaneWrapper.setLayout(new BorderLayout()); textPaneWrapper.setPreferredSize(new Dimension(640, 400)); textPaneWrapper.setMaximumSize(new Dimension(640, 400)); textPaneWrapper.setSize(new Dimension(640, 400)); try { textPane = (JEditorPane) getTextComponent(locator); JScrollPane scrollPane = new SimpleScrollPane(textPane); TextLineNumber tln = new TextLineNumber(textPane); scrollPane.setRowHeaderView( tln ); textPaneWrapper.add(scrollPane); JPanel toolbarWrapper = new JPanel(); toolbarWrapper.add(getJToolBar()); ui.add(textPaneWrapper, BorderLayout.CENTER); ui.add(toolbarWrapper, BorderLayout.SOUTH); } catch(FileNotFoundException fnfe) { PreviewUtils.previewError(ui, "Can't find locator resource.", fnfe); } catch(Exception e) { PreviewUtils.previewError(ui, "Can't initialize text viewer. Exception occurred.", e); } } return ui; } protected String getContent(String locator) throws Exception { try { if(locator.startsWith("file:")) { return IObox.loadFile(new URL(locator).getFile()); } else if(DataURL.isDataURL(locator)) { DataURL dataUrl = new DataURL(locator); byte[] dataBytes = dataUrl.getData(); String dataString = new String(dataBytes); return dataString; } else { return IObox.doUrl(new URL(locator)); } } catch(Exception e) { // PreviewUtils.previewError(ui, "Unable to read locator content.", e); throw e; } } protected JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { "Open ext", PreviewUtils.ICON_OPEN_EXT, this, "Copy location", PreviewUtils.ICON_COPY_LOCATION, this, "Save", PreviewUtils.ICON_SAVE, this, }, this); } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c == null) return; if(c.startsWith("Open ext")) { PreviewUtils.forkExternalPlayer(locator); } else if(c.equalsIgnoreCase("Copy location")) { if(locator != null) { ClipboardBox.setClipboard(locator); } } else if(c.startsWith("Save")) { PreviewUtils.saveToFile(locator); } } // ------------------------------------------------------------------------- public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "text", "application/x-sh" }, new String[] { "txt", "text", "asm", "asp", "bat", "c", "c++", "cc", "com", "conf", "cpp", "csh", "ccs", "cxx", "def", "g", "h", "hh", "idc", "jav", "java", "js", "ksh", "list", "log", "lst", "m", "mar", "p", "pas", "pl", "py", "r", "sdml", "sgml", "sh", "sketch", "uri", "uni", "unis", "zhs" } ); } }
6,925
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApplicationZ80.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/ApplicationZ80.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.previews.formats; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Graphics; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.net.MalformedURLException; import java.util.HashMap; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JPopupMenu; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.WandoraOptionPane; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.application.gui.previews.formats.applicationz80.Qaop; import org.wandora.application.tools.extractors.files.SimpleFileExtractor; import org.wandora.topicmap.TopicMap; import org.wandora.utils.Base64; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; /** * * @author akivela */ public class ApplicationZ80 implements ActionListener, PreviewPanel, ComponentListener { private String locator = null; private Qaop qaop = null; private JPanel qaopWrapper = null; private JPanel ui = null; private boolean isPaused = false; private boolean isMuted = false; private int sizeScaler = 1; public ApplicationZ80(String locator) { this.locator = locator; } @Override public void stop() { if(qaop != null) { qaop.destroy(); qaop = null; } } @Override public void finish() { if(qaop != null) { qaop.destroy(); qaop = null; } } @Override public Component getGui() { if(ui == null) { ui = new JPanel(); ui.setLayout(new BorderLayout(8,8)); ui.addComponentListener(this); try { qaopWrapper = new JPanel(); if(qaop == null) { HashMap params = new HashMap(); if(DataURL.isDataURL(locator)) { params.put("load", new DataURL(locator).toExternalForm(Base64.DONT_BREAK_LINES)); } else { params.put("load", locator); } params.put("focus", "1"); qaop = new Qaop(params); qaop.addComponentListener(this); qaopWrapper.add(qaop); } JPanel toolbarWrapper = new JPanel(); toolbarWrapper.add(getJToolBar()); ui.add(qaopWrapper, BorderLayout.CENTER); ui.add(toolbarWrapper, BorderLayout.SOUTH); } catch(Exception e) { PreviewUtils.previewError(ui, "Can't initialize text viewer. Exception occurred.", e); } } return ui; } protected JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { getMenuButton(), }, this); } public JButton getMenuButton() { final JButton button = UIBox.makeDefaultButton(); button.setIcon(UIBox.getIcon(0xf0c9)); button.setToolTipText("Sinclair ZX preview options."); button.setBorder(null); button.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { getOptionsMenu().show(button, e.getX(), e.getY()); } }); return button; } private static final Icon selectedIcon = UIBox.getIcon("gui/icons/checked2.png"); private static final Icon unselectedIcon = UIBox.getIcon("gui/icons/empty.png"); public JPopupMenu getOptionsMenu() { Object[] menuStruct = new Object[] { "Open subject locator in ext", PreviewUtils.ICON_OPEN_EXT, "Copy subject locator", PreviewUtils.ICON_COPY_LOCATION, "Save subject locator resource...", PreviewUtils.ICON_SAVE, "---", "Reify snapshot", "Reify screen capture", "---", "Display size", new Object[] { "1x", sizeScaler == 1 ? selectedIcon : unselectedIcon, "2x", sizeScaler == 2 ? selectedIcon : unselectedIcon, }, "Mute", isMuted ? selectedIcon : unselectedIcon, "---", "Pause", isPaused ? selectedIcon : unselectedIcon, "Reset", "---", "About" }; JPopupMenu optionsPopup = UIBox.makePopupMenu(menuStruct, this); return optionsPopup; } @Override public void actionPerformed(java.awt.event.ActionEvent actionEvent) { String c = actionEvent.getActionCommand(); if(c == null) return; if("Open subject locator in ext".equalsIgnoreCase(c)) { PreviewUtils.forkExternalPlayer(locator); } else if("Copy subject locator".equalsIgnoreCase(c)) { if(locator != null) { ClipboardBox.setClipboard(locator); } } else if("Save subject locator resource...".equalsIgnoreCase(c)) { PreviewUtils.saveToFile(locator); } else if("Reify snapshot".equalsIgnoreCase(c)) { DataURL snapshot = makeSnapshot(); if(snapshot != null) { saveToTopic(snapshot); } } else if("Reify screen capture".equalsIgnoreCase(c)) { DataURL screenCapture = makeScreenCapture(); if(screenCapture != null) { saveToTopic(screenCapture); } } else if("Type text...".equalsIgnoreCase(c)) { } else if("Enter a special key...".equalsIgnoreCase(c)) { } else if("1x".equalsIgnoreCase(c)) { setScaling(1); } else if("2x".equalsIgnoreCase(c)) { setScaling(2); } else if("Display size".equalsIgnoreCase(c)) { sizeScaler += 1; if(sizeScaler > 2) sizeScaler = 1; setScaling(sizeScaler); } else if("Mute".equalsIgnoreCase(c)) { isMuted = !isMuted; qaop.mute(isMuted); } else if("Reset".equalsIgnoreCase(c)) { qaop.reset(); } else if("Pause".equalsIgnoreCase(c)) { isPaused = !isPaused; qaop.pause(isPaused); } else if("Resume".equalsIgnoreCase(c)) { isPaused = false; qaop.pause(isPaused); } else if("About".equalsIgnoreCase(c)) { StringBuilder aboutBuilder = new StringBuilder(""); aboutBuilder.append("Wandora's Sinclair ZX emulation support is based on Qaop - ZX Spectrum emulator by Jan Bobrowski "); aboutBuilder.append("distributed under the license of GNU GPL."); qaop.pause(true); WandoraOptionPane.showMessageDialog(Wandora.getWandora(), aboutBuilder.toString(), "About Sinclair ZX emulation"); qaop.pause(false); } } private void setScaling(int scale) { sizeScaler = scale; qaop.setScreenSize(scale); qaop.validate(); qaop.repaint(); } // ------------------------------------------------------------------------- private DataURL makeSnapshot() { try { return new DataURL(qaop.save()); } catch (MalformedURLException ex) { ex.printStackTrace(); } return null; } private DataURL makeScreenCapture() { try { BufferedImage screenCaptureImage = new BufferedImage(qaop.getPreferredSize().width, qaop.getPreferredSize().height, BufferedImage.TYPE_INT_RGB); Graphics screenCaptureGraphics = screenCaptureImage.createGraphics(); qaop.paintAll(screenCaptureGraphics); DataURL screenCaptureDataUrl = null; screenCaptureDataUrl = new DataURL(screenCaptureImage); return screenCaptureDataUrl; } catch(Exception e) { e.printStackTrace(); } return null; } private void saveToTopic(DataURL dataUrl) { Wandora wandora = Wandora.getWandora(); try { TopicMap topicMap = wandora.getTopicMap(); SimpleFileExtractor simpleFileExtractor = new SimpleFileExtractor(); simpleFileExtractor._extractTopicsFrom(dataUrl.toExternalForm(), topicMap); wandora.doRefresh(); } catch(Exception e) { wandora.handleError(e); } } // ------------------------------------------------------------------------- @Override public boolean isHeavy() { return false; } public static boolean canView(String url) { return PreviewUtils.isOfType(url, new String[] { "application/x.zx.", "application/x-spectrum-", "application/x.spectrum." }, new String[] { "z80", "slt", "tap", "sna", "rom", "z80.gz", "slt.gz", "tap.gz", "sna.gz", "rom.gz" } ); } // ------------------------------------------------------------------------- private void refreshSize() { if(qaopWrapper != null) { qaopWrapper.setPreferredSize(qaop.getPreferredSize()); qaopWrapper.setSize(qaop.getPreferredSize()); qaopWrapper.revalidate(); ui.validate(); } } @Override public void componentResized(ComponentEvent e) { refreshSize(); } @Override public void componentMoved(ComponentEvent e) { refreshSize(); } @Override public void componentShown(ComponentEvent e) { refreshSize(); } @Override public void componentHidden(ComponentEvent e) { } }
11,564
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApplicationPDFPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/ApplicationPDFPanel.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/>. * * * ApplicationPDFPanel.java * * Created on 12. lokakuuta 2007, 17:14 * */ package org.wandora.application.gui.previews.formats; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import javax.swing.JPanel; import org.wandora.application.gui.UIBox; import com.sun.pdfview.PDFPage; /** * * @author akivela, anttirt */ public class ApplicationPDFPanel extends JPanel { private Image currentImage; private BufferedImage currentBufferedImage; private PDFPage currentPage; private double zoom; public ApplicationPDFPanel() { super(); this.currentPage = null; zoom = 1.0; currentImage = null; } public void changePage(PDFPage page) { currentPage = page; refresh(); repaint(); } public void setZoom(double zoom) { if(zoom > .1 && zoom < 10) { this.zoom = zoom; refresh(); repaint(); } } public double getZoom() { return zoom; } @Override public void setSize(int width, int height) { super.setSize(width, height); repaint(); } @Override public void setSize(Dimension d) { super.setSize(d); repaint(); } @Override protected void paintComponent(Graphics g) { int w = getWidth(); int h = getHeight(); if(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); ((Graphics2D) g).addRenderingHints(qualityHints); ((Graphics2D) g).addRenderingHints(antialiasHints); } if(currentBufferedImage == null) { g.setColor(getBackground()); g.fillRect(0, 0, w, h); g.setColor(Color.black); g.drawString("No page selected", getWidth() / 2 - 30, getHeight() / 2); } else { g.setColor(getBackground()); g.fillRect(0, 0, w, h); g.drawImage(currentBufferedImage, 0, 0, currentBufferedImage.getWidth(), currentBufferedImage.getHeight(), null); } } private void refresh() { if(currentPage != null) { int w = (int) (currentPage.getWidth() * zoom); int h = (int) (currentPage.getHeight() * zoom); Rectangle rect = new Rectangle(0, 0, w, h); Rectangle clip = currentPage.getBBox().getBounds(); int rotation = currentPage.getRotation(); if(rotation == 90 || rotation == 270) { clip = new Rectangle( (int) clip.getY(), (int) clip.getX(), (int) clip.getHeight(), (int) clip.getWidth() ); } Dimension pageSize = new Dimension(rect.width, rect.height); setPreferredSize(pageSize); setMinimumSize(pageSize); setMaximumSize(pageSize); currentImage = currentPage.getImage( rect.width, // lastPageSize.width, rect.height, // lastPageSize.height, clip, null, /* imageobserver */ true, /* draw white bg */ true); /* block */ currentBufferedImage = UIBox.makeBufferedImage(currentImage); revalidate(); } } }
5,008
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AudioAbstract.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/AudioAbstract.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.previews.formats; import static org.wandora.application.gui.previews.PreviewUtils.startsWithAny; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Properties; import javax.swing.JComponent; import javax.swing.JPanel; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.previews.PreviewPanel; import org.wandora.application.gui.previews.PreviewUtils; import org.wandora.application.gui.simple.SimpleTimeSlider; import org.wandora.utils.ClipboardBox; import org.wandora.utils.DataURL; import org.wandora.utils.MimeTypes; import de.quippy.javamod.main.JavaModMainBase; import de.quippy.javamod.mixer.Mixer; import de.quippy.javamod.multimedia.MultimediaContainer; import de.quippy.javamod.multimedia.MultimediaContainerManager; import de.quippy.javamod.multimedia.mod.ModContainer; /** * AudioAbstract uses Daniel Becker's Javamod player. * * @author akivela */ public abstract class AudioAbstract extends JavaModMainBase implements PreviewPanel, ActionListener { private String locator = null; private PlayerThread playerThread = null; private JPanel ui = null; private Mixer currentMixer; private SimpleTimeSlider progressBar = null; private File tmpFile = null; public AudioAbstract(String locator) { super(false); this.locator = locator; } @Override public void stop() { if(currentMixer != null) { currentMixer.stopPlayback(); } } @Override public void finish() { if(currentMixer != null) { currentMixer.stopPlayback(); } } @Override public Component getGui() { if(ui == null) { ui = makeUI(); } return ui; } @Override public boolean isHeavy() { return false; } @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if(startsWithAny(cmd, "Play")) { if(currentMixer != null && currentMixer.isPaused()) { currentMixer.pausePlayback(); } else { playerThread = new PlayerThread(); } } else if(startsWithAny(cmd, "Pause")) { if(currentMixer != null) { currentMixer.pausePlayback(); } } else if(startsWithAny(cmd, "Stop")) { if(currentMixer != null) { currentMixer.stopPlayback(); currentMixer = null; } } else if(startsWithAny(cmd, "Forward")) { if(currentMixer != null) { if(currentMixer.isNotSeeking() && currentMixer.isNotPausingNorPaused()) { long currentPosition = currentMixer.getMillisecondPosition(); long forwardPosition = currentPosition + 10000; currentMixer.setMillisecondPosition(forwardPosition); } } } else if(startsWithAny(cmd, "Backward")) { if(currentMixer != null) { if(currentMixer.isNotSeeking() && currentMixer.isNotPausingNorPaused()) { long currentPosition = currentMixer.getMillisecondPosition(); long backwardPosition = currentPosition - 10000; currentMixer.setMillisecondPosition(Math.max(0, backwardPosition)); } } } else if(startsWithAny(cmd, "Open ext")) { if(locator != null) { PreviewUtils.forkExternalPlayer(locator); } } else if(startsWithAny(cmd, "Copy audio location", "Copy location")) { if(locator != null) { ClipboardBox.setClipboard(locator); } } else if(startsWithAny(cmd, "Save")) { if(locator != null) { PreviewUtils.saveToFile(locator); } } } protected Mixer getMixer() { return currentMixer; } // ------------------ protected JPanel makeUI() { JPanel ui = new JPanel(); progressBar = new SimpleTimeSlider(); progressBar.setString(locator); JPanel progressBarContainer = new JPanel(); progressBarContainer.setLayout(new BorderLayout()); progressBarContainer.add(progressBar, BorderLayout.CENTER); JPanel controllerPanel = new JPanel(); controllerPanel.add(getJToolBar(), BorderLayout.CENTER); ui.setLayout(new BorderLayout(8,8)); ui.add(progressBarContainer, BorderLayout.CENTER); ui.add(controllerPanel, BorderLayout.SOUTH); progressBar.addMouseListener(new MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent e) { int mouseValue = progressBar.getValueFor(e); if(currentMixer != null && currentMixer.isSeekSupported()) { if(currentMixer.isNotSeeking() && currentMixer.isNotPausingNorPaused()) { currentMixer.setMillisecondPosition(mouseValue*1000); // System.out.println("newPosition: "+mouseValue*1000); // System.out.println("newPosition2: "+currentMixer.getMillisecondPosition()); } } } }); return ui; } protected JComponent getJToolBar() { return UIBox.makeButtonContainer(new Object[] { "Play", PreviewUtils.ICON_PLAY, this, "Pause", PreviewUtils.ICON_PAUSE, this, "Stop", PreviewUtils.ICON_STOP, this, "---", "Backward", PreviewUtils.ICON_BACKWARD, this, "Forward", PreviewUtils.ICON_FORWARD, this, "---", "Copy location", PreviewUtils.ICON_COPY_LOCATION, this, "Open ext", PreviewUtils.ICON_OPEN_EXT, this, "Save as", PreviewUtils.ICON_SAVE, this, }, this); } // ------------------------------------------------------------------------- protected class PlayerThread extends Thread { private ProgressThread progressThread = null; public PlayerThread() { Properties props = new Properties(); props.setProperty(ModContainer.PROPERTY_PLAYER_ISP, "3"); props.setProperty(ModContainer.PROPERTY_PLAYER_STEREO, "2"); props.setProperty(ModContainer.PROPERTY_PLAYER_WIDESTEREOMIX, "FALSE"); props.setProperty(ModContainer.PROPERTY_PLAYER_NOISEREDUCTION, "FALSE"); props.setProperty(ModContainer.PROPERTY_PLAYER_NOLOOPS, "1"); props.setProperty(ModContainer.PROPERTY_PLAYER_MEGABASS, "TRUE"); props.setProperty(ModContainer.PROPERTY_PLAYER_BITSPERSAMPLE, "16"); props.setProperty(ModContainer.PROPERTY_PLAYER_FREQUENCY, "48000"); props.setProperty(ModContainer.PROPERTY_PLAYER_MSBUFFERSIZE, "250"); MultimediaContainerManager.configureContainer(props); this.setDaemon(true); this.start(); } @Override public void run() { try { if(progressThread == null) { progressThread = new ProgressThread(progressBar); } if(currentMixer == null) { createMixer(); } if(currentMixer != null) { progressThread.setMixer(currentMixer); progressThread.start(); currentMixer.startPlayback(); } } catch(Exception ex) { ui.removeAll(); JComponent errorPanel = PreviewUtils.previewError(ui, "Error while starting player", ex); ex.printStackTrace(System.err); } if(progressThread != null) { progressThread.abort(); progressThread = null; } currentMixer = null; } public void createMixer() { try { if(DataURL.isDataURL(locator)) { DataURL dataUrl = new DataURL(locator); tmpFile = dataUrl.createTempFile(); if(tmpFile != null) { MultimediaContainer multimediaContainer = MultimediaContainerManager.getMultimediaContainer(tmpFile); currentMixer = multimediaContainer.createNewMixer(); } else { PreviewUtils.previewError(ui, "Unable to create temporal file for a dataurl."); } } else if(locator.startsWith("file:")) { MultimediaContainer multimediaContainer = MultimediaContainerManager.getMultimediaContainer(new URL(locator)); currentMixer = multimediaContainer.createNewMixer(); } else { File tempfile = createTempFile(new URL(locator)); MultimediaContainer multimediaContainer = MultimediaContainerManager.getMultimediaContainer(tempfile.toURI().toURL()); currentMixer = multimediaContainer.createNewMixer(); } } catch(IOException ioe) { PreviewUtils.previewError(ui, "IOException occurred while preparing media.", ioe); } catch(Exception e) { PreviewUtils.previewError(ui, "Unable to play audio.", e); } } private File createTempFile(URL url) throws Exception { HttpURLConnection con = (HttpURLConnection) url.openConnection(); Wandora.initUrlConnection(con); con.setRequestMethod("GET"); con.setDoOutput(false); //con.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) "); //con.setRequestProperty("Accept","*/*"); String prefix = "wandora" + url.hashCode(); String mimetype = null; String suffix = null; mimetype = MimeTypes.getMimeType(url); if(mimetype != null) { suffix = MimeTypes.getExtension(mimetype); } if(suffix == null) { mimetype = con.getContentType(); suffix = MimeTypes.getExtension(mimetype); } //System.out.println("mimetype: "+mimetype); //System.out.println("suffix: "+suffix); if(suffix == null) suffix = "tmp"; if(!suffix.startsWith(".")) suffix = "."+suffix; String tmpdir = System.getProperty("java.io.tmpdir"); File tempFile = new File(tmpdir + File.separator + prefix + suffix); //System.out.println("tempFile: "+tempFile.getAbsolutePath()); if(!tempFile.exists()) { tempFile.deleteOnExit(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] chunk = new byte[128]; int bytesRead; int contentLength = con.getContentLength(); int totalBytesRead = 0; InputStream stream = con.getInputStream(); try { while ((bytesRead = stream.read(chunk)) > 0) { outputStream.write(chunk, 0, bytesRead); if(progressThread != null) { totalBytesRead = totalBytesRead + bytesRead; progressThread.setProgress("Downloading...", totalBytesRead, contentLength); } } stream.close(); } catch(Exception e) { stream.close(); throw e; } byte[] bytes = outputStream.toByteArray(); if(bytes != null && bytes.length > 0) { FileOutputStream fos = new FileOutputStream(tempFile); try { fos.write(bytes); fos.close(); } catch(Exception e) { fos.close(); throw e; } } } return tempFile; } } // ------------------------------------------------------------------------- protected class ProgressThread extends Thread { private Mixer progressMixer = null; private SimpleTimeSlider progressBar = null; private boolean isRunning = true; public ProgressThread(SimpleTimeSlider bar) { progressBar = bar; if(progressBar != null) { progressBar.setMinimum(0.0); progressBar.setValue(0.0); } } public void setMixer(Mixer mixer) { progressMixer = mixer; if(progressBar != null) { progressBar.setValue(0.0); if(progressMixer != null) { progressBar.setMaximum(progressMixer.getLengthInMilliseconds() / 1000); } } } public void setProgress(String text, int value, int maxValue) { progressBar.setProgress(text, 0, value, maxValue); } @Override public void run() { long progress = 0; while(progressMixer != null && progressBar != null && isRunning) { try { if(progressMixer.isNotSeeking()) { progress = progressMixer.getMillisecondPosition() / 1000; progressBar.setValue((int) progress); } Thread.sleep(100); } catch(Exception e) {} } progressBar.setValue(0); progressBar.setString(locator); } public void abort() { isRunning = false; } } }
15,732
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Spectrum.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/applicationz80/Spectrum.java
/* * Spectrum.java * * Copyright 2004-2009 Jan Bobrowski <jb@wizard.ae.krakow.pl> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ package org.wandora.application.gui.previews.formats.applicationz80; import java.awt.event.KeyEvent; import java.awt.image.ColorModel; import java.awt.image.ImageConsumer; import java.awt.image.ImageProducer; import java.awt.image.IndexColorModel; import java.util.Vector; public class Spectrum extends Thread implements Z80.Env, ImageProducer { final Z80 cpu = new Z80(this); final Qaop qaop; int rom48k[] = new int[16384]; final int ram[] = new int[49152]; int rom[] = rom48k; int if1rom[]; final Audio audio; Spectrum(Qaop q) { super("Spectrum"); qaop = q; for (int i = 0; i < 8; i++) { keyboard[i] = 0xFF; } for (int i = 6144; i < 6912; i++) { ram[i] = 070; // white } audio = new Audio(); audio.open(3500000); } public void run() { try { frames(); } catch (InterruptedException e) { } audio.close(); } private void end_frame() { refresh_screen(); if (border != border_solid) { int t = refrb_t; refresh_border(); if (t == BORDER_START) { border_solid = border; } } for (int i = 0; i < consumers.size();) { ImageConsumer c = (ImageConsumer) consumers.elementAt(consumers.size() - ++i); update_screen(c); } send_change(); cpu.time -= FRTIME; if (--flash_count <= 0) { flash ^= 0xFF; flash_count = 16; } audio.level -= audio.level >> 8; } private long time; private int timet; static final int FRSTART = -14335; static final int FRTIME = 69888; private void frames() throws InterruptedException { time = System.currentTimeMillis(); cpu.time = FRSTART; cpu.time_limit = FRSTART + FRTIME; au_time = cpu.time; do { byte[] tap = null; boolean tend = false; synchronized (this) { int w = want_scale; if (w != scale) { if (w < 0) { break; // quit } scale = w; width = w * W; height = w * H; cm = w == 0 ? cm1 : cm2; notifyAll(); abort_consumers(); } w = want_pause; if ((w != 0) ^ paused) { paused = w != 0; notifyAll(); } if (stop_loading) { loading = stop_loading = false; notifyAll(); } if (!paused) { tap = tape; tend = tape_ready; if (!loading && tap != null) { loading = check_load(); } } } update_keyboard(); refresh_new(); if (paused) { int t = cpu.time = cpu.time_limit; audio.step(t - au_time, 0); au_time = t; } else { if (loading) { loading = do_load(tap, tend); cpu.time = cpu.time_limit; } else { cpu.interrupt(0xFF); cpu.execute(); } au_update(); } au_time -= FRTIME; end_frame(); /* sync */ timet += 121; if (timet >= 125) { timet -= 125; time++; } time += 19; long t = System.currentTimeMillis(); if (t < time) { t = time - t; sleep(t); } else { // yield(); t -= 100; if (t > time) { time = t; } } } while (!interrupted()); } boolean paused = true; int want_pause = 1; public synchronized int pause(int m) throws InterruptedException { if ((want_pause = want_pause & ~m >> 3 ^ m & 7) != 0 && !paused) { do { wait(); } while (!paused); } return want_pause; } public synchronized void reset() { stop_loading(); cpu.reset(); au_reset(); rom = rom48k; } /* Z80.Env */ public final int m1(int addr, int ir) { int n = cpu.time - ctime; if (n > 0) { cont(n); } addr -= 0x4000; if ((addr & 0xC000) == 0) { cont1(0); } ctime = NOCONT; if ((ir & 0xC000) == 0x4000) { ctime = cpu.time + 4; } if (addr >= 0) { return ram[addr]; } n = rom[addr += 0x4000]; if (if1rom != null && (addr & 0xE8F7) == 0) { if (addr == 0x0008 || addr == 0x1708) { if (rom == rom48k) { rom = if1rom; } } else if (addr == 0x0700) { if (rom == if1rom) { rom = rom48k; } } } return n; } public final int mem(int addr) { int n = cpu.time - ctime; if (n > 0) { cont(n); } ctime = NOCONT; addr -= 0x4000; if (addr >= 0) { if (addr < 0x4000) { cont1(0); ctime = cpu.time + 3; } return ram[addr]; } return rom[addr + 0x4000]; } public final int mem16(int addr) { int n = cpu.time - ctime; if (n > 0) { cont(n); } ctime = NOCONT; int addr1 = addr - 0x3FFF; if ((addr1 & 0x3FFF) != 0) { if (addr1 < 0) { return rom[addr] | rom[addr1 + 0x4000] << 8; } if (addr1 < 0x4000) { cont1(0); cont1(3); ctime = cpu.time + 6; } return ram[addr - 0x4000] | ram[addr1] << 8; } switch (addr1 >>> 14) { case 0: cont1(3); ctime = cpu.time + 6; return rom[addr] | ram[0] << 8; case 1: cont1(0); case 2: return ram[addr - 0x4000] | ram[addr1] << 8; default: return ram[0xBFFF] | rom[0] << 8; } } public final void mem(int addr, int v) { int n = cpu.time - ctime; if (n > 0) { cont(n); } ctime = NOCONT; addr -= 0x4000; if (addr < 0x4000) { if (addr < 0) { return; } cont1(0); ctime = cpu.time + 3; if (ram[addr] == v) { return; } if (addr < 6912) { refresh_screen(); } } ram[addr] = v; } public final void mem16(int addr, int v) { int addr1 = addr - 0x3FFF; if ((addr1 & 0x3FFF) != 0) { int n = cpu.time - ctime; if (n > 0) { cont(n); } ctime = NOCONT; if (addr1 < 0) { return; } if (addr1 >= 0x4000) { ram[addr1 - 1] = v & 0xFF; ram[addr1] = v >>> 8; return; } } mem(addr, v & 0xFF); cpu.time += 3; mem((char) (addr + 1), v >>> 8); cpu.time -= 3; } protected byte ay_idx; private byte ula28; public void out(int port, int v) { cont_port(port); if ((port & 0x0001) == 0) { ula28 = (byte) v; int n = v & 7; if (n != border) { refresh_border(); border = (byte) n; } n = sp_volt[v >> 3 & 3]; if (n != speaker) { au_update(); speaker = n; } } if ((port & 0x8002) == 0x8000 && ay_enabled) { if ((port & 0x4000) != 0) { ay_idx = (byte) (v & 15); } else { au_update(); ay_write(ay_idx, v); } } } private int ear = 0x1BBA4; // EAR noise public int in(int port) { cont_port(port); if ((port & 0x00E0) == 0) { return kempston; } if ((port & 0xC002) == 0xC000 && ay_enabled) { if (ay_idx >= 14 && (ay_reg[7] >> ay_idx - 8 & 1) == 0) { return 0xFF; } return ay_reg[ay_idx]; } int v = 0xFF; if ((port & 0x0001) == 0) { for (int i = 0; i < 8; i++) { if ((port & 0x100 << i) == 0) { v &= keyboard[i]; } } int e = 0; // Apply tape noise only when SPK==0 and MIC==1. // thanks Jose Luis for bug report if ((ula28 & 0x18) == 8) { e = ear - 0x100000; if ((e & 0xFFF00000) == 0) { e = e << 2 | e >> 18; } ear = e; } v &= ula28 << 2 | e | 0xBF; } else if (cpu.time >= 0) { int t = cpu.time; int y = t / 224; t %= 224; if (y < 192 && t < 124 && (t & 4) == 0) { int x = t >> 1 & 1 | t >> 2; if ((t & 1) == 0) { x += y & 0x1800 | y << 2 & 0xE0 | y << 8 & 0x700; } else { x += 6144 | y << 2 & 0x3E0; } v = ram[x]; } } return v; } public int halt(int n, int ir) { return n; } /* contention */ // according to scratchpad.wikia.com/wiki/Contended_memory static final int NOCONT = 99999; int ctime; private final void cont1(int t) { t += cpu.time; if (t < 0 || t >= SCRENDT) { return; } if ((t & 7) >= 6) { return; } if (t % 224 < 126) { cpu.time += 6 - (t & 7); } } private final void cont(int n) { int s, k; int t = ctime; if (t + n <= 0) { return; } s = SCRENDT - t; if (s < 0) { return; } s %= 224; if (s > 126) { n -= s - 126; if (n <= 0) { return; } t = 6; k = 15; } else { k = s >>> 3; s &= 7; if (s == 7) { s--; if (--n == 0) { return; } } t = s; } n = n - 1 >> 1; if (k < n) { n = k; } cpu.time += t + 6 * n; } private void cont_port(int port) { int n = cpu.time - ctime; if (n > 0) { cont(n); } if ((port & 0xC000) != 0x4000) { if ((port & 0x0001) == 0) { cont1(1); } ctime = NOCONT; } else { ctime = cpu.time; cont(2 + ((port & 1) << 1)); ctime = cpu.time + 4; } } /* ImageProducer */ static final String pal1 = "\0\0\0\25\25\311\312\41\41\313\46\313\54\313\54\57\314\314\315\315\65\315\315\315" + "\0\0\0\33\33\373\374\51\51\374\57\374\67\375\67\73\376\376\377\377\101\377\377\377"; static final String pal2 = "\1\1\1\27\27\320\321\43\43\322\50\322\56\323\56\62\323\323\324\324\67\324\324\324" + "\1\1\1\34\34\377\377\53\53\377\61\377\71\377\71\76\377\377\377\377\104\377\377\377" + "\0\0\0\24\24\302\303\37\37\303\43\303\51\304\51\55\305\305\305\305\62\306\306\306" + "\0\0\0\31\31\364\367\46\46\370\54\370\64\372\64\70\373\373\375\375\76\376\376\376"; static byte[] palcolor(String p, int n, int m) { byte a[] = new byte[n]; for (int i = 0; i < n; i++) { a[i] = (byte) p.charAt(m); m += 3; } return a; } static final ColorModel cm1 = new IndexColorModel(8, 16, palcolor(pal1, 16, 0), palcolor(pal1, 16, 1), palcolor(pal1, 16, 2)); static final ColorModel cm2 = new IndexColorModel(8, 32, palcolor(pal2, 32, 0), palcolor(pal2, 32, 1), palcolor(pal2, 32, 2)); private ColorModel cm; private Vector consumers = new Vector(1); public synchronized void addConsumer(ImageConsumer ic) { try { update_buf = new byte[8 * W * scale * scale]; ic.setDimensions(width, height); consumers.addElement(ic); // XXX it may have been just removed ic.setHints(ic.RANDOMPIXELORDER | ic.SINGLEPASS); if (isConsumer(ic)) { ic.setColorModel(cm); } force_refresh(); } catch (Exception e) { if (isConsumer(ic)) { ic.imageComplete(ImageConsumer.IMAGEERROR); } } } public boolean isConsumer(ImageConsumer ic) { return consumers.contains(ic); } public synchronized void removeConsumer(ImageConsumer ic) { consumers.removeElement(ic); } public void startProduction(ImageConsumer ic) { addConsumer(ic); } public void requestTopDownLeftRightResend(ImageConsumer ic) { } private void abort_consumers() { for (;;) { int s = consumers.size(); if (s == 0) { break; } s--; ImageConsumer c = (ImageConsumer) consumers.elementAt(s); consumers.removeElementAt(s); c.imageComplete(ImageConsumer.IMAGEABORTED); } } /* screen */ private static final int SCRENDT = 191 * 224 + 126; private static final int Mh = 6; // margin private static final int Mv = 5; static final int W = 256 + 8 * Mh * 2; // 352 static final int H = 192 + 8 * Mv * 2; // 272 int width = W, height = H, scale = 0, want_scale = 0; public synchronized void scale(int m) { want_scale = m; if (m >= 0) { try { while (scale != m) { wait(); } } catch (InterruptedException e) { currentThread().interrupt(); } } } public int scale() { return scale; } private void force_refresh() { bordchg = (1L << Mv + 24 + Mv) - 1; for (int r = 0; r < 24; r++) { scrchg[r] = ~0; } } final int screen[] = new int[W / 8 * H]; // canonicalized scr. content int flash_count = 16; int flash = 0x8000; /* screen refresh */ private static final int REFRESH_END = 99999; final int scrchg[] = new int[24]; // where the picture changed private int refrs_t, refrs_a, refrs_b, refrs_s; private final void refresh_new() { refrs_t = refrs_b = 0; refrs_s = Mv * W + Mh; refrs_a = 0x1800; refrb_x = -Mh; refrb_y = -8 * Mv; refrb_t = BORDER_START; } private final void refresh_screen() { int ft = cpu.time; if (ft < refrs_t) { return; } final int flash = this.flash; int a = refrs_a, b = refrs_b; int t = refrs_t, s = refrs_s; do { int sch = 0; int v = ram[a] << 8 | ram[b++]; if (v >= 0x8000) { v ^= flash; } v = canonic[v]; if (v != screen[s]) { screen[s] = v; sch = 1; } v = ram[a + 1] << 8 | ram[b++]; if (v >= 0x8000) { v ^= flash; } v = canonic[v]; if (v != screen[++s]) { screen[s] = v; sch += 2; } if (sch != 0) { scrchg[a - 0x1800 >> 5] |= sch << (a & 31); } a += 2; t += 8; s++; if ((a & 31) != 0) { continue; } // next line t += 96; s += 2 * Mh; a -= 32; b += 256 - 32; if ((b & 0x700) != 0) { continue; } // next row a += 32; b += 32 - 0x800; if ((b & 0xE0) != 0) { continue; } // next segment b += 0x800 - 256; if (b >= 6144) { t = REFRESH_END; break; } } while (ft >= t); refrs_a = a; refrs_b = b; refrs_t = t; refrs_s = s; } /* border refresh */ private static final int BORDER_START = -224 * 8 * Mv - 4 * Mh + 4; private long bordchg; private int refrb_t, refrb_x, refrb_y; private final void refresh_border() { int ft = cpu.time; int t = refrb_t; // if(t == BORDER_END) XXX only if within screen if (ft < t) { return; } border_solid = -1; int c = canonic[border << 11]; int x = refrb_x; int y = refrb_y; int p = Mh + (Mh + 32 + Mh) * 8 * Mv + x + (Mh + 32 + Mh) * y; long m = 1L << (y >>> 3) + Mv; boolean chg = false; do { if (screen[p] != c) { screen[p] = c; chg = true; } p++; t += 4; if (++x == 0 && (char) y < 192) { p += (x = 32); t += 128; continue; } if (x < 32 + Mh) { continue; } x = -Mh; t += 224 - 4 * (Mh + 32 + Mh); if ((++y & 7) != 0) { continue; } if (y == 8 * (24 + Mv)) { t = REFRESH_END; break; } if (chg) { bordchg |= m; chg = false; } m <<= 1; } while (t <= ft); if (chg) { bordchg |= m; } refrb_x = x; refrb_y = y; refrb_t = t; } /* image */ private final void update_box(ImageConsumer ic, int y, int x, int w, byte buf[]) { int si = y * W + x; int p = 0; x <<= 3; y <<= 3; int h, s; if (scale == 1) { s = w * 8; for (int n = 0; n < 8; n++) { for (int k = 0; k < w; k++) { int m = screen[si++]; byte c0 = (byte) (m >>> 8 & 0xF); byte c1 = (byte) (m >>> 12); m &= 0xFF; do { buf[p++] = (m & 1) == 0 ? c0 : c1; } while ((m >>>= 1) != 0); } si += (W / 8) - w; } h = 8; } else { h = scale << 3; s = w * h; for (int n = 0; n < 8; n++) { for (int k = 0; k < w; k++) { int m = screen[si++]; byte c0 = (byte) (m >>> 8 & 0xF); byte c1 = (byte) (m >>> 12); m &= 0xFF; do { buf[p + s] = buf[p + s + 1] = (byte) ((buf[p] = buf[p + 1] = (m & 1) == 0 ? c0 : c1) + 16); p += 2; } while ((m >>>= 1) != 0); } p += s; si += (W / 8) - w; } x *= scale; y *= scale; } ic.setPixels(x, y, s, h, cm, buf, 0, s); } private byte[] update_buf; private void update_screen(ImageConsumer ic) { long bm = bordchg; boolean chg = false; byte buf[] = update_buf; for (int r = -Mv; r < 24 + Mv; r++, bm >>>= 1) { if ((bm & 1) != 0) { update_box(ic, r + Mv, 0, Mh + 32 + Mh, buf); chg = true; continue; } if ((char) r >= 24) { continue; } int v = scrchg[r]; if (v != 0) { int x = max_bit(v ^ v - 1); update_box(ic, Mv + r, Mh + x, max_bit(v) + 1 - x, buf); chg = true; } } if (chg) { ic.imageComplete(ImageConsumer.SINGLEFRAMEDONE); } } private void send_change() { int y1, y2, s; long vv; loop: for (int i = 0;;) { s = scrchg[i]; if (s != 0) { y1 = i; for (;;) { scrchg[y2 = i] = 0; do { if (++i == 24) { break loop; } } while (scrchg[i] == 0); s |= scrchg[i]; } } if (++i < 24) { continue; } vv = bordchg; if (vv == 0) { return; } bordchg = 0; y1 = max_bit(vv ^ vv - 1); y2 = max_bit(vv); int sc8 = scale * 8; qaop.new_pixels(0, y1 * sc8, (Mh + 32 + Mh) * sc8, (y2 - y1 + 1) * sc8); return; } int x, w; y1 += Mv; y2 += Mv; if ((vv = bordchg) != 0) { bordchg = 0; int v = max_bit(vv ^ vv - 1); if (v < y1) { y1 = v; } v = max_bit(vv); if (v > y2) { y2 = v; } x = 0; w = Mh + 32 + Mh; } else { x = max_bit(s ^ s - 1) + Mh; w = max_bit(s) + (Mh + 1) - x; } int sc8 = scale * 8; qaop.new_pixels(x * sc8, y1 * sc8, w * sc8, (y2 - y1 + 1) * sc8); } static final int max_bit(long vv) { int v = (int) (vv >>> 32); return (v != 0 ? 32 : 0) + max_bit(v != 0 ? v : (int) vv); } static final int max_bit(int v) { int b = 0; if ((char) v != v) { v >>>= (b = 16); } if (v > 0xFF) { v >>>= 8; b += 8; } if (v > 0xF) { v >>>= 4; b += 4; } return b + (-0x55B0 >>> 2 * v & 3); } static final int canonic[] = new int[32768]; static { // .bpppiii 76543210 -> bppp biii 01234567 for (int a = 0; a < 0x8000; a += 0x100) { int b = a >> 3 & 0x0800; int p = a >> 3 & 0x0700; int i = a & 0x0700; if (p != 0) { p |= b; } if (i != 0) { i |= b; } canonic[a] = p << 4 | 0xFF; canonic[a | 0xFF] = i << 4 | 0xFF; for (int m = 1; m < 255; m += 2) { if (i != p) { int xm = m >>> 4 | m << 4; xm = xm >>> 2 & 0x33 | xm << 2 & 0xCC; xm = xm >>> 1 & 0x55 | xm << 1 & 0xAA; canonic[a | m] = i << 4 | p | xm; canonic[a | m ^ 0xFF] = p << 4 | i | xm; } else { canonic[a | m] = canonic[a | m ^ 0xFF] = p << 4 | 0xFF; } } } } byte border = (byte) 7; // border color byte border_solid = -1; // nonnegative: solid border color /* audio */ static final int CHANNEL_VOLUME = 26000; static final int SPEAKER_VOLUME = 49000; boolean ay_enabled; void ay(boolean y) // enable { if (!y) { ay_mix = 0; } ay_enabled = y; } private int speaker; private static final int sp_volt[]; protected final byte ay_reg[] = new byte[16]; private int ay_aper, ay_bper, ay_cper, ay_nper, ay_eper; private int ay_acnt, ay_bcnt, ay_ccnt, ay_ncnt, ay_ecnt; private int ay_gen, ay_mix, ay_ech, ay_dis; private int ay_avol, ay_bvol, ay_cvol; private int ay_noise = 1; private int ay_ekeep; // >=0:hold, ==0:stop private boolean ay_div16; private int ay_eattack, ay_ealt, ay_estep; private static final int ay_volt[]; void ay_write(int n, int v) { switch (n) { case 0: ay_aper = ay_aper & 0xF00 | v; break; case 1: ay_aper = ay_aper & 0x0FF | (v &= 15) << 8; break; case 2: ay_bper = ay_bper & 0xF00 | v; break; case 3: ay_bper = ay_bper & 0x0FF | (v &= 15) << 8; break; case 4: ay_cper = ay_cper & 0xF00 | v; break; case 5: ay_cper = ay_cper & 0x0FF | (v &= 15) << 8; break; case 6: ay_nper = v &= 31; break; case 7: ay_mix = ~(v | ay_dis); break; case 8: case 9: case 10: int a = v &= 31, x = 011 << (n - 8); if (v == 0) { ay_dis |= x; ay_ech &= ~x; } else if (v < 16) { ay_dis &= (x = ~x); ay_ech &= x; } else { ay_dis &= ~x; ay_ech |= x; a = ay_estep ^ ay_eattack; } ay_mix = ~(ay_reg[7] | ay_dis); a = ay_volt[a]; switch (n) { case 8: ay_avol = a; break; case 9: ay_bvol = a; break; case 10: ay_cvol = a; break; } break; case 11: ay_eper = ay_eper & 0xFF00 | v; break; case 12: ay_eper = ay_eper & 0xFF | v << 8; break; case 13: ay_eshape(v &= 15); break; } ay_reg[n] = (byte) v; } private void ay_eshape(int v) { if (v < 8) { v = v < 4 ? 1 : 7; } ay_ekeep = (v & 1) != 0 ? 1 : -1; ay_ealt = (v + 1 & 2) != 0 ? 15 : 0; ay_eattack = (v & 4) != 0 ? 15 : 0; ay_estep = 15; ay_ecnt = -1; // ? ay_echanged(); } private void ay_echanged() { int v = ay_volt[ay_estep ^ ay_eattack]; int x = ay_ech; if ((x & 1) != 0) { ay_avol = v; } if ((x & 2) != 0) { ay_bvol = v; } if ((x & 4) != 0) { ay_cvol = v; } } private int ay_tick() { int x = 0; if ((--ay_acnt & ay_aper) == 0) { ay_acnt = -1; x ^= 1; } if ((--ay_bcnt & ay_bper) == 0) { ay_bcnt = -1; x ^= 2; } if ((--ay_ccnt & ay_cper) == 0) { ay_ccnt = -1; x ^= 4; } if (ay_div16 ^= true) { ay_gen ^= x; return x & ay_mix; } if ((--ay_ncnt & ay_nper) == 0) { ay_ncnt = -1; if ((ay_noise & 1) != 0) { x ^= 070; ay_noise ^= 0x28000; } ay_noise >>= 1; } if ((--ay_ecnt & ay_eper) == 0) { ay_ecnt = -1; if (ay_ekeep != 0) { if (ay_estep == 0) { ay_eattack ^= ay_ealt; ay_ekeep >>= 1; ay_estep = 16; } ay_estep--; if (ay_ech != 0) { ay_echanged(); x |= 0x100; } } } ay_gen ^= x; return x & ay_mix; } private int au_value() { int g = ay_mix & ay_gen; int v = speaker; if ((g & 011) == 0) { v += ay_avol; } if ((g & 022) == 0) { v += ay_bvol; } if ((g & 044) == 0) { v += ay_cvol; } return v; } private int au_time; private int au_val, au_dt; private void au_update() { int t = cpu.time; au_time += (t -= au_time); int dv = au_value() - au_val; if (dv != 0) { au_val += dv; audio.step(0, dv); } int dt = au_dt; for (; t >= dt; dt += 16) { if (ay_tick() == 0) { continue; } dv = au_value() - au_val; if (dv == 0) { continue; } au_val += dv; audio.step(dt, dv); t -= dt; dt = 0; } au_dt = dt - t; audio.step(t, 0); } void au_reset() { /* XXX */ speaker = 0; ay_mix = ay_gen = 0; ay_avol = ay_bvol = ay_cvol = 0; ay_ekeep = 0; ay_dis = 077; } static boolean muted = false; static int volume = 40; // % void mute(boolean v) { muted = v; setvol(); } int volume(int v) { if (v < 0) { v = 0; } else if (v > 100) { v = 100; } volume = v; setvol(); return v; } int volumeChg(int chg) { return volume(volume + chg); } static { sp_volt = new int[4]; ay_volt = new int[16]; setvol(); } static void setvol() { double a = muted ? 0 : volume / 100.; a *= a; sp_volt[2] = (int) (SPEAKER_VOLUME * a); sp_volt[3] = (int) (SPEAKER_VOLUME * 1.06 * a); a *= CHANNEL_VOLUME; int n; ay_volt[n = 15] = (int) a; do { ay_volt[--n] = (int) (a *= 0.7071); } while (n > 1); } /* keyboard & joystick */ public final int keyboard[] = new int[8]; public int kempston = 0; public final KeyEvent keys[] = new KeyEvent[8]; static final int arrowsDefault[] = {0143, 0124, 0134, 0144}; int arrows[] = arrowsDefault; void update_keyboard() { for (int i = 0; i < 8; i++) { keyboard[i] = 0xFF; } kempston = 0; int m[] = new int[]{-1, -1, -1, -1, -1}; int s = 0; synchronized (keys) { for (int i = 0; i < keys.length; i++) { if (keys[i] != null) { int k = key(keys[i]); if (k < 0) { continue; } // .......xxx row // ....xxx... column // ...x...... caps shift // ..x....... symbol shift // .x........ caps shift alone // x......... symbol shift alone s |= k; if (k < 01000) { pressed(k, m); } } } } if ((s & 0300) == 0) { s |= s >>> 3 & 0300; } if ((s & 0100) != 0) { pressed(000, m); } if ((s & 0200) != 0) { pressed(017, m); } } private final void pressed(int k, int m[]) { int a = k & 7, b = k >>> 3 & 7; int v = keyboard[a] & ~(1 << b); int n = m[b]; keyboard[a] = v; m[b] = a; if (n >= 0) { v |= keyboard[n]; } for (n = 0; n < 8; n++) { if ((keyboard[n] | v) != 0xFF) { keyboard[n] = v; } } } private int key(KeyEvent e) { int c = e.getKeyCode(); int a = e.getKeyChar(); int i = "[AQ10P\n ZSW29OL]XDE38IKMCFR47UJNVGT56YHB".indexOf((char) c); if (i >= 0) { simple: { int s = 0; if (c >= KeyEvent.VK_0 && c <= KeyEvent.VK_9) { if (c != (int) a) { break simple; } if (e.isAltDown()) { s = 0100; } } return i | s; } } if (a != '\0') { i = "\t\0\0!_\"\0\0:\0\0@);=\0\0\0\0#(\0+.?\0<$'\0-,/\0>%&\0^*".indexOf(a); if (i >= 0) { return i | 0200; } } switch (c) { case KeyEvent.VK_INSERT: case KeyEvent.VK_ESCAPE: return 0103; case KeyEvent.VK_KP_LEFT: case KeyEvent.VK_LEFT: i = 0; break; case KeyEvent.VK_KP_DOWN: case KeyEvent.VK_DOWN: i = 3; break; case KeyEvent.VK_KP_UP: case KeyEvent.VK_UP: i = 2; break; case KeyEvent.VK_KP_RIGHT: case KeyEvent.VK_RIGHT: i = 1; break; case KeyEvent.VK_BACK_SPACE: return 0104; case KeyEvent.VK_SHIFT: return 01000; case KeyEvent.VK_CONTROL: kempston |= 0x10; /* fall */ case KeyEvent.VK_ALT: return 02000; default: return -1; } kempston |= 1 << (i ^ 1); return e.isAltDown() ? arrowsDefault[i] : arrows[i]; } public void setArrows(String s) { arrows = new int[4]; for (int i = 0; i < 4; i++) { int c = -1; if (i < s.length()) { c = "Caq10pE_zsw29olSxde38ikmcfr47ujnvgt56yhb" .indexOf(s.charAt(i)); } if (c < 0) { c = arrowsDefault[i]; } arrows[i] = c; } } /* tape */ private boolean check_load() { int pc = cpu.pc(); if (cpu.ei() || pc < 0x56B || pc > 0x604) { return false; } int sp = cpu.sp(); if (pc >= 0x5E3) { pc = mem16(sp); sp = (char) (sp + 2); if (pc == 0x5E6) { pc = mem16(sp); sp = (char) (sp + 2); } } if (pc < 0x56B || pc > 0x58E) { return false; } cpu.sp(sp); cpu.ex_af(); if (tape_changed || tape_ready && tape.length <= tape_blk) { tape_changed = false; tape_blk = 0; } tape_pos = tape_blk; return true; } private boolean loading, stop_loading; private byte[] tape; private int tape_blk; private int tape_pos; private boolean tape_changed = false; private boolean tape_ready = false; public synchronized void stop_loading() { stop_loading = true; try { while (loading) { wait(); } } catch (InterruptedException e) { currentThread().interrupt(); } } public synchronized void tape(byte[] tape, boolean end) { if (tape == null) { tape_changed = true; } tape_ready = end; this.tape = tape; } private final boolean do_load(byte[] tape, boolean ready) { if (tape_changed || (keyboard[7] & 1) == 0) { cpu.f(0); return false; } int p = tape_pos; int ix = cpu.ix(); int de = cpu.de(); int h, l = cpu.hl(); h = l >> 8 & 0xFF; l &= 0xFF; int a = cpu.a(); int f = cpu.f(); int rf = -1; if (p == tape_blk) { p += 2; if (tape.length < p) { if (ready) { cpu.pc(cpu.pop()); cpu.f(cpu.FZ); } return !ready; } tape_blk = p + (tape[p - 2] & 0xFF | tape[p - 1] << 8 & 0xFF00); h = 0; } for (;;) { if (p == tape_blk) { rf = cpu.FZ; break; } if (p == tape.length) { if (ready) { rf = cpu.FZ; } break; } l = tape[p++] & 0xFF; h ^= l; if (de == 0) { a = h; rf = 0; if (a < 1) { rf = cpu.FC; } break; } if ((f & cpu.FZ) == 0) { a ^= l; if (a != 0) { rf = 0; break; } f |= cpu.FZ; continue; } if ((f & cpu.FC) != 0) { mem(ix, l); } else { a = mem(ix) ^ l; if (a != 0) { rf = 0; break; } } ix = (char) (ix + 1); de--; } cpu.ix(ix); cpu.de(de); cpu.hl(h << 8 | l); cpu.a(a); if (rf >= 0) { f = rf; cpu.pc(cpu.pop()); } cpu.f(f); tape_pos = p; return rf < 0; } /* LOAD "" */ public final void basic_exec(String cmd) { rom = rom48k; cpu.i(0x3F); int p = 16384; do { mem(p++, 0); } while (p < 22528); do { mem(p++, 070); } while (p < 23296); do { mem(p++, 0); } while (p < 65536); mem16(23732, --p); // P-RAMT p -= 0xA7; System.arraycopy(rom48k, 0x3E08, ram, p - 16384, 0xA8); mem16(23675, p--); // UDG mem(23608, 0x40); // RASP mem16(23730, p); // RAMTOP mem16(23606, 0x3C00); // CHARS mem(p--, 0x3E); cpu.sp(p); mem16(23613, p - 2); // ERR-SP cpu.iy(0x5C3A); cpu.im(1); cpu.ei(true); mem16(23631, 0x5CB6); // CHANS System.arraycopy(rom48k, 0x15AF, ram, 0x1CB6, 0x15); p = 0x5CB6 + 0x14; mem16(23639, p++); // DATAADD mem16(23635, p); // PROG mem16(23627, p); // VARS mem(p++, 0x80); mem16(23641, p); // E-LINE for (int i = 0; i < cmd.length(); i++) { mem(p++, cmd.charAt(i)); } mem16(p, 0x800D); p += 2; mem16(23649, p); // WORKSP mem16(23651, p); // STKBOT mem16(23653, p); // STKEND mem(23693, 070); mem(23695, 070); mem(23624, 070); mem16(23561, 0x0523); mem(23552, 0xFF); mem(23556, 0xFF); // KSTATE System.arraycopy(rom48k, 0x15C6, ram, 0x1C10, 14); mem16(23688, 0x1821); // S-POSN mem(23659, 2); // DF-SZ mem16(23656, 0x5C92); // MEM mem(23611, 0x0C); // FLAGS /* int r = (int)Math.floor(Math.random() * 128); cpu.r(r); mem(23672, r); // FRAMES */ cpu.pc(4788); au_reset(); } }
40,290
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Audio.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/applicationz80/Audio.java
/* * Audio.java * * Copyright 2007-2008 Jan Bobrowski <jb@wizard.ae.krakow.pl> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ package org.wandora.application.gui.previews.formats.applicationz80; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.SourceDataLine; class Audio { byte buf[] = new byte[4096]; int bufp; long div; int idiv, mul; int acct; int accv0, accv1, level; void open(int hz) { div = hz; acct = hz; idiv = (1 << 30) / hz; } void step(int t, int d) { t = acct - mul * t; if (t < 0) { int p = bufp, v = accv0; buf[p++] = (byte) v; buf[p++] = (byte) (v >> 8); v = accv1; accv1 = level; loop: for (;;) { if (p == buf.length) { p = flush(p); } if ((t += div) >= 0) { break; } buf[p++] = (byte) v; buf[p++] = (byte) (v >> 8); v = level; if (p == buf.length) { continue; } if ((t += div) >= 0) { break; } byte l = (byte) v; byte h = (byte) (v >> 8); for (;;) { buf[p++] = l; buf[p++] = h; if (p == buf.length) { continue loop; } if ((t += div) >= 0) { break loop; } } } accv0 = v; bufp = p; } // 0 <= t < div acct = t; int v = level + d; if ((short) v != v) { v = (short) (v >> 31 ^ 0x7FFF); d = v - level; } level = v; int x = idiv * t >> 22; int xx = x * x >> 9; accv0 += d * xx >> 8; xx = 128 - xx + x; accv1 += d * xx >> 8; } static final int FREQ = 22050; SourceDataLine line; Audio() { try { mul = FREQ; AudioFormat fmt = new AudioFormat(FREQ, 16, 1, true, false); System.out.println(fmt); SourceDataLine l = (SourceDataLine) AudioSystem.getLine( new DataLine.Info(SourceDataLine.class, fmt) ); l.open(fmt, 4096); l.start(); line = l; } catch (Exception e) { System.out.println(e); } catch (Error e) { // Java on some Linuces throws an error when sound // can't start. Thanks for Ricardo Almeida e.printStackTrace(); } } synchronized int flush(int p) { SourceDataLine l = line; if (l != null) { l.write(buf, 0, p); } return 0; } synchronized void close() { SourceDataLine l = line; if (l != null) { line = null; l.stop(); l.close(); } } }
3,377
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Z80.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/applicationz80/Z80.java
/* * Z80.java * * Copyright 2004-2010 Jan Bobrowski <jb@wizard.ae.krakow.pl> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ /* * Based on "The Undocumented Z80 Documented" by Sean Young */ package org.wandora.application.gui.previews.formats.applicationz80; public final class Z80 { interface Env { int m1(int pc, int ir); int mem(int addr); void mem(int addr, int v); int in(int port); void out(int port, int v); int mem16(int addr); void mem16(int addr, int v); int halt(int n, int ir); } private final Env env; Z80(Env env) { this.env = env; } private int PC, SP; private int A, B, C, D, E, HL; private int A_, B_, C_, D_, E_, HL_; private int IX, IY; private int IR, R; private int MP; /* MEMPTR, the hidden register emulated according to memptr_eng.txt */ private int Ff, Fr, Fa, Fb; private int Ff_, Fr_, Fa_, Fb_; /* lazy flag evaluation: state is stored in four variables: Ff, Fr, Fa, Fb Z: Fr==0 P: parity of Fr&0xFF V: (Fa.7^Fr.7) & (Fb.7^Fr.7) X: Fa.8 P/V: X ? P : V N: Fb.9 H: Fr.4 ^ Fa.4 ^ Fb.4 ^ Fb.12 FEDCBA98 76543210 Ff .......C S.5.3... Fr ........ V..H.... Fa .......X V..H.... Fb ...H..N. V..H.... */ static final int FC = 0x01; static final int FN = 0x02; static final int FP = 0x04; static final int F3 = 0x08; static final int FH = 0x10; static final int F5 = 0x20; static final int FZ = 0x40; static final int FS = 0x80; static final int F53 = 0x28; private int flags() { int f = Ff, a = Fa, b = Fb, r = Fr; f = f&(FS|F53) | f>>>8&FC; // S.5.3..C int u = b >> 8; if(r == 0) f |= FZ; // .Z...... int ra = r ^ a; f |= u & FN; // ......N. f |= (ra ^ b ^ u) & FH; // ...H.... if((a&~0xFF)==0) { a = ra & (b ^ r); b = 5; // .....V.. } else { a = 0x9669*FP; b = (r ^ r>>>4)&0xF; // .....P.. } return f | a>>>b & FP; } private void flags(int f) { Fr = ~f&FZ; Ff = (f |= f<<8); Fa = 0xFF & (Fb = f&~0x80 | (f&FP)<<5); } int a() {return A;} int f() {return flags();} int bc() {return B<<8|C;} int de() {return D<<8|E;} int hl() {return HL;} int ix() {return IX;} int iy() {return IY;} int pc() {return PC;} int sp() {return SP;} int af() {return A<<8 | flags();} int i() {return IR>>>8;} int r() {return R&0x7F | IR&0x80;} int im() {int v=IM; return v==0?v:v-1;} int iff() {return IFF;} boolean ei() {return (IFF&1)!=0;} void a(int v) {A = v;} void f(int v) {flags(v);} void bc(int v) {C=v&0xFF; B=v>>>8;} void de(int v) {E=v&0xFF; D=v>>>8;} void hl(int v) {HL = v;} void ix(int v) {IX = v;} void iy(int v) {IY = v;} void pc(int v) {PC = v;} void sp(int v) {SP = v;} void af(int v) {A = v>>>8; flags(v&0xFF);} void i(int v) {IR = IR&0xFF | v<<8;} void r(int v) {R=v; IR = IR&0xFF00 | v&0x80;} void im(int v) {IM = v+1 & 3;} void iff(int v) {IFF = v;} void ei(boolean v) {IFF = v ? 3 : 0;} int time; int time_limit; void exx() { int tmp; tmp = B_; B_ = B; B = tmp; tmp = C_; C_ = C; C = tmp; tmp = D_; D_ = D; D = tmp; tmp = E_; E_ = E; E = tmp; tmp = HL_; HL_ = HL; HL = tmp; } void ex_af() { int tmp = A_; A_ = A; A = tmp; tmp = Ff_; Ff_ = Ff; Ff = tmp; tmp = Fr_; Fr_ = Fr; Fr = tmp; tmp = Fa_; Fa_ = Fa; Fa = tmp; tmp = Fb_; Fb_ = Fb; Fb = tmp; } public void push(int v) { int sp; time++; env.mem((char)((sp=SP)-1), v>>>8); time += 3; env.mem(SP = (char)(sp-2), v&0xFF); time += 3; } int pop() { int sp, v = env.mem16(sp=SP); SP = (char)(sp+2); time += 6; return v; } private void add(int b) { A = Fr = (Ff = (Fa = A) + (Fb = b)) & 0xFF; } private void adc(int b) { A = Fr = (Ff = (Fa = A) + (Fb = b) + (Ff>>>8 & FC)) & 0xFF; } private void sub(int b) { Fb = ~b; A = Fr = (Ff = (Fa = A) - b) & 0xFF; } private void sbc(int b) { Fb = ~b; A = Fr = (Ff = (Fa = A) - b - (Ff>>>8 & FC)) & 0xFF; } private void cp(int b) { int r = (Fa = A) - b; Fb = ~b; Ff = r&~F53 | b&F53; Fr = r&0xFF; } private void and(int b) {Fa = ~(A = Ff = Fr = A & b); Fb = 0;} private void or(int b) {Fa = (A = Ff = Fr = A | b) | 0x100; Fb = 0;} private void xor(int b) {Fa = (A = Ff = Fr = A ^ b) | 0x100; Fb = 0;} private void cpl() { Ff = Ff&~F53 | (A ^= 0xFF)&F53; Fb |= ~0x80; Fa = Fa&~FH | ~Fr&FH; // set H, N } private int inc(int v) { Ff = Ff&0x100 | (Fr = v = (Fa=v)+(Fb=1) & 0xFF); return v; } private int dec(int v) { Ff = Ff&0x100 | (Fr = v = (Fa=v)+(Fb=-1) & 0xFF); return v; } private void bit(int n, int v) { int m = v & 1<<n; Ff = Ff&~0xFF | v&F53 | m; Fa = ~(Fr = m); Fb = 0; } private void f_szh0n0p(int r) { // SZ5H3PNC // xxx0xP0. Ff = Ff&~0xFF | (Fr = r); Fa = r|0x100; Fb = 0; } private void rot(int a) { Ff = Ff&0xD7 | a&0x128; Fb &= 0x80; Fa = Fa&~FH | Fr&FH; // reset H, N A = a&0xFF; } private int shifter(int o, int v) { switch(o&7) { case 0: v = v*0x101>>>7; break; case 1: v = v*0x80800000>>24; break; case 2: v = v<<1|Ff>>>8&1; break; case 3: v = (v*0x201|Ff&0x100)>>>1; break; case 4: v <<= 1; break; case 5: v = v>>>1|v&0x80|v<<8; break; case 6: v = v<<1|1; break; case 7: v = v*0x201>>>1; break; } Fa = 0x100 | (Fr = v = 0xFF&(Ff = v)); Fb = 0; return v; } private int add16(int a, int b) { int r = a + b; Ff = Ff & FS | r>>>8 & 0x128; Fa &= ~FH; Fb = Fb&0x80 | ((r ^ a ^ b)>>>8 ^ Fr) & FH; MP = a+1; time += 7; return (char)r; } private void adc_hl(int b) { int a,r; r = (a=HL) + b + (Ff>>>8 & FC); Ff = r>>>8; Fa = a>>>8; Fb = b>>>8; HL = r = (char)r; Fr = r>>>8 | r<<8; MP = a+1; time += 7; } private void sbc_hl(int b) { int a,r; r = (a=HL) - b - (Ff>>>8 & FC); Ff = r>>>8; Fa = a>>>8; Fb = ~(b>>>8); HL = r = (char)r; Fr = r>>>8 | r<<8; MP = a+1; time += 7; } private int getd(int xy) { int d = env.mem(PC); PC = (char)(PC+1); time += 8; return MP = (char)(xy + (byte)d); } private int imm8() { int v = env.mem(PC); PC = (char)(PC+1); time += 3; return v; } private int imm16() { int v = env.mem16(PC); PC = (char)(PC+2); time += 6; return v; } /* instructions */ // may be wrong. see http://scratchpad.wikia.com/wiki/Z80 private void scf_ccf(int x) { Fa &= ~FH; Fb = Fb&0x80 | (x>>>4 ^ Fr) & FH; Ff = 0x100 ^ x | Ff&FS | A&F53; } private void daa() { int h = (Fr ^ Fa ^ Fb ^ Fb>>8) & FH; int d = 0; if((A | Ff&0x100) > 0x99) d = 0x160; if((A&0xF | h) > 9) d += 6; Fa = A | 0x100; // parity if((Fb & 0x200)==0) A += (Fb = d); else { A -= d; Fb = ~d; } Ff = (Fr = A &= 0xFF) | d&0x100; } private void rrd() { int v = env.mem(HL) | A<<8; time += 7; f_szh0n0p(A = A&0xF0 | v&0x0F); env.mem(HL, v>>>4 & 0xFF); MP = HL+1; time += 3; } private void rld() { int v = env.mem(HL)<<4 | A&0x0F; time += 7; f_szh0n0p(A = A&0xF0 | v>>>8); env.mem(HL, v & 0xFF); MP = HL+1; time += 3; } private void ld_a_ir(int v) { Ff = Ff&~0xFF | (A = v); Fr = v==0 ? 0 : 1; Fa = Fb = IFF<<6 & 0x80; time++; } private void jp(boolean y) { int a = MP = imm16(); if(y) PC = a; } private void jr() { int pc = PC; byte d = (byte)env.mem(pc); time += 8; MP = PC = (char)(pc+d+1); } private void call(boolean y) { int a = MP = imm16(); if(y) {push(PC); PC = a;} } private void halt() { halted = true; int n = time_limit-time+3 >> 2; if(n>0) { n = env.halt(n, IR|R&0x7F); R+=n; time+=4*n; } } private void ldir(int i, boolean r) { int a,v; v = env.mem(a = HL); HL = (char)(a+i); time += 3; env.mem(a = de(), v); de((char)(a+i)); time += 5; if(Fr!=0) Fr = 1; // keep Z v += A; Ff = Ff&~F53 | v&F3 | v<<4&F5; bc(a = (char)(bc()-1)); v = 0; if(a!=0) { if(r) { time += 5; MP = (PC = (char)(PC-2)) + 1; } v = 0x80; } Fa = Fb = v; } private void cpir(int i, boolean r) { int a,b,v; v = A-(b = env.mem(a=HL)) & 0xFF; MP += i; HL = (char)(a+i); time += 8; Fr = v & 0x7F | v>>>7; Fb = ~(b | 0x80); Fa = A & 0x7F; bc(a = (char)(bc() - 1)); if(a!=0) { Fa |= 0x80; Fb |= 0x80; if(r && v!=0) { MP = (PC = (char)(PC-2)) + 1; time += 5; } } Ff = Ff&~0xFF | v&~F53; if(((v ^ b ^ A)&FH) != 0) v--; Ff |= v<<4&0x20 | v&8; } private void inir_otir(int op) // op: 101rd01o { int bc, hl, d, v; hl = (char)(HL + (d = (op&8)==0 ? 1 : -1)); bc = B<<8|C; time++; if((op&1)==0) { v = env.in(bc); time += 4; MP = bc+d; bc = (char)(bc-256); env.mem(HL, v); time += 3; d += bc; } else { v = env.mem(HL); time += 3; bc = (char)(bc-256); MP = bc+d; env.out(bc, v); time += 4; d = hl; } d = (d&0xFF) + v; HL = hl; B = (bc >>= 8); if(op>0xB0 && bc>0) { time += 5; PC = (char)(PC-2); } int x = d&7 ^ bc; Ff = bc | (d &= 0x100); Fa = (Fr = bc) ^ 0x80; x = 0x4B3480 >> ((x^x>>>4)&15); Fb = (x^bc) & 0x80 | d>>>4 | (v & 0x80)<<2; } /* Note: EI isn't prefix here - interrupt will be acknowledged */ void execute() { if(halted) { halt(); return; } do { int v, c = env.m1(PC, IR|R++&0x7F); PC = (char)(PC+1); time += 4; switch(c) { // -------------- >8 main // case 0x00: break; case 0x08: ex_af(); break; case 0x10: {time++; v=PC; byte d=(byte)env.mem(v++); time+=3; if((B=B-1&0xFF)!=0) {time+=5; MP=v+=d;} PC=(char)v;} break; case 0x18: MP=PC=(char)(PC+1+(byte)env.mem(PC)); time+=8; break; case 0x09: HL=add16(HL,B<<8|C); break; case 0x19: HL=add16(HL,D<<8|E); break; case 0x29: HL=add16(HL,HL); break; case 0x39: HL=add16(HL,SP); break; case 0x01: v=imm16(); B=v>>>8; C=v&0xFF; break; case 0x11: v=imm16(); D=v>>>8; E=v&0xFF; break; case 0x21: HL=imm16(); break; case 0x23: HL=(char)(HL+1); time+=2; break; case 0x2B: HL=(char)(HL-1); time+=2; break; case 0x31: SP=imm16(); break; case 0x33: SP=(char)(SP+1); time+=2; break; case 0x3B: SP=(char)(SP-1); time+=2; break; case 0x03: if(++C==256) {B=B+1&0xFF;C=0;} time+=2; break; case 0x13: if(++E==256) {D=D+1&0xFF;E=0;} time+=2; break; case 0x0B: if(--C<0) B=B-1&(C=0xFF); time+=2; break; case 0x1B: if(--E<0) D=D-1&(E=0xFF); time+=2; break; case 0x02: MP=(v=B<<8|C)+1&0xFF|A<<8; env.mem(v,A); time+=3; break; case 0x0A: MP=(v=B<<8|C)+1; A=env.mem(v); time+=3; break; case 0x12: MP=(v=D<<8|E)+1&0xFF|A<<8; env.mem(v,A); time+=3; break; case 0x1A: MP=(v=D<<8|E)+1; A=env.mem(v); time+=3; break; case 0x22: MP=(v=imm16())+1; env.mem16(v,HL); time+=6; break; case 0x2A: MP=(v=imm16())+1; HL=env.mem16(v); time+=6; break; case 0x32: MP=(v=imm16())+1&0xFF|A<<8; env.mem(v,A); time+=3; break; case 0x3A: MP=(v=imm16())+1; A=env.mem(v); time+=3; break; case 0x04: B=inc(B); break; case 0x05: B=dec(B); break; case 0x06: B=imm8(); break; case 0x0C: C=inc(C); break; case 0x0D: C=dec(C); break; case 0x0E: C=imm8(); break; case 0x14: D=inc(D); break; case 0x15: D=dec(D); break; case 0x16: D=imm8(); break; case 0x1C: E=inc(E); break; case 0x1D: E=dec(E); break; case 0x1E: E=imm8(); break; case 0x24: HL=HL&0xFF|inc(HL>>>8)<<8; break; case 0x25: HL=HL&0xFF|dec(HL>>>8)<<8; break; case 0x26: HL=HL&0xFF|imm8()<<8; break; case 0x2C: HL=HL&0xFF00|inc(HL&0xFF); break; case 0x2D: HL=HL&0xFF00|dec(HL&0xFF); break; case 0x2E: HL=HL&0xFF00|imm8(); break; case 0x34: v=inc(env.mem(HL)); time+=4; env.mem(HL,v); time+=3; break; case 0x35: v=dec(env.mem(HL)); time+=4; env.mem(HL,v); time+=3; break; case 0x36: env.mem(HL,imm8()); time+=3; break; case 0x3C: A=inc(A); break; case 0x3D: A=dec(A); break; case 0x3E: A=imm8(); break; case 0x20: if(Fr!=0) jr(); else imm8(); break; case 0x28: if(Fr==0) jr(); else imm8(); break; case 0x30: if((Ff&0x100)==0) jr(); else imm8(); break; case 0x38: if((Ff&0x100)!=0) jr(); else imm8(); break; case 0x07: rot(A*0x101>>>7); break; case 0x0F: rot(A*0x80800000>>24); break; case 0x17: rot(A<<1|Ff>>>8&1); break; case 0x1F: rot((A*0x201|Ff&0x100)>>>1); break; case 0x27: daa(); break; case 0x2F: cpl(); break; case 0x37: scf_ccf(0); break; case 0x3F: scf_ccf(Ff&0x100); break; // case 0x40: break; case 0x41: B=C; break; case 0x42: B=D; break; case 0x43: B=E; break; case 0x44: B=HL>>>8; break; case 0x45: B=HL&0xFF; break; case 0x46: B=env.mem(HL); time+=3; break; case 0x47: B=A; break; case 0x48: C=B; break; // case 0x49: break; case 0x4A: C=D; break; case 0x4B: C=E; break; case 0x4C: C=HL>>>8; break; case 0x4D: C=HL&0xFF; break; case 0x4E: C=env.mem(HL); time+=3; break; case 0x4F: C=A; break; case 0x50: D=B; break; case 0x51: D=C; break; // case 0x52: break; case 0x53: D=E; break; case 0x54: D=HL>>>8; break; case 0x55: D=HL&0xFF; break; case 0x56: D=env.mem(HL); time+=3; break; case 0x57: D=A; break; case 0x58: E=B; break; case 0x59: E=C; break; case 0x5A: E=D; break; // case 0x5B: break; case 0x5C: E=HL>>>8; break; case 0x5D: E=HL&0xFF; break; case 0x5E: E=env.mem(HL); time+=3; break; case 0x5F: E=A; break; case 0x60: HL=HL&0xFF|B<<8; break; case 0x61: HL=HL&0xFF|C<<8; break; case 0x62: HL=HL&0xFF|D<<8; break; case 0x63: HL=HL&0xFF|E<<8; break; // case 0x64: break; case 0x65: HL=HL&0xFF|(HL&0xFF)<<8; break; case 0x66: HL=HL&0xFF|env.mem(HL)<<8; time+=3; break; case 0x67: HL=HL&0xFF|A<<8; break; case 0x68: HL=HL&0xFF00|B; break; case 0x69: HL=HL&0xFF00|C; break; case 0x6A: HL=HL&0xFF00|D; break; case 0x6B: HL=HL&0xFF00|E; break; case 0x6C: HL=HL&0xFF00|HL>>>8; break; // case 0x6D: break; case 0x6E: HL=HL&0xFF00|env.mem(HL); time+=3; break; case 0x6F: HL=HL&0xFF00|A; break; case 0x70: env.mem(HL,B); time+=3; break; case 0x71: env.mem(HL,C); time+=3; break; case 0x72: env.mem(HL,D); time+=3; break; case 0x73: env.mem(HL,E); time+=3; break; case 0x74: env.mem(HL,HL>>>8); time+=3; break; case 0x75: env.mem(HL,HL&0xFF); time+=3; break; case 0x76: halt(); break; case 0x77: env.mem(HL,A); time+=3; break; case 0x78: A=B; break; case 0x79: A=C; break; case 0x7A: A=D; break; case 0x7B: A=E; break; case 0x7C: A=HL>>>8; break; case 0x7D: A=HL&0xFF; break; case 0x7E: A=env.mem(HL); time+=3; break; // case 0x7F: break; case 0xA7: Fa=~(Ff=Fr=A); Fb=0; break; case 0xAF: A=Ff=Fr=Fb=0; Fa=0x100; break; case 0x80: add(B); break; case 0x81: add(C); break; case 0x82: add(D); break; case 0x83: add(E); break; case 0x84: add(HL>>>8); break; case 0x85: add(HL&0xFF); break; case 0x86: add(env.mem(HL)); time+=3; break; case 0x87: add(A); break; case 0x88: adc(B); break; case 0x89: adc(C); break; case 0x8A: adc(D); break; case 0x8B: adc(E); break; case 0x8C: adc(HL>>>8); break; case 0x8D: adc(HL&0xFF); break; case 0x8E: adc(env.mem(HL)); time+=3; break; case 0x8F: adc(A); break; case 0x90: sub(B); break; case 0x91: sub(C); break; case 0x92: sub(D); break; case 0x93: sub(E); break; case 0x94: sub(HL>>>8); break; case 0x95: sub(HL&0xFF); break; case 0x96: sub(env.mem(HL)); time+=3; break; case 0x97: sub(A); break; case 0x98: sbc(B); break; case 0x99: sbc(C); break; case 0x9A: sbc(D); break; case 0x9B: sbc(E); break; case 0x9C: sbc(HL>>>8); break; case 0x9D: sbc(HL&0xFF); break; case 0x9E: sbc(env.mem(HL)); time+=3; break; case 0x9F: sbc(A); break; case 0xA0: and(B); break; case 0xA1: and(C); break; case 0xA2: and(D); break; case 0xA3: and(E); break; case 0xA4: and(HL>>>8); break; case 0xA5: and(HL&0xFF); break; case 0xA6: and(env.mem(HL)); time+=3; break; case 0xA8: xor(B); break; case 0xA9: xor(C); break; case 0xAA: xor(D); break; case 0xAB: xor(E); break; case 0xAC: xor(HL>>>8); break; case 0xAD: xor(HL&0xFF); break; case 0xAE: xor(env.mem(HL)); time+=3; break; case 0xB0: or(B); break; case 0xB1: or(C); break; case 0xB2: or(D); break; case 0xB3: or(E); break; case 0xB4: or(HL>>>8); break; case 0xB5: or(HL&0xFF); break; case 0xB6: or(env.mem(HL)); time+=3; break; case 0xB7: or(A); break; case 0xB8: cp(B); break; case 0xB9: cp(C); break; case 0xBA: cp(D); break; case 0xBB: cp(E); break; case 0xBC: cp(HL>>>8); break; case 0xBD: cp(HL&0xFF); break; case 0xBE: cp(env.mem(HL)); time+=3; break; case 0xBF: cp(A); break; case 0xDD: case 0xFD: group_xy(c); break; case 0xCB: group_cb(); break; case 0xED: group_ed(); break; case 0xC0: time++; if(Fr!=0) MP=PC=pop(); break; case 0xC2: jp(Fr!=0); break; case 0xC4: call(Fr!=0); break; case 0xC8: time++; if(Fr==0) MP=PC=pop(); break; case 0xCA: jp(Fr==0); break; case 0xCC: call(Fr==0); break; case 0xD0: time++; if((Ff&0x100)==0) MP=PC=pop(); break; case 0xD2: jp((Ff&0x100)==0); break; case 0xD4: call((Ff&0x100)==0); break; case 0xD8: time++; if((Ff&0x100)!=0) MP=PC=pop(); break; case 0xDA: jp((Ff&0x100)!=0); break; case 0xDC: call((Ff&0x100)!=0); break; case 0xE0: time++; if((flags()&FP)==0) MP=PC=pop(); break; case 0xE2: jp((flags()&FP)==0); break; case 0xE4: call((flags()&FP)==0); break; case 0xE8: time++; if((flags()&FP)!=0) MP=PC=pop(); break; case 0xEA: jp((flags()&FP)!=0); break; case 0xEC: call((flags()&FP)!=0); break; case 0xF0: time++; if((Ff&FS)==0) MP=PC=pop(); break; case 0xF2: jp((Ff&FS)==0); break; case 0xF4: call((Ff&FS)==0); break; case 0xF8: time++; if((Ff&FS)!=0) MP=PC=pop(); break; case 0xFA: jp((Ff&FS)!=0); break; case 0xFC: call((Ff&FS)!=0); break; case 0xC1: v=pop(); B=v>>>8; C=v&0xFF; break; case 0xC5: push(B<<8|C); break; case 0xD1: v=pop(); D=v>>>8; E=v&0xFF; break; case 0xD5: push(D<<8|E); break; case 0xE1: HL=pop(); break; case 0xE5: push(HL); break; case 0xF1: af(pop()); break; case 0xF5: push(A<<8|flags()); break; case 0xC3: MP=PC=imm16(); break; case 0xC6: add(imm8()); break; case 0xCE: adc(imm8()); break; case 0xD6: sub(imm8()); break; case 0xDE: sbc(imm8()); break; case 0xE6: and(imm8()); break; case 0xEE: xor(imm8()); break; case 0xF6: or(imm8()); break; case 0xFE: cp(imm8()); break; case 0xC9: MP=PC=pop(); break; case 0xCD: v=imm16(); push(PC); MP=PC=v; break; case 0xD3: env.out(v=imm8()|A<<8,A); MP=v+1&0xFF|v&0xFF00; time+=4; break; case 0xDB: MP=(v=imm8()|A<<8)+1; A=env.in(v); time+=4; break; case 0xD9: exx(); break; case 0xE3: v=pop(); push(HL); MP=HL=v; time+=2; break; case 0xE9: PC=HL; break; case 0xEB: v=HL; HL=D<<8|E; D=v>>>8; E=v&0xFF; break; case 0xF3: IFF=0; break; case 0xFB: IFF=3; break; case 0xF9: SP=HL; time+=2; break; case 0xC7: case 0xCF: case 0xD7: case 0xDF: case 0xE7: case 0xEF: case 0xF7: case 0xFF: push(PC); PC=c-199; break; // -------------- >8 } } while(time_limit - time > 0); } private void group_xy(int c0) { for(;;) { int xy = c0==0xDD ? IX : IY; int v, c = env.m1(PC, IR|R++&0x7F); PC = (char)(PC+1); time += 4; switch(c) { // -------------- >8 xy // case 0x00: break; case 0x08: ex_af(); break; case 0x10: time++; if((B=B-1&0xFF)!=0) jr(); else imm8(); break; case 0x18: jr(); break; case 0x09: xy=add16(xy,B<<8|C); break; case 0x19: xy=add16(xy,D<<8|E); break; case 0x29: xy=add16(xy,xy); break; case 0x39: xy=add16(xy,SP); break; case 0x01: bc(imm16()); break; case 0x03: bc((char)(bc()+1)); time+=2; break; case 0x0B: bc((char)(bc()-1)); time+=2; break; case 0x11: de(imm16()); break; case 0x13: de((char)(de()+1)); time+=2; break; case 0x1B: de((char)(de()-1)); time+=2; break; case 0x21: xy=imm16(); break; case 0x23: xy=(char)(xy+1); time+=2; break; case 0x2B: xy=(char)(xy-1); time+=2; break; case 0x31: SP=imm16(); break; case 0x33: SP=(char)(SP+1); time+=2; break; case 0x3B: SP=(char)(SP-1); time+=2; break; case 0x02: MP=(v=bc())+1&0xFF|A<<8; env.mem(v,A); time+=3; break; case 0x0A: MP=(v=bc())+1; A=env.mem(v); time+=3; break; case 0x12: MP=(v=de())+1&0xFF|A<<8; env.mem(v,A); time+=3; break; case 0x1A: MP=(v=de())+1; A=env.mem(v); time+=3; break; case 0x22: MP=(v=imm16())+1; env.mem16(v,xy); time+=6; break; case 0x2A: MP=(v=imm16())+1; xy=env.mem16(v); time+=6; break; case 0x32: MP=(v=imm16())+1&0xFF|A<<8; env.mem(v,A); time+=3; break; case 0x3A: MP=(v=imm16())+1; A=env.mem(v); time+=3; break; case 0x04: B=inc(B); break; case 0x05: B=dec(B); break; case 0x06: B=imm8(); break; case 0x0C: C=inc(C); break; case 0x0D: C=dec(C); break; case 0x0E: C=imm8(); break; case 0x14: D=inc(D); break; case 0x15: D=dec(D); break; case 0x16: D=imm8(); break; case 0x1C: E=inc(E); break; case 0x1D: E=dec(E); break; case 0x1E: E=imm8(); break; case 0x24: xy=xy&0xFF|inc(xy>>>8)<<8; break; case 0x25: xy=xy&0xFF|dec(xy>>>8)<<8; break; case 0x26: xy=xy&0xFF|imm8()<<8; break; case 0x2C: xy=xy&0xFF00|inc(xy&0xFF); break; case 0x2D: xy=xy&0xFF00|dec(xy&0xFF); break; case 0x2E: xy=xy&0xFF00|imm8(); break; case 0x34: {int a; v=inc(env.mem(a=getd(xy))); time+=4; env.mem(a,v); time+=3;} break; case 0x35: {int a; v=dec(env.mem(a=getd(xy))); time+=4; env.mem(a,v); time+=3;} break; case 0x36: {int a=(char)(xy+(byte)env.mem(PC)); time+=3; v=env.mem((char)(PC+1)); time+=5; env.mem(a,v); PC=(char)(PC+2); time+=3;} break; case 0x3C: A=inc(A); break; case 0x3D: A=dec(A); break; case 0x3E: A=imm8(); break; case 0x20: if(Fr!=0) jr(); else imm8(); break; case 0x28: if(Fr==0) jr(); else imm8(); break; case 0x30: if((Ff&0x100)==0) jr(); else imm8(); break; case 0x38: if((Ff&0x100)!=0) jr(); else imm8(); break; case 0x07: rot(A*0x101>>>7); break; case 0x0F: rot(A*0x80800000>>24); break; case 0x17: rot(A<<1|Ff>>>8&1); break; case 0x1F: rot((A*0x201|Ff&0x100)>>>1); break; case 0x27: daa(); break; case 0x2F: cpl(); break; case 0x37: scf_ccf(0); break; case 0x3F: scf_ccf(Ff&0x100); break; // case 0x40: break; case 0x41: B=C; break; case 0x42: B=D; break; case 0x43: B=E; break; case 0x44: B=xy>>>8; break; case 0x45: B=xy&0xFF; break; case 0x46: B=env.mem(getd(xy)); time+=3; break; case 0x47: B=A; break; case 0x48: C=B; break; // case 0x49: break; case 0x4A: C=D; break; case 0x4B: C=E; break; case 0x4C: C=xy>>>8; break; case 0x4D: C=xy&0xFF; break; case 0x4E: C=env.mem(getd(xy)); time+=3; break; case 0x4F: C=A; break; case 0x50: D=B; break; case 0x51: D=C; break; // case 0x52: break; case 0x53: D=E; break; case 0x54: D=xy>>>8; break; case 0x55: D=xy&0xFF; break; case 0x56: D=env.mem(getd(xy)); time+=3; break; case 0x57: D=A; break; case 0x58: E=B; break; case 0x59: E=C; break; case 0x5A: E=D; break; // case 0x5B: break; case 0x5C: E=xy>>>8; break; case 0x5D: E=xy&0xFF; break; case 0x5E: E=env.mem(getd(xy)); time+=3; break; case 0x5F: E=A; break; case 0x60: xy=xy&0xFF|B<<8; break; case 0x61: xy=xy&0xFF|C<<8; break; case 0x62: xy=xy&0xFF|D<<8; break; case 0x63: xy=xy&0xFF|E<<8; break; // case 0x64: break; case 0x65: xy=xy&0xFF|(xy&0xFF)<<8; break; case 0x66: HL=HL&0xFF|env.mem(getd(xy))<<8; time+=3; break; case 0x67: xy=xy&0xFF|A<<8; break; case 0x68: xy=xy&0xFF00|B; break; case 0x69: xy=xy&0xFF00|C; break; case 0x6A: xy=xy&0xFF00|D; break; case 0x6B: xy=xy&0xFF00|E; break; case 0x6C: xy=xy&0xFF00|xy>>>8; break; // case 0x6D: break; case 0x6E: HL=HL&0xFF00|env.mem(getd(xy)); time+=3; break; case 0x6F: xy=xy&0xFF00|A; break; case 0x70: env.mem(getd(xy),B); time+=3; break; case 0x71: env.mem(getd(xy),C); time+=3; break; case 0x72: env.mem(getd(xy),D); time+=3; break; case 0x73: env.mem(getd(xy),E); time+=3; break; case 0x74: env.mem(getd(xy),HL>>>8); time+=3; break; case 0x75: env.mem(getd(xy),HL&0xFF); time+=3; break; case 0x76: halt(); break; case 0x77: env.mem(getd(xy),A); time+=3; break; case 0x78: A=B; break; case 0x79: A=C; break; case 0x7A: A=D; break; case 0x7B: A=E; break; case 0x7C: A=xy>>>8; break; case 0x7D: A=xy&0xFF; break; case 0x7E: A=env.mem(getd(xy)); time+=3; break; // case 0x7F: break; case 0x80: add(B); break; case 0x81: add(C); break; case 0x82: add(D); break; case 0x83: add(E); break; case 0x84: add(xy>>>8); break; case 0x85: add(xy&0xFF); break; case 0x86: add(env.mem(getd(xy))); time+=3; break; case 0x87: add(A); break; case 0x88: adc(B); break; case 0x89: adc(C); break; case 0x8A: adc(D); break; case 0x8B: adc(E); break; case 0x8C: adc(xy>>>8); break; case 0x8D: adc(xy&0xFF); break; case 0x8E: adc(env.mem(getd(xy))); time+=3; break; case 0x8F: adc(A); break; case 0x90: sub(B); break; case 0x91: sub(C); break; case 0x92: sub(D); break; case 0x93: sub(E); break; case 0x94: sub(xy>>>8); break; case 0x95: sub(xy&0xFF); break; case 0x96: sub(env.mem(getd(xy))); time+=3; break; case 0x97: sub(A); break; case 0x98: sbc(B); break; case 0x99: sbc(C); break; case 0x9A: sbc(D); break; case 0x9B: sbc(E); break; case 0x9C: sbc(xy>>>8); break; case 0x9D: sbc(xy&0xFF); break; case 0x9E: sbc(env.mem(getd(xy))); time+=3; break; case 0x9F: sbc(A); break; case 0xA0: and(B); break; case 0xA1: and(C); break; case 0xA2: and(D); break; case 0xA3: and(E); break; case 0xA4: and(xy>>>8); break; case 0xA5: and(xy&0xFF); break; case 0xA6: and(env.mem(getd(xy))); time+=3; break; case 0xA7: and(A); break; case 0xA8: xor(B); break; case 0xA9: xor(C); break; case 0xAA: xor(D); break; case 0xAB: xor(E); break; case 0xAC: xor(xy>>>8); break; case 0xAD: xor(xy&0xFF); break; case 0xAE: xor(env.mem(getd(xy))); time+=3; break; case 0xAF: xor(A); break; case 0xB0: or(B); break; case 0xB1: or(C); break; case 0xB2: or(D); break; case 0xB3: or(E); break; case 0xB4: or(xy>>>8); break; case 0xB5: or(xy&0xFF); break; case 0xB6: or(env.mem(getd(xy))); time+=3; break; case 0xB7: or(A); break; case 0xB8: cp(B); break; case 0xB9: cp(C); break; case 0xBA: cp(D); break; case 0xBB: cp(E); break; case 0xBC: cp(xy>>>8); break; case 0xBD: cp(xy&0xFF); break; case 0xBE: cp(env.mem(getd(xy))); time+=3; break; case 0xBF: cp(A); break; case 0xDD: case 0xFD: c0=c; continue; case 0xCB: group_xy_cb(xy); break; case 0xED: group_ed(); break; case 0xC0: time++; if(Fr!=0) MP=PC=pop(); break; case 0xC2: jp(Fr!=0); break; case 0xC4: call(Fr!=0); break; case 0xC8: time++; if(Fr==0) MP=PC=pop(); break; case 0xCA: jp(Fr==0); break; case 0xCC: call(Fr==0); break; case 0xD0: time++; if((Ff&0x100)==0) MP=PC=pop(); break; case 0xD2: jp((Ff&0x100)==0); break; case 0xD4: call((Ff&0x100)==0); break; case 0xD8: time++; if((Ff&0x100)!=0) MP=PC=pop(); break; case 0xDA: jp((Ff&0x100)!=0); break; case 0xDC: call((Ff&0x100)!=0); break; case 0xE0: time++; if((flags()&FP)==0) MP=PC=pop(); break; case 0xE2: jp((flags()&FP)==0); break; case 0xE4: call((flags()&FP)==0); break; case 0xE8: time++; if((flags()&FP)!=0) MP=PC=pop(); break; case 0xEA: jp((flags()&FP)!=0); break; case 0xEC: call((flags()&FP)!=0); break; case 0xF0: time++; if((Ff&FS)==0) MP=PC=pop(); break; case 0xF2: jp((Ff&FS)==0); break; case 0xF4: call((Ff&FS)==0); break; case 0xF8: time++; if((Ff&FS)!=0) MP=PC=pop(); break; case 0xFA: jp((Ff&FS)!=0); break; case 0xFC: call((Ff&FS)!=0); break; case 0xC1: bc(pop()); break; case 0xC5: push(bc()); break; case 0xD1: de(pop()); break; case 0xD5: push(de()); break; case 0xE1: xy=pop(); break; case 0xE5: push(xy); break; case 0xF1: af(pop()); break; case 0xF5: push(A<<8|flags()); break; case 0xC3: MP=PC=imm16(); break; case 0xC6: add(imm8()); break; case 0xCE: adc(imm8()); break; case 0xD6: sub(imm8()); break; case 0xDE: sbc(imm8()); break; case 0xE6: and(imm8()); break; case 0xEE: xor(imm8()); break; case 0xF6: or(imm8()); break; case 0xFE: cp(imm8()); break; case 0xC9: MP=PC=pop(); break; case 0xCD: call(true); break; case 0xD3: env.out(v=imm8()|A<<8,A); MP=v+1&0xFF|v&0xFF00; time+=4; break; case 0xDB: MP=(v=imm8()|A<<8)+1; A=env.in(v); time+=4; break; case 0xD9: exx(); break; case 0xE3: v=pop(); push(xy); MP=xy=v; time+=2; break; case 0xE9: PC=xy; break; case 0xEB: v=HL; HL=de(); de(v); break; case 0xF3: IFF=0; break; case 0xFB: IFF=3; break; case 0xF9: SP=xy; time+=2; break; case 0xC7: case 0xCF: case 0xD7: case 0xDF: case 0xE7: case 0xEF: case 0xF7: case 0xFF: push(PC); PC=c-199; break; // -------------- >8 } if(c0==0xDD) IX = xy; else IY = xy; break; } } private void group_ed() { int v, c = env.m1(PC, IR|R++&0x7F); PC = (char)(PC+1); time += 4; switch(c) { // -------------- >8 ed case 0x47: i(A); time++; break; case 0x4F: r(A); time++; break; case 0x57: ld_a_ir(IR>>>8); break; case 0x5F: ld_a_ir(r()); break; case 0x67: rrd(); break; case 0x6F: rld(); break; case 0x40: f_szh0n0p(B=env.in(B<<8|C)); time+=4; break; case 0x48: f_szh0n0p(C=env.in(B<<8|C)); time+=4; break; case 0x50: f_szh0n0p(D=env.in(B<<8|C)); time+=4; break; case 0x58: f_szh0n0p(E=env.in(B<<8|C)); time+=4; break; case 0x60: f_szh0n0p(v=env.in(B<<8|C)); HL=HL&0xFF|v<<8; time+=4; break; case 0x68: f_szh0n0p(v=env.in(B<<8|C)); HL=HL&0xFF00|v; time+=4; break; case 0x70: f_szh0n0p(env.in(B<<8|C)); time+=4; break; case 0x78: MP=(v=B<<8|C)+1; f_szh0n0p(A=env.in(v)); time+=4; break; case 0x41: env.out(B<<8|C,B); time+=4; break; case 0x49: env.out(B<<8|C,C); time+=4; break; case 0x51: env.out(B<<8|C,D); time+=4; break; case 0x59: env.out(B<<8|C,E); time+=4; break; case 0x61: env.out(B<<8|C,HL>>>8); time+=4; break; case 0x69: env.out(B<<8|C,HL&0xFF); time+=4; break; case 0x71: env.out(B<<8|C,0); time+=4; break; case 0x79: MP=(v=B<<8|C)+1; env.out(v,A); time+=4; break; case 0x42: sbc_hl(B<<8|C); break; case 0x4A: adc_hl(B<<8|C); break; case 0x43: MP=(v=imm16())+1; env.mem16(v,B<<8|C); time+=6; break; case 0x4B: MP=(v=imm16())+1; v=env.mem16(v); B=v>>>8; C=v&0xFF; time+=6; break; case 0x52: sbc_hl(D<<8|E); break; case 0x5A: adc_hl(D<<8|E); break; case 0x53: MP=(v=imm16())+1; env.mem16(v,D<<8|E); time+=6; break; case 0x5B: MP=(v=imm16())+1; v=env.mem16(v); D=v>>>8; E=v&0xFF; time+=6; break; case 0x62: sbc_hl(HL); break; case 0x6A: adc_hl(HL); break; case 0x63: MP=(v=imm16())+1; env.mem16(v,HL); time+=6; break; case 0x6B: MP=(v=imm16())+1; HL=env.mem16(v); time+=6; break; case 0x72: sbc_hl(SP); break; case 0x7A: adc_hl(SP); break; case 0x73: MP=(v=imm16())+1; env.mem16(v,SP); time+=6; break; case 0x7B: MP=(v=imm16())+1; SP=env.mem16(v); time+=6; break; case 0x44: case 0x4C: case 0x54: case 0x5C: case 0x64: case 0x6C: case 0x74: case 0x7C: v=A; A=0; sub(v); break; case 0x45: case 0x4D: case 0x55: case 0x5D: case 0x65: case 0x6D: case 0x75: case 0x7D: IFF|=IFF>>1; MP=PC=pop(); break; case 0x46: case 0x4E: case 0x56: case 0x5E: case 0x66: case 0x6E: case 0x76: case 0x7E: IM = c>>3&3; break; case 0xA0: ldir(1,false); break; case 0xA8: ldir(-1,false); break; case 0xB0: ldir(1,true); break; case 0xB8: ldir(-1,true); break; case 0xA1: cpir(1,false); break; case 0xA9: cpir(-1,false); break; case 0xB1: cpir(1,true); break; case 0xB9: cpir(-1,true); break; case 0xA2: case 0xA3: case 0xAA: case 0xAB: case 0xB2: case 0xB3: case 0xBA: case 0xBB: inir_otir(c); break; // -------------- >8 default: System.out.println(PC+": Not emulated ED/"+c); } } private void group_cb() { int v, c = env.m1(PC, IR|R++&0x7F); PC = (char)(PC+1); time += 4; int o = c>>>3 & 7; switch(c & 0xC7) { // -------------- >8 cb case 0x00: B=shifter(o,B); break; case 0x01: C=shifter(o,C); break; case 0x02: D=shifter(o,D); break; case 0x03: E=shifter(o,E); break; case 0x04: HL=HL&0xFF|shifter(o,HL>>>8)<<8; break; case 0x05: HL=HL&0xFF00|shifter(o,HL&0xFF); break; case 0x06: v=shifter(o,env.mem(HL)); time+=4; env.mem(HL,v); time+=3; break; case 0x07: A=shifter(o,A); break; case 0x40: bit(o,B); break; case 0x41: bit(o,C); break; case 0x42: bit(o,D); break; case 0x43: bit(o,E); break; case 0x44: bit(o,HL>>>8); break; case 0x45: bit(o,HL&0xFF); break; case 0x46: bit(o,env.mem(HL)); Ff=Ff&~F53|MP>>>8&F53; time+=4; break; case 0x47: bit(o,A); break; case 0x80: B=B&~(1<<o); break; case 0x81: C=C&~(1<<o); break; case 0x82: D=D&~(1<<o); break; case 0x83: E=E&~(1<<o); break; case 0x84: HL&=~(0x100<<o); break; case 0x85: HL&=~(1<<o); break; case 0x86: v=env.mem(HL)&~(1<<o); time+=4; env.mem(HL,v); time+=3; break; case 0x87: A=A&~(1<<o); break; case 0xC0: B=B|1<<o; break; case 0xC1: C=C|1<<o; break; case 0xC2: D=D|1<<o; break; case 0xC3: E=E|1<<o; break; case 0xC4: HL|=0x100<<o; break; case 0xC5: HL|=1<<o; break; case 0xC6: v=env.mem(HL)|1<<o; time+=4; env.mem(HL,v); time+=3; break; case 0xC7: A=A|1<<o; break; // -------------- >8 } } private void group_xy_cb(int xy) { int pc = PC; int a = MP = (char)(xy + (byte)env.mem(pc)); time += 3; int c = env.mem((char)(pc+1)); PC = (char)(pc+2); time += 5; int v = env.mem(a); time += 4; int o = c>>>3 & 7; switch(c&0xC0) { case 0x00: v = shifter(o, v); break; case 0x40: bit(o, v); Ff=Ff&~F53 | a>>8&F53; return; case 0x80: v &= ~(1<<o); break; case 0xC0: v |= 1<<o; break; } env.mem(a, v); time += 3; switch(c&0x07) { case 0: B = v; break; case 1: C = v; break; case 2: D = v; break; case 3: E = v; break; case 4: HL = HL&0x00FF | v<<8; break; case 5: HL = HL&0xFF00 | v; break; case 7: A = v; break; } } /* interrupts */ private int IFF, IM; private boolean halted; boolean interrupt(int bus) { if((IFF&1)==0) return false; IFF = 0; halted = false; time += 6; push(PC); switch(IM) { case 0: // IM 0 case 1: // IM 0 if((bus|0x38)==0xFF) {PC=bus-199; break;} /* not emulated */ case 2: // IM 1 PC = 0x38; break; case 3: // IM 2 PC = env.mem16(IR&0xFF00 | bus); time += 6; break; } MP=PC; return true; } void nmi() { IFF &= 2; halted = false; push(PC); time += 4; PC = 0x66; } void reset() { halted = false; PC = IFF = IM = 0; af(SP = 0xFFFF); } }
33,609
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Qaop.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/previews/formats/applicationz80/Qaop.java
/* * Qaop.java * * Copyright 2004-2009 Jan Bobrowski <jb@wizard.ae.krakow.pl> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ package org.wandora.application.gui.previews.formats.applicationz80; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import javax.imageio.ImageIO; import javax.swing.JPanel; import org.wandora.application.gui.UIBox; public class Qaop extends JPanel implements Runnable, KeyListener, FocusListener, ComponentListener, MouseListener { protected Spectrum spectrum; protected Map params; private int screenScaler = 1; public Qaop(Map params) { super(); this.params = params; this.setBackground(new Color(0x222222)); this.addMouseListener(this); init(); } public synchronized void init() { showStatus(getAppletInfo(), true); String a = param("mask"); if (a != null) { mask = getImage(a); } /* a = param("boxbgcolor"); if(a != null) { Color bg = Color.getColor(a); if(bg != null) this.setBackground(bg); } */ Spectrum s = new Spectrum(this); spectrum = s; queue = new LinkedList(); addKeyListener(this); addFocusListener(this); a = param("rom"); if (a == null) { InputStream in = resource("/org/wandora/application/gui/previews/formats/applicationz80/roms/spectrum48.rom"); if (in != null) { int l = tomem(s.rom48k, 0, 16384, in); if(l != 0) { showStatus("Can't read spectrum.rom (2)", true); } } else { showStatus("Can't read spectrum.rom", true); } } else { Loader.add(this, a, Loader.ROM); } a = param("if1rom"); if (a != null) { Loader.add(this, a, Loader.IF1ROM); } a = param("load"); if (a != null) { Loader.add(this, a, 0); } a = param("tape"); if (a != null) { Loader.add(this, a, Loader.TAP); } a = param("arrows"); if (a != null) { s.setArrows(a); } if (param("ay", false)) { s.ay(true); } if (param("muted", false)) { s.mute(true); } s.volume((int) param("volume", 40)); s.start(); th = new Thread(this, "Qaop"); // th.setPriority(Thread.NORM_PRIORITY-1); th.start(); if (param("focus", true)) { addComponentListener(this); } } public synchronized void destroy() { th.interrupt(); spectrum.scale(-1); // signal to quit spectrum.interrupt(); // this seems to be not enough try { th.join(); spectrum.join(); } catch (Exception x) { } } public String getAppletInfo() { return "Qaop - ZX Spectrum emulator by Jan Bobrowski"; } static final String info[][] = { {"rom", "filename", "alternative ROM image"}, {"if1rom", "filename", "enable Interface1; use this ROM"}, {"tape", "filename", "tape file"}, {"load", "filename", "snapshot or tape to load"}, {"focus", "yes/no", "grab focus on start"}, {"arrows", "keys", "define arrow keys"}, {"ay", "yes/no", "with AY"}, {"muted", "yes/no", "muted to start"}, {"volume", "number", "volume 0..100"}, {"mask", "filename", "overlay"} }; public String[][] getParameterInfo() { return info; } @Override public Dimension getPreferredSize() { return new Dimension(spectrum.width, spectrum.height); } /* javascript interface */ public void reset() { synchronized (queue) { Loader.clear(queue, 0); } spectrum.reset(); } public void load(String name) { Loader.add(this, name, 0); } public void tape(String name) { Loader.add(this, name, Loader.TAP); } public String save() { try { spectrum.pause(022); String s = Loader.get_snap(this); spectrum.pause(020); return s; } catch (InterruptedException x) { intr(); return null; } } public boolean pause(boolean v) { try { spectrum.pause(v ? 044 : 040); } catch (InterruptedException x) { intr(); } return v; } public void mask(String name) { mask = name != null ? getImage(name) : null; repaint(); } public void mute(boolean y) { spectrum.mute(y); } public int volume() { return spectrum.volumeChg(0); } public int volume(int v) { return spectrum.volume(v); } public void setScreenSize(int scaler) { screenScaler = scaler; this.setSize(352*scaler, 272*scaler); } private int state; // bit 0:paused, 1:loading, 2:muted public int state() { int v = 0; try { Spectrum s = spectrum; v = s.pause(0) >>> 2 & 1; if (s.muted) { v |= 4; } } catch (InterruptedException x) { intr(); } return state | v; } public void focus() { requestFocus(); } public static void intr() { Thread.currentThread().interrupt(); } /* graphics */ private Image img; // speccy private Dimension size; private int posx, posy; private Image buf_image; private Image mask; private void resized(Dimension d) { size = d; int s1 = d.width / 256; int s2 = d.height / 192; int s = Math.min(s1, s2); // Although the s can be bigger than 2, the spectrum doesn't support s > 2. if (spectrum.scale() != s) { img = null; spectrum.scale(s); img = createImage(spectrum); dl_text_current = null; } posx = (d.width - spectrum.width) / 2; posy = (d.height - spectrum.height) / 2; buf_image = null; } @Override public void paint(Graphics g) { update(g); } @Override public synchronized void update(Graphics g) { Dimension d = getSize(); if (!d.equals(size)) { resized(d); } String t = dl_text; if (mask == null && t == null) { g.drawImage(img, posx, posy, null); return; } int sw = spectrum.width; int sh = spectrum.height; if (dl_text_current == null ? t != null : !dl_text_current.equals(t)) { dl_img = dl_mk_image(t, sw); } if (buf_image == null) { buf_image = createImage(sw, sh); } Graphics g2 = buf_image.getGraphics(); Rectangle r = g.getClipBounds(); int x = posx, y = posy; g2.setClip(r.x - x, r.y - y, r.width, r.height); g2.drawImage(img, 0, 0, null); if (mask != null) { g2.drawImage(mask, 0, 0, sw, sh, this); } if (dl_img != null) { g2.translate(0, sh / 2); dl_paint(g2, sw); } g2.dispose(); g.drawImage(buf_image, x, y, null); } protected void new_pixels(int x, int y, int w, int h) { repaint(posx + x, posy + y, w, h); } Color pb_color = Color.black; protected Image dl_img; protected String dl_text_current; private void dl_paint(Graphics g, int w) { g.drawImage(dl_img, 0, -dl_img.getHeight(null), null); String e = dl_msg; if (e != null) { g.setFont(new Font("SansSerif", 0, 12)); FontMetrics m = g.getFontMetrics(); int ex = (w - m.stringWidth(e)) / 2; int ey = m.getAscent(); g.setColor(new Color(0xFF8800)); g.drawString(e, ex, ey); return; } double perc = dl_length > 0 ? (double) dl_loaded / dl_length : 0; if (perc > 1) { perc = 1; } int pb_w = 68; int x = (w - pb_w) / 2, y = 5; int s = (int) (pb_w * perc); g.setColor(new Color(0x7FBBBBBB, true)); g.fillRect(x, y, pb_w, 3); g.setColor(new Color(0x1A646464, true)); g.fillRect(x, y - 1, pb_w, 1); g.setColor(pb_color); g.fillRect(x, y, s, 3); g.setColor(new Color(0x66FFFFFF, true)); g.fillRect(x, y, s, 1); } private Image dl_mk_image(String t, int w) { Image i = null; if (t != null) { i = new BufferedImage(w, 20, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) i.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setFont(new Font("SansSerif", Font.BOLD, 14)); g.setColor(new Color(0x66EEEECC, true)); FontMetrics m = g.getFontMetrics(); g.translate((w - m.stringWidth(t)) / 2, m.getAscent()); int dx = 1, dy = 0; do { g.drawString(t, +dx, +dy); g.drawString(t, -dx, -dy); dx -= dy; dy = 1; } while (dx >= -1); g.setColor(new Color(0x111111)); g.drawString(t, 0, 0); g.dispose(); } dl_text_current = t; return i; } /* KeyListener, FocusListener */ @Override public void keyTyped(KeyEvent e) { e.consume(); } @Override public void keyPressed(KeyEvent e) { int c = e.getKeyCode(); boolean m; int v; if (c == e.VK_DELETE && e.isControlDown()) { spectrum.reset(); return; } else if (c == e.VK_F11) { spectrum.mute(m = !spectrum.muted); v = spectrum.volumeChg(0); } else if (c == e.VK_PAGE_UP || c == e.VK_PAGE_DOWN) { m = spectrum.muted; v = spectrum.volumeChg(c == e.VK_PAGE_UP ? +5 : -5); } else if (c == e.VK_PAUSE) { try { spectrum.pause(4); } catch (InterruptedException x) { intr(); } return; } else { keyEvent(e); return; } String s = "Volume: "; for (int i = 0; i < v; i += 4) { s += "|"; } s += " " + v + "%"; if (m) { s += " (muted)"; } showStatus(s, false); e.consume(); } @Override public void keyReleased(KeyEvent e) { keyEvent(e); e.consume(); } void keyEvent(KeyEvent e) { KeyEvent[] k = spectrum.keys; int c = e.getKeyCode(); int j = -1; synchronized (k) { for (int i = 0; i < k.length; i++) { if (k[i] == null) { j = i; continue; } int d = k[i].getKeyCode(); if (d == c) { j = i; break; } } if (j >= 0) { k[j] = e.getID() == KeyEvent.KEY_PRESSED ? e : null; } } } @Override public void focusGained(FocusEvent e) { showStatus(getAppletInfo(), false); } @Override public void focusLost(FocusEvent e) { KeyEvent[] k = spectrum.keys; synchronized (k) { for (int i = 0; i < k.length; i++) { k[i] = null; } } } /* ComponentListener */ @Override public void componentResized(ComponentEvent e) { } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentHidden(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { removeComponentListener(this); requestFocus(); } /* parameters */ String param(String n) { return params != null ? (String) params.get(n) : null; } boolean param(String name, boolean dflt) { String p = param(name); if (p == null || p.length() == 0) { return dflt; } p = p.toUpperCase(); char c = p.charAt(0); return c != 'N' && c != 'F' && c != '0' && !p.equals("OFF"); } double param(String name, double dflt) { try { String p = param(name); return Double.parseDouble(p); } catch (Exception x) { return dflt; } } /* resource */ private InputStream resource(String name) { //return ClassLoader.getResourceAsStream(name); return Qaop.class.getResourceAsStream(name); } protected static int tomem(int[] m, int p, int l, InputStream in) { do { try { int v = in.read(); if (v < 0) { break; } m[p++] = v; } catch (IOException ignored) { break; } } while (--l > 0); return l; } public void showStatus(String s, boolean log) { if (log) { System.out.println(s); } try { // TODO // super.showStatus(s); } catch (Exception e) { } } public Image getImage(URL u) { try { return ImageIO.read(u); } catch(Exception e) { return null; } } /* download */ protected java.util.List queue; private Thread th; @Override public void run() { Loader l; for (;;) { try { synchronized (queue) { if (queue.isEmpty()) { state &= ~2; spectrum.pause(010); queue.wait(); continue; } state |= 2; l = (Loader) queue.remove(0); } l.exec(); } catch (InterruptedException x) { break; } catch (Exception x) { x.printStackTrace(); } } } protected int dl_length, dl_loaded; protected String dl_text, dl_msg; private Image getImage(String name) { return UIBox.getImage(name); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { this.requestFocus(); } @Override public void mouseEntered(MouseEvent e) { this.requestFocus(); } @Override public void mouseExited(MouseEvent e) { } } // ------------------------------------------------------------------ LOADER --- class Loader extends Thread { Qaop qaop; String file; int kind; boolean gz, zip; DataInputStream in; static final int ROM = 0x4001, IF1ROM = 0x2011, CART = 0x4021, TAP = 2, SNA = 3, Z80 = 4; static final String MIME = "application/x.zx."; protected static Loader add(Qaop a, String f, int k) { Loader l = new Loader(); l.qaop = a; l.file = f; l.kind = k; List q = a.queue; synchronized (q) { clear(q, k); q.add(l); q.notify(); } return l; } protected static void clear(List q, int k) { int i = q.size(); while (--i >= 0) { Loader l = (Loader) q.get(i); if (l.kind == k) { q.remove(i); } } } void exec() throws InterruptedException { Qaop q = qaop; try { do_exec(); } catch (InterruptedException x) { throw x; } catch (InterruptedIOException x) { throw new InterruptedException(); } catch (Exception x) { System.out.println(x); if (q.dl_msg == null) { String m; if (x instanceof FileNotFoundException) { m = "Not found"; } else if (x instanceof EOFException) { m = "File truncated"; } else { m = x.getMessage(); if (m == null) { m = "Error"; } } q.dl_msg = m; } if (q.dl_text == null) { q.dl_text = ""; } q.repaint(100); try { Thread.sleep(1500); } catch (InterruptedException xx) { throw xx; } } finally { try { interrupt(); join(); } catch (Exception x) { } q.dl_text = q.dl_msg = null; q.repaint(200); } } private void do_exec() throws Exception { InputStream s; String n = file; int k = kind; if (n == null) { qaop.spectrum.tape(null, false); return; } qaop.pb_color = Color.gray; file = null; // now ZIP entry if (n.startsWith("data:")) { s = data_url(n); } else { raw_in = start_download(n); pipe = new PipedOutputStream(); // setPriority(Thread.NORM_PRIORITY-1); s = new PipedInputStream(pipe); start(); } if (zip) { s = unzip(s); } else if (gz) { s = new GZIPInputStream(s); } pb_color: { int c; switch (kind & 0xF) { case SNA & 0xF: case Z80 & 0xF: c = 0x0077FF; break; case TAP & 0xF: c = 0x00CC22; break; case ROM & 0xF: c = 0xFF1100; break; default: break pb_color; } qaop.pb_color = new Color(c); } in = new DataInputStream(s); Spectrum spec = qaop.spectrum; spec.pause(011); switch (kind) { case 0: throw new IOException("Unknown format"); case TAP: spec.tape(null, false); if (k != TAP) { spec.basic_exec("\u00EF\"\""); // LOAD "" } spec.pause(010); load_tape(); break; case SNA: load_sna(); break; case Z80: load_z80(); break; case CART: qaop.spectrum.reset(); default: load_rom(kind); } } private InputStream start_download(String f) throws IOException { Qaop a = qaop; a.dl_length = a.dl_loaded = 0; a.dl_text = f; URL u = new URL(f); f = u.getFile(); int i = f.lastIndexOf('/'); if (i >= 0) { f = f.substring(i + 1); } a.dl_text = f; a.repaint(200); URLConnection c = u.openConnection(); try { c.setConnectTimeout(15000); c.setReadTimeout(10000); } catch (Error e) { } if (c instanceof java.net.HttpURLConnection) { int x = ((java.net.HttpURLConnection) c).getResponseCode(); if (x < 200 || x > 299) { throw new FileNotFoundException(); } } check_type(c.getContentType(), f); String s = c.getContentEncoding(); if (s != null && s.contains("gzip")) { gz = true; } int l = c.getContentLength(); qaop.dl_length = l > 0 ? l : 1 << 16; file = u.getRef(); return c.getInputStream(); } private InputStream unzip(InputStream s) throws IOException { ZipInputStream zip = new ZipInputStream(s); int k; for (;;) { ZipEntry e = zip.getNextEntry(); if (e == null) { throw new IOException("No suitable file found"); } if (e.isDirectory()) { continue; } String n = e.getName(); k = get_type(n.toLowerCase()); if (file == null) { if (k == 0) { continue; } if (kind == 0) { break; } if (((kind ^ k) & 0xF) == 0) { break; } } else if (n.equals(file)) { break; } } if (kind == 0) { kind = k; } return zip; } private InputStream data_url(String s) throws IOException { // data:application/x.zx.tap;base64,EwAAAGJvcm int i = s.indexOf(',', 5); if (i < 0) { throw new IOException(); } String h = s.substring(5, i); s = s.substring(i + 1); boolean b64; if (b64 = h.endsWith(";base64")) { h = h.substring(0, i - 5 - 7); } check_type(h, null); s = URLDecoder.decode(s, "iso-8859-1"); byte[] b = b64 ? base64decode(s) : s.getBytes("iso-8859-1"); return new ByteArrayInputStream(b); } static byte[] base64decode(String s) throws IOException { int l = s.length(); l = l / 4 * 3; if (s.endsWith("=")) { l -= s.endsWith("==") ? 2 : 1; } byte[] o = new byte[l]; int ii = 0, oi = 0, b = 0, k = 2; for (;;) { // replaced -> + int n = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 /" .indexOf(s.charAt(ii++)); if (n < 0) { throw new IOException("data: '" + s.charAt(ii - 1) + "' " + (ii - 1)); } if (k <= 0) { o[oi] = (byte) (b | n >> -k); if (++oi == l) { break; } k += 8; b = 0; } b |= n << k; k -= 6; } return o; } private void check_type(String mime, String name) { int tk = 0, nk = 0; if (mime != null) { int i = mime.indexOf(';'); if (i > 0) { mime = mime.substring(0, i).trim(); } mime = mime.toLowerCase(); if (zip = mime.equals("application/zip")) { return; } if (mime.startsWith("application/x-spectrum-")) { tk = get_type("." + mime.substring(23)); } else if (mime.startsWith(MIME)) { tk = get_type(mime); } } if (name != null) { name = name.toLowerCase(); if (zip = name.endsWith(".zip")) { return; } nk = get_type(name); } if (kind == 0) { kind = tk != 0 ? tk : nk; } } private int get_type(String f) { int k; if (gz = f.endsWith(".gz")) { f = f.substring(0, f.length() - 3); } k = 0; if (f.endsWith(".sna")) { k = SNA; } else if (f.endsWith(".z80") || f.endsWith(".slt")) { k = Z80; } else if (f.endsWith(".tap")) { k = TAP; } else if (f.endsWith(".rom")) { k = CART; } return k; } PipedOutputStream pipe; InputStream raw_in; public void run() { // yield(); byte buf[] = new byte[4096]; try { while (!interrupted()) { int n = raw_in.read(buf, 0, buf.length); if (n <= 0) { break; } qaop.dl_loaded += n; qaop.repaint(100); try { pipe.write(buf, 0, n); } catch (InterruptedIOException x) { break; } } } catch (Exception x) { x.printStackTrace(); } finally { try { pipe.close(); } catch (Exception x) { } } } /* file handlers */ private void load_rom(int kind) throws Exception { int m[] = new int[0x8000]; if (qaop.tomem(m, 0, kind & 0xF000, in) != 0) { throw new Exception("Rom image truncated"); } Spectrum spec = qaop.spectrum; switch (kind) { case IF1ROM: System.arraycopy(m, 0, m, 0x4000, 0x4000); spec.if1rom = m; break; case ROM: spec.rom48k = m; default: spec.rom = m; } } private void load_tape() { byte data[] = null; int pos = 0; for (;;) { try { byte buf[] = new byte[pos + 512]; int n = in.read(buf, pos, 512); if (n < 512) { if (n <= 0) { break; } byte buf2[] = new byte[pos + n]; System.arraycopy(buf, pos, buf2, pos, n); buf = buf2; } if (data != null) { System.arraycopy(data, 0, buf, 0, pos); } data = buf; pos += n; qaop.spectrum.tape(data, false); Thread.yield(); } catch (IOException e) { break; } } if (data != null) { qaop.spectrum.tape(data, true); } } private int get8() throws IOException { return in.readUnsignedByte(); } private int get16() throws IOException { int b = in.readUnsignedByte(); return b | in.readUnsignedByte() << 8; } private void poke_stream(int pos, int len) throws IOException { Spectrum s = qaop.spectrum; do { s.mem(pos++, get8()); } while (--len > 0); } private void get_regs(Z80 z, String s) throws IOException { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '\'') { z.exx(); z.ex_af(); continue; } int v = c < 'a' ? get16() : get8(); switch (c) { case 'a': z.a(v); break; case 'f': z.f(v); break; case 'B': z.bc(v); break; case 'D': z.de(v); break; case 'H': z.hl(v); break; case 'X': z.ix(v); break; case 'Y': z.iy(v); break; case 'S': z.sp(v); break; case 'i': z.i(v); break; case 'r': z.r(v); break; } } } private void load_sna() throws IOException { Spectrum spectrum = qaop.spectrum; Z80 cpu = spectrum.cpu; spectrum.reset(); get_regs(cpu, "iHDBfa'HDBYX"); cpu.ei(get8() != 0); get_regs(cpu, "rfaS"); cpu.im(get8()); spectrum.border = (byte) (get8() & 7); poke_stream(16384, 49152); try { cpu.pc(get16()); System.out.println("Is it 128K .SNA?"); } catch (EOFException e) { int sp = cpu.sp(); cpu.pc(spectrum.mem16(sp)); cpu.sp((char) (sp + 2)); spectrum.mem16(sp, 0); } } private void load_z80() throws IOException { Spectrum spectrum = qaop.spectrum; Z80 cpu = spectrum.cpu; spectrum.reset(); get_regs(cpu, "afBH"); int pc = get16(); cpu.pc(pc); get_regs(cpu, "Si"); int f1 = get16(); cpu.r(f1 & 0x7F | f1 >> 1 & 0x80); if ((f1 >>>= 8) == 0xFF) { f1 = 1; } spectrum.border = (byte) (f1 >> 1 & 7); get_regs(cpu, "D'BDHaf'YX"); int v = get8(); cpu.iff((v == 0 ? 0 : 1) | (get8() == 0 ? 0 : 2)); cpu.im(get8()); if (pc != 0) { if ((f1 & 0x20) != 0) { uncompress_z80(16384, 49152); } else { poke_stream(16384, 49152); } return; } int l = get16(); cpu.pc(get16()); int hm = get8(); if (hm > 1) { System.out.println("Unsupported model: #" + hm); } get8(); if (get8() == 0xFF && spectrum.if1rom != null) { spectrum.rom = spectrum.if1rom; } int ay_idx = 0, ay_reg[] = null; if ((get8() & 4) != 0 && spectrum.ay_enabled && l >= 23) { ay_idx = get8() & 15; ay_reg = new int[16]; for (int i = 0; i < 16; i++) { ay_reg[i] = get8(); } l -= 17; } in.skip(l - 6); for (;;) { try { l = get16(); } catch (IOException x) { break; } int a; switch (get8()) { case 8: a = 0x4000; break; case 4: a = 0x8000; break; case 5: a = 0xC000; break; default: in.skip(l); continue; } if (l == 0xFFFF) { poke_stream(a, 16384); } else { uncompress_z80(a, 16384); } } if (ay_reg != null) { for (int i = 0; i < 16; i++) { spectrum.ay_write(i, ay_reg[i]); } spectrum.ay_idx = (byte) ay_idx; } } private int uncompress_z80(int pos, int count) throws IOException { Spectrum spectrum = qaop.spectrum; int end = pos + count; int n = 0; loop: do { int v = get8(); n++; if (v != 0xED) { spectrum.mem(pos++, v); continue; } v = get8(); n++; if (v != 0xED) { spectrum.mem16(pos, v << 8 | 0xED); pos += 2; continue; } int l = get8(); v = get8(); n += 2; while (l > 0) { spectrum.mem(pos++, v); if (pos >= end) { break loop; } l--; } } while (pos < end); return n; } /* make snapshot */ protected static String get_snap(Qaop q) { byte[] b; try { b = save_z80(q); return to_data("z80", b); } catch (Exception x) { x.printStackTrace(); return null; } } private static String to_data(String t, byte[] b) { return "data:" + MIME + t + ";base64," + base64encode(b); //return "data:" + MIME + t + ";base64," + Base64.encodeBytes(b); } private static String base64encode(byte[] b) { int l = b.length; if (l == 0) { return ""; } StringBuilder s = new StringBuilder(); int a = b[0], k = 2; for (int i = 1;;) { s.append( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" .charAt(a >>> k & 63) ); if ((k -= 6) >= 0) { continue; } if (i < l) { a <<= 8; k += 8; a += b[i++] & 0xFF; continue; } if (k == -6) { break; } a <<= 5; k += 5; if (i++ == l) { continue; } s.append('='); if (k == 0) { s.append('='); } break; } return s.toString(); } private static OutputStream put16(OutputStream o, int v) throws IOException { o.write(v); o.write(v >> 8); return o; } private static byte[] save_z80(Qaop q) throws IOException { Spectrum s = q.spectrum; Z80 cpu = s.cpu; ByteArrayOutputStream o = new ByteArrayOutputStream(); o.write(cpu.a()); o.write(cpu.f()); put16(o, cpu.bc()); put16(o, cpu.hl()); put16(o, 0); // v2 put16(o, cpu.sp()); o.write(cpu.i()); int n = cpu.r(); put16(o, n | n << 1 & 256 | s.border << 9); put16(o, cpu.de()); cpu.exx(); cpu.ex_af(); put16(o, cpu.bc()); put16(o, cpu.de()); put16(o, cpu.hl()); o.write(cpu.a()); o.write(cpu.f()); cpu.exx(); cpu.ex_af(); put16(o, cpu.iy()); put16(o, cpu.ix()); put16(o, 0x81 * cpu.iff() & 0x101); o.write(cpu.im()); put16(o, 23); put16(o, cpu.pc()); put16(o, s.if1rom != null ? 1 : 0); put16(o, (s.rom == s.if1rom ? 0xFF : 0) | (s.ay_enabled ? 0x400 : 0)); o.write(s.ay_idx); for (int i = 0; i < 16; i++) { o.write(s.ay_reg[i]); } byte[] b = new byte[24576]; for (int i = 0; i < 3; i++) { int l = compress_z80(b, s.ram, i << 14, 1 << 14); put16(o, l).write(0x050408 >> 8 * i); o.write(b, 0, l); } o.close(); return o.toByteArray(); } private static int compress_z80(byte b[], int m[], int i, int l) { int j = 0; l += i; loop: do { int n = i; int a = m[i]; do { i++; } while (i < l && m[i] == a); n = i - n; do { if (a != 0xED) { if (n < 5) { do { b[j++] = (byte) a; } while (--n != 0); continue loop; } } else if (n == 1) { b[j++] = (byte) a; if (i == l) { break loop; } b[j++] = (byte) m[i++]; continue loop; } b[j] = b[j + 1] = (byte) 0xED; b[j + 2] = (byte) (n > 255 ? 255 : n); b[j + 3] = (byte) a; j += 4; n -= 255; } while (n > 0); } while (i < l); return j; } // ------------------------------------------------------------------------- }
37,361
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SearchTopicsFrame.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/search/SearchTopicsFrame.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.search; import java.awt.BorderLayout; import org.wandora.application.Wandora; import org.wandora.application.gui.simple.SimpleButton; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.application.gui.topicpanels.SearchTopicPanel; /** * * @author akivela */ public class SearchTopicsFrame extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private SearchTopicPanel searchPanels = null; /** * Creates new form SearchTopicsFrame */ public SearchTopicsFrame() { super(Wandora.getWandora(), false); Wandora wandora = Wandora.getWandora(); setAlwaysOnTop(false); setTitle("Search and query"); initComponents(); searchPanels = new SearchTopicPanel(); searchPanels.setUseResultScrollPanes(true); searchPanels.init(); containerPanel.add(searchPanels.getGui(), BorderLayout.CENTER); setSize(850, 600); if(wandora != null) { setIconImages(wandora.wandoraIcons); wandora.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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonPanel = new javax.swing.JPanel(); fillerPanel = new javax.swing.JPanel(); closeButton = new SimpleButton(); containerScrollPane = new SimpleScrollPane(); containerPanel = new javax.swing.JPanel(); buttonPanel.setLayout(new java.awt.GridBagLayout()); fillerPanel.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; buttonPanel.add(fillerPanel, gridBagConstraints); closeButton.setText("Close"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2); buttonPanel.add(closeButton, gridBagConstraints); getContentPane().setLayout(new java.awt.GridBagLayout()); containerPanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(containerPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed this.setVisible(false); }//GEN-LAST:event_closeButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel buttonPanel; private javax.swing.JButton closeButton; private javax.swing.JPanel containerPanel; private javax.swing.JScrollPane containerScrollPane; private javax.swing.JPanel fillerPanel; // End of variables declaration//GEN-END:variables }
4,544
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimilarityPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/search/SimilarityPanel.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.search; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseWheelListener; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.swing.table.DefaultTableModel; import org.wandora.application.Wandora; import org.wandora.application.gui.TopicSelector; import org.wandora.application.gui.UIBox; 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.SimpleLabel; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.application.gui.simple.SimpleTabbedPane; import org.wandora.application.gui.table.TopicTable; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.TopicMapSearchOptions; import org.wandora.utils.Textbox; import org.wandora.utils.Tuples; import uk.ac.shef.wit.simmetrics.similaritymetrics.BlockDistance; import uk.ac.shef.wit.simmetrics.similaritymetrics.CosineSimilarity; import uk.ac.shef.wit.simmetrics.similaritymetrics.DiceSimilarity; import uk.ac.shef.wit.simmetrics.similaritymetrics.EuclideanDistance; import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric; import uk.ac.shef.wit.simmetrics.similaritymetrics.JaccardSimilarity; import uk.ac.shef.wit.simmetrics.similaritymetrics.Jaro; import uk.ac.shef.wit.simmetrics.similaritymetrics.JaroWinkler; import uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein; import uk.ac.shef.wit.simmetrics.similaritymetrics.MatchingCoefficient; import uk.ac.shef.wit.simmetrics.similaritymetrics.MongeElkan; import uk.ac.shef.wit.simmetrics.similaritymetrics.NeedlemanWunch; import uk.ac.shef.wit.simmetrics.similaritymetrics.OverlapCoefficient; import uk.ac.shef.wit.simmetrics.similaritymetrics.QGramsDistance; import uk.ac.shef.wit.simmetrics.similaritymetrics.SmithWaterman; import uk.ac.shef.wit.simmetrics.similaritymetrics.Soundex; import uk.ac.shef.wit.simmetrics.tokenisers.InterfaceTokeniser; import uk.ac.shef.wit.simmetrics.tokenisers.TokeniserCSVBasic; import uk.ac.shef.wit.simmetrics.tokenisers.TokeniserQGram2; import uk.ac.shef.wit.simmetrics.tokenisers.TokeniserQGram2Extended; import uk.ac.shef.wit.simmetrics.tokenisers.TokeniserQGram3; import uk.ac.shef.wit.simmetrics.tokenisers.TokeniserQGram3Extended; import uk.ac.shef.wit.simmetrics.tokenisers.TokeniserWhitespace; /** * * @author akivela */ public class SimilarityPanel extends javax.swing.JPanel implements TopicSelector { private static final long serialVersionUID = 1L; public boolean ALLOW_PARTIAL_MATCH = true; public static final int SIMILARITY_LEVENSHTEIN_DISTANCE = 101; public static final int SIMILARITY_NEEDLEMAN_WUNCH_DISTANCE = 102; public static final int SIMILARITY_SMITH_WATERMAN_DISTANCE = 104; public static final int SIMILARITY_GOTOH_DISTANCE = 105; public static final int SIMILARITY_BLOCK_DISTANCE = 107; public static final int SIMILARITY_MONGE_ELKAN_DISTANCE = 110; public static final int SIMILARITY_JARO_DISTANCE_METRIC = 111; public static final int SIMILARITY_JARO_WINKLER = 112; public static final int SIMILARITY_SOUNDEX_DISTANCE_METRIC = 113; public static final int SIMILARITY_MATCHING_COEFFICIENT = 114; public static final int SIMILARITY_DICES_COEFFICIENT = 115; public static final int SIMILARITY_JACCARD_SIMILARITY = 116; public static final int SIMILARITY_OVERLAP_COEFFICIENT = 119; public static final int SIMILARITY_EUCLIDEAN_DISTANCE = 120; public static final int SIMILARITY_COSINE_SIMILARITY = 122; public static final int SIMILARITY_Q_GRAM = 136; public Tuples.T2[] similarityTypes = { new Tuples.T2<>("Levenshtein distance", Integer.valueOf(SIMILARITY_LEVENSHTEIN_DISTANCE)), new Tuples.T2<>("Needleman-Wunch distance (Sellers Algorithm)", Integer.valueOf(SIMILARITY_NEEDLEMAN_WUNCH_DISTANCE)), new Tuples.T2<>("Smith-Waterman distance", Integer.valueOf(SIMILARITY_SMITH_WATERMAN_DISTANCE)), new Tuples.T2<>("Block distance (L1 distance or City block distance)", Integer.valueOf(SIMILARITY_BLOCK_DISTANCE)), new Tuples.T2<>("Monge Elkan distance", Integer.valueOf(SIMILARITY_MONGE_ELKAN_DISTANCE)), new Tuples.T2<>("Jaro distance metric", Integer.valueOf(SIMILARITY_JARO_DISTANCE_METRIC)), new Tuples.T2<>("Jaro Winkler", Integer.valueOf(SIMILARITY_JARO_WINKLER)), new Tuples.T2<>("SoundEx distance metric", Integer.valueOf(SIMILARITY_SOUNDEX_DISTANCE_METRIC)), new Tuples.T2<>("Matching Coefficient", Integer.valueOf(SIMILARITY_MATCHING_COEFFICIENT)), new Tuples.T2<>("Dice's Coefficient", Integer.valueOf(SIMILARITY_DICES_COEFFICIENT)), new Tuples.T2<>("Jaccard Similarity (Jaccard Coefficient or Tanimoto coefficient)", Integer.valueOf(SIMILARITY_OVERLAP_COEFFICIENT)), new Tuples.T2<>("Overlap Coefficient", Integer.valueOf(SIMILARITY_JACCARD_SIMILARITY)), new Tuples.T2<>("Euclidean distance (L2 distance)", Integer.valueOf(SIMILARITY_EUCLIDEAN_DISTANCE)), new Tuples.T2<>("Cosine similarity", Integer.valueOf(SIMILARITY_COSINE_SIMILARITY)), new Tuples.T2<>("q-gram", Integer.valueOf(SIMILARITY_Q_GRAM)), }; public Tuples.T2[] similarityTokenizers = { new Tuples.T2<>("Whitespace", new TokeniserWhitespace()), new Tuples.T2<>("CSVBasic", new TokeniserCSVBasic()), new Tuples.T2<>("QGram2", new TokeniserQGram2()), new Tuples.T2<>("QGram2 extended", new TokeniserQGram2Extended()), new Tuples.T2<>("QGram3", new TokeniserQGram3()), new Tuples.T2<>("QGram3 extended", new TokeniserQGram3Extended()) }; private TopicTable resultsTable = null; private SimpleLabel message = null; /** * Creates new form SimilarityPanel */ public SimilarityPanel() { initComponents(); message = new SimpleLabel(); message.setHorizontalAlignment(SimpleLabel.CENTER); message.setIcon(UIBox.getIcon("gui/icons/warn.png")); similarityTextField.setPreferredSize(new Dimension(200, 26)); similarityThresholdSlider.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); similarityTypeComboBox.removeAllItems(); similarityTypeComboBox.setEditable(false); for(int i=0; i<similarityTypes.length; i++) { similarityTypeComboBox.addItem(similarityTypes[i].e1); } similarityTokenizerComboBox.removeAllItems(); similarityTokenizerComboBox.setEditable(false); for(int i=0; i<similarityTokenizers.length; i++) { similarityTokenizerComboBox.addItem(similarityTokenizers[i].e1); } updateSimilarityOptions(); similarityTextField.addKeyListener( new java.awt.event.KeyAdapter() { @Override public void keyReleased(java.awt.event.KeyEvent evt){ if(evt.getKeyChar()==KeyEvent.VK_ENTER) { doSearch(); } } } ); } public void removeResultScrollPanesMouseListeners() { MouseWheelListener[] mouseWheelListeners = resultScrollPane.getMouseWheelListeners(); for(MouseWheelListener listener : mouseWheelListeners) { resultScrollPane.removeMouseWheelListener(listener); } } public String getSimilarityQuery() { return similarityTextField.getText(); } public int getSimilarityType() { Object type = similarityTypeComboBox.getSelectedItem(); if(type != null) { Object t = null; for(Tuples.T2 similarityType : similarityTypes) { if(type.equals(similarityType.e1)) { t = similarityType.e2; if(t instanceof Integer) { return ((Integer) t).intValue(); } } } } return 0; } public InterfaceTokeniser getSimilarityTokenizer() { Object tokenizer = similarityTokenizerComboBox.getSelectedItem(); if(tokenizer != null) { Object t = null; for(Tuples.T2 similarityTokenizer : similarityTokenizers) { if(tokenizer.equals(similarityTokenizer.e1)) { t = similarityTokenizer.e2; if(t instanceof InterfaceTokeniser) { return (InterfaceTokeniser) t; } } } } return new TokeniserWhitespace(); } public TopicMapSearchOptions getSimilarityOptions() { return new TopicMapSearchOptions( similarityBasenameCheckBox.isSelected(), similarityVariantCheckBox.isSelected(), similarityOccurrenceCheckBox.isSelected(), similaritySICheckBox.isSelected(), similaritySLCheckBox.isSelected() ); } public float getSimilarityThreshold() { String ts = similarityThresholdTextField.getText(); float threshold = 0.5f; try { threshold = Float.parseFloat(ts); } catch(Exception e) { e.printStackTrace(); } return Math.max(0, Math.min( threshold, 100 )) / 100; } public void updateSimilarityThreshold() { int threshold = similarityThresholdSlider.getValue(); similarityThresholdTextField.setText(""+threshold); } public Collection<Topic> getSimilarTopics(TopicMap tm) throws TopicMapException { if(tm != null) { int similarityType = getSimilarityType(); float threshold = getSimilarityThreshold(); Iterator<Topic> iterator = tm.getTopics(); String query = getSimilarityQuery(); TopicMapSearchOptions options = getSimilarityOptions(); boolean differenceInsteadOfSimilarity = similarityDifferenceCheckBox.isSelected(); return getSimilarTopics(query, options, iterator, similarityType, threshold, differenceInsteadOfSimilarity); } return null; } public InterfaceStringMetric getStringMetric(int similarityType) { InterfaceStringMetric stringMetric = null; InterfaceTokeniser tokenizer = getSimilarityTokenizer(); switch(similarityType) { case SIMILARITY_LEVENSHTEIN_DISTANCE: { stringMetric = new Levenshtein(); break; } case SIMILARITY_NEEDLEMAN_WUNCH_DISTANCE: { float cost = getGapCost(0.5f); stringMetric = new NeedlemanWunch(cost); break; } case SIMILARITY_SMITH_WATERMAN_DISTANCE: { float cost = getGapCost(0.5f); stringMetric = new SmithWaterman(cost); break; } case SIMILARITY_BLOCK_DISTANCE: { stringMetric = new BlockDistance(tokenizer); break; } case SIMILARITY_MONGE_ELKAN_DISTANCE: { stringMetric = new MongeElkan(tokenizer); break; } case SIMILARITY_JARO_DISTANCE_METRIC: { stringMetric = new Jaro(); break; } case SIMILARITY_JARO_WINKLER: { stringMetric = new JaroWinkler(); break; } case SIMILARITY_SOUNDEX_DISTANCE_METRIC: { stringMetric = new Soundex(); break; } case SIMILARITY_MATCHING_COEFFICIENT: { stringMetric = new MatchingCoefficient(tokenizer); break; } case SIMILARITY_DICES_COEFFICIENT: { stringMetric = new DiceSimilarity(tokenizer); break; } case SIMILARITY_JACCARD_SIMILARITY: { stringMetric = new JaccardSimilarity(tokenizer); break; } case SIMILARITY_OVERLAP_COEFFICIENT: { stringMetric = new OverlapCoefficient(tokenizer); break; } case SIMILARITY_EUCLIDEAN_DISTANCE: { stringMetric = new EuclideanDistance(tokenizer); break; } case SIMILARITY_COSINE_SIMILARITY: { stringMetric = new CosineSimilarity(tokenizer); break; } case SIMILARITY_Q_GRAM: { stringMetric = new QGramsDistance(tokenizer); break; } default: { System.out.println("Unknown similarity type used in similarity test"); } } return stringMetric; } public Collection<Topic> getSimilarTopics(String query, TopicMapSearchOptions options, Iterator<Topic> topicIterator, int similarityType, float threshold, boolean differenceInsteadOfSimilarity) { InterfaceStringMetric stringMetric = getStringMetric(similarityType); if(stringMetric != null) { return SimilarityBox.getSimilarTopics(query, options, topicIterator, stringMetric, threshold, differenceInsteadOfSimilarity, getUseNGrams()); } return new ArrayList<Topic>(); } private void updateSimilarityOptions() { int t = getSimilarityType(); if(t == SIMILARITY_SMITH_WATERMAN_DISTANCE || t == SIMILARITY_NEEDLEMAN_WUNCH_DISTANCE) { gapCostTextField.setEnabled(true); gapCostLabel.setEnabled(true); } else { gapCostTextField.setEnabled(false); gapCostLabel.setEnabled(false); } if(t == SIMILARITY_SOUNDEX_DISTANCE_METRIC || t == SIMILARITY_JARO_WINKLER || t == SIMILARITY_JARO_DISTANCE_METRIC || t == SIMILARITY_LEVENSHTEIN_DISTANCE || t == SIMILARITY_NEEDLEMAN_WUNCH_DISTANCE || t == SIMILARITY_SMITH_WATERMAN_DISTANCE) { similarityTokenizerComboBox.setEnabled(false); similarityTokenizerLabel.setEnabled(false); } else { similarityTokenizerComboBox.setEnabled(true); similarityTokenizerLabel.setEnabled(true); } InterfaceStringMetric stringMetric = getStringMetric(getSimilarityType()); if(stringMetric != null) { similarityTypeComboBox.setToolTipText(Textbox.makeHTMLParagraph(stringMetric.getLongDescriptionString(), 40)); } } public void updateTokenizerOptions() { InterfaceTokeniser tokenizer = getSimilarityTokenizer(); if(tokenizer != null) { similarityTokenizerComboBox.setToolTipText(Textbox.makeHTMLParagraph(tokenizer.getShortDescriptionString(), 40)); } } public float getGapCost(float defaultValue) { float cost = defaultValue; try { cost = Float.parseFloat(gapCostTextField.getText()); } catch(Exception e) { e.printStackTrace(); } return cost; } public boolean getUseNGrams() { return useNGrams.isSelected(); } public void refresh() { if(resultsTable != null) { ((DefaultTableModel) resultsTable.getModel()).fireTableDataChanged(); } resultPanel.revalidate(); revalidate(); } public void doSearch() { try { resultPanel.removeAll(); Wandora wandora = Wandora.getWandora(); TopicMap topicMap = wandora.getTopicMap(); Collection<Topic> results = getSimilarTopics(topicMap); if(results != null && !results.isEmpty()) { resultsTable = new TopicTable(wandora); resultsTable.initialize(results); resultPanel.add(resultsTable, BorderLayout.NORTH); } else { resultsTable = null; message.setText("Found no topics!"); resultPanel.add(message, BorderLayout.CENTER); } } catch(TopicMapException tme) { message.setText("Topic map exception!"); resultPanel.add(message, BorderLayout.CENTER); tme.printStackTrace(); } catch(Exception e){ message.setText("Error!"); resultPanel.add(message, BorderLayout.CENTER); e.printStackTrace(); return; } revalidate(); repaint(); } /** * 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; containerPanel = new javax.swing.JPanel(); similarityPanel = new javax.swing.JPanel(); similarityPanelInner = new javax.swing.JPanel(); similarityTypePanel = new javax.swing.JPanel(); similarityTypeComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); similarityTextPanel = new javax.swing.JPanel(); similarityTextField = new SimpleField(); optionsTabbedPane = new SimpleTabbedPane(); thresholdPanel = new javax.swing.JPanel(); thresholdInnerPanel = new javax.swing.JPanel(); similarityThresholdSlider = new javax.swing.JSlider(); similarityThresholdTextField = new org.wandora.application.gui.simple.SimpleField(); similarityDifferenceCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); similarityTokenizerPanel = new javax.swing.JPanel(); tokenizerPanel = new javax.swing.JPanel(); similarityTokenizerLabel = new org.wandora.application.gui.simple.SimpleLabel(); similarityTokenizerComboBox = new org.wandora.application.gui.simple.SimpleComboBox(); similaritygapCostPanel = new javax.swing.JPanel(); gapCostLabel = new org.wandora.application.gui.simple.SimpleLabel(); gapCostTextField = new org.wandora.application.gui.simple.SimpleField(); compareToPanel = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); similarityBasenameCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); similarityVariantCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); similarityOccurrenceCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); jPanel2 = new javax.swing.JPanel(); similaritySICheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); similaritySLCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); jSeparator1 = new javax.swing.JSeparator(); jPanel3 = new javax.swing.JPanel(); useNGrams = new SimpleCheckBox(); runButtonPanel = new javax.swing.JPanel(); searchButton = new SimpleButton(); resultPanelContainer = new javax.swing.JPanel(); resultScrollPane = new SimpleScrollPane(); resultPanel = new javax.swing.JPanel(); setLayout(new java.awt.GridBagLayout()); containerPanel.setLayout(new java.awt.GridBagLayout()); similarityPanel.setLayout(new java.awt.GridBagLayout()); similarityPanelInner.setLayout(new java.awt.GridBagLayout()); similarityTypePanel.setLayout(new java.awt.GridBagLayout()); similarityTypeComboBox.setPreferredSize(new java.awt.Dimension(28, 25)); similarityTypeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { similarityTypeComboBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; similarityTypePanel.add(similarityTypeComboBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; similarityPanelInner.add(similarityTypePanel, gridBagConstraints); similarityTextPanel.setLayout(new java.awt.GridBagLayout()); similarityTextField.setMargin(new java.awt.Insets(4, 4, 4, 4)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; similarityTextPanel.add(similarityTextField, 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, 0, 2, 0); similarityPanelInner.add(similarityTextPanel, gridBagConstraints); thresholdPanel.setLayout(new java.awt.GridBagLayout()); thresholdInnerPanel.setLayout(new java.awt.GridBagLayout()); similarityThresholdSlider.setToolTipText(Textbox.makeHTMLParagraph("Similarity threshold specifies allowed difference between similar strings. When threshold is near 100, only minimal differences are allowed. When threshold is near 0, strings may be very different and they are still similar.", 40)); similarityThresholdSlider.setMinimumSize(new java.awt.Dimension(100, 24)); similarityThresholdSlider.setPreferredSize(new java.awt.Dimension(200, 24)); similarityThresholdSlider.addMouseListener(new java.awt.event.MouseAdapter() { public void mousePressed(java.awt.event.MouseEvent evt) { similarityThresholdSliderMousePressed(evt); } public void mouseReleased(java.awt.event.MouseEvent evt) { similarityThresholdSliderMouseReleased(evt); } }); similarityThresholdSlider.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) { similarityThresholdSliderMouseDragged(evt); } }); thresholdInnerPanel.add(similarityThresholdSlider, new java.awt.GridBagConstraints()); similarityThresholdTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); similarityThresholdTextField.setText("50"); similarityThresholdTextField.setMinimumSize(new java.awt.Dimension(40, 24)); similarityThresholdTextField.setPreferredSize(new java.awt.Dimension(40, 24)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); thresholdInnerPanel.add(similarityThresholdTextField, gridBagConstraints); similarityDifferenceCheckBox.setFont(org.wandora.application.gui.UIConstants.tabFont); similarityDifferenceCheckBox.setText("Difference instead similarity"); similarityDifferenceCheckBox.setToolTipText("Results different topics instead of similar topics, if checked."); similarityDifferenceCheckBox.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); similarityDifferenceCheckBox.setMargin(new java.awt.Insets(2, 0, 2, 2)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0); thresholdInnerPanel.add(similarityDifferenceCheckBox, 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(6, 0, 5, 0); thresholdPanel.add(thresholdInnerPanel, gridBagConstraints); optionsTabbedPane.addTab("Threshold", thresholdPanel); similarityTokenizerPanel.setLayout(new java.awt.GridBagLayout()); tokenizerPanel.setLayout(new java.awt.GridBagLayout()); similarityTokenizerLabel.setFont(org.wandora.application.gui.UIConstants.tabFont); similarityTokenizerLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); similarityTokenizerLabel.setText("Tokenizer"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); tokenizerPanel.add(similarityTokenizerLabel, gridBagConstraints); similarityTokenizerComboBox.setMinimumSize(new java.awt.Dimension(130, 24)); similarityTokenizerComboBox.setPreferredSize(new java.awt.Dimension(130, 24)); similarityTokenizerComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { similarityTokenizerComboBoxActionPerformed(evt); } }); tokenizerPanel.add(similarityTokenizerComboBox, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0); similarityTokenizerPanel.add(tokenizerPanel, gridBagConstraints); similaritygapCostPanel.setLayout(new java.awt.GridBagLayout()); gapCostLabel.setFont(org.wandora.application.gui.UIConstants.tabFont); gapCostLabel.setText("Gap cost"); gapCostLabel.setToolTipText("Some similarity metrics require gap cost in similarity calculations."); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); similaritygapCostPanel.add(gapCostLabel, gridBagConstraints); gapCostTextField.setHorizontalAlignment(javax.swing.JTextField.CENTER); gapCostTextField.setText("0.5"); gapCostTextField.setMinimumSize(new java.awt.Dimension(40, 24)); gapCostTextField.setPreferredSize(new java.awt.Dimension(40, 24)); similaritygapCostPanel.add(gapCostTextField, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; similarityTokenizerPanel.add(similaritygapCostPanel, gridBagConstraints); optionsTabbedPane.addTab("Tokenizer", similarityTokenizerPanel); compareToPanel.setLayout(new java.awt.GridBagLayout()); jPanel1.setLayout(new java.awt.GridBagLayout()); similarityBasenameCheckBox.setSelected(true); similarityBasenameCheckBox.setText("base names"); jPanel1.add(similarityBasenameCheckBox, new java.awt.GridBagConstraints()); similarityVariantCheckBox.setSelected(true); similarityVariantCheckBox.setText("variant names"); jPanel1.add(similarityVariantCheckBox, new java.awt.GridBagConstraints()); similarityOccurrenceCheckBox.setText("occurrences"); jPanel1.add(similarityOccurrenceCheckBox, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0); compareToPanel.add(jPanel1, gridBagConstraints); jPanel2.setLayout(new java.awt.GridBagLayout()); similaritySICheckBox.setText("subject identifiers"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; jPanel2.add(similaritySICheckBox, gridBagConstraints); similaritySLCheckBox.setText("subject locators"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; jPanel2.add(similaritySLCheckBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; compareToPanel.add(jPanel2, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.8; gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6); compareToPanel.add(jSeparator1, gridBagConstraints); jPanel3.setLayout(new java.awt.GridBagLayout()); useNGrams.setSelected(true); useNGrams.setText("Compare n-grams instead of complete strings"); useNGrams.setToolTipText("<html>If the target string is longer than user specified similarity text,<br>split the target string into n-grams and choose biggest n-gram similarity value.</html>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; jPanel3.add(useNGrams, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 8, 0); compareToPanel.add(jPanel3, gridBagConstraints); optionsTabbedPane.addTab("Compare to", compareToPanel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; similarityPanelInner.add(optionsTabbedPane, gridBagConstraints); optionsTabbedPane.getAccessibleContext().setAccessibleName("tab2"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.PAGE_START; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); similarityPanel.add(similarityPanelInner, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; containerPanel.add(similarityPanel, gridBagConstraints); runButtonPanel.setMaximumSize(new java.awt.Dimension(2147483647, 40)); runButtonPanel.setMinimumSize(new java.awt.Dimension(92, 40)); runButtonPanel.setPreferredSize(new java.awt.Dimension(10, 40)); runButtonPanel.setLayout(new java.awt.GridBagLayout()); searchButton.setText("Search"); searchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(38, 13, 39, 14); runButtonPanel.add(searchButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; containerPanel.add(runButtonPanel, gridBagConstraints); resultPanelContainer.setLayout(new java.awt.BorderLayout()); resultScrollPane.setBorder(null); resultPanel.setLayout(new java.awt.BorderLayout()); resultScrollPane.setViewportView(resultPanel); resultPanelContainer.add(resultScrollPane, java.awt.BorderLayout.CENTER); 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(5, 0, 0, 0); containerPanel.add(resultPanelContainer, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(containerPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void similarityTypeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_similarityTypeComboBoxActionPerformed if((evt.getModifiers() | ActionEvent.MOUSE_EVENT_MASK) != 0) { updateSimilarityOptions(); } }//GEN-LAST:event_similarityTypeComboBoxActionPerformed private void similarityTokenizerComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_similarityTokenizerComboBoxActionPerformed if((evt.getModifiers() | ActionEvent.MOUSE_EVENT_MASK) != 0) { updateTokenizerOptions(); } }//GEN-LAST:event_similarityTokenizerComboBoxActionPerformed private void similarityThresholdSliderMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_similarityThresholdSliderMousePressed updateSimilarityThreshold(); }//GEN-LAST:event_similarityThresholdSliderMousePressed private void similarityThresholdSliderMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_similarityThresholdSliderMouseReleased updateSimilarityThreshold(); }//GEN-LAST:event_similarityThresholdSliderMouseReleased private void similarityThresholdSliderMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_similarityThresholdSliderMouseDragged updateSimilarityThreshold(); }//GEN-LAST:event_similarityThresholdSliderMouseDragged private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed doSearch(); }//GEN-LAST:event_searchButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel compareToPanel; private javax.swing.JPanel containerPanel; private javax.swing.JLabel gapCostLabel; private javax.swing.JTextField gapCostTextField; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JSeparator jSeparator1; private javax.swing.JTabbedPane optionsTabbedPane; private javax.swing.JPanel resultPanel; private javax.swing.JPanel resultPanelContainer; private javax.swing.JScrollPane resultScrollPane; private javax.swing.JPanel runButtonPanel; private javax.swing.JButton searchButton; private javax.swing.JCheckBox similarityBasenameCheckBox; private javax.swing.JCheckBox similarityDifferenceCheckBox; private javax.swing.JCheckBox similarityOccurrenceCheckBox; private javax.swing.JPanel similarityPanel; private javax.swing.JPanel similarityPanelInner; private javax.swing.JCheckBox similaritySICheckBox; private javax.swing.JCheckBox similaritySLCheckBox; private javax.swing.JTextField similarityTextField; private javax.swing.JPanel similarityTextPanel; private javax.swing.JSlider similarityThresholdSlider; private javax.swing.JTextField similarityThresholdTextField; private javax.swing.JComboBox similarityTokenizerComboBox; private javax.swing.JLabel similarityTokenizerLabel; private javax.swing.JPanel similarityTokenizerPanel; private javax.swing.JComboBox similarityTypeComboBox; private javax.swing.JPanel similarityTypePanel; private javax.swing.JCheckBox similarityVariantCheckBox; private javax.swing.JPanel similaritygapCostPanel; private javax.swing.JPanel thresholdInnerPanel; private javax.swing.JPanel thresholdPanel; private javax.swing.JPanel tokenizerPanel; private javax.swing.JCheckBox useNGrams; // End of variables declaration//GEN-END:variables // ------------------------------------------------------- TopicSelector --- @Override public Topic getSelectedTopic() { if(resultsTable != null) { Topic[] topics = resultsTable.getSelectedTopics(); if(topics != null && topics.length > 0) { return topics[0]; } } return null; } @Override public Topic[] getSelectedTopics() { if(resultsTable != null) { resultsTable.getSelectedTopics(); } return null; } @Override public java.awt.Component getPanel() { return this; } @Override public String getSelectorName() { return "Similarity"; } @Override public void init() { } @Override public void cleanup() { } }
38,860
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SimilarityBox.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/search/SimilarityBox.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.search; import java.util.ArrayList; import java.util.List; import java.util.Collection; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Set; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapSearchOptions; import uk.ac.shef.wit.simmetrics.similaritymetrics.InterfaceStringMetric; /** * * @author akivela */ public class SimilarityBox { public static Collection<Topic> getSimilarTopics(String query, TopicMapSearchOptions options, Iterator<Topic> topicIterator, InterfaceStringMetric stringMetric, float threshold, boolean differenceInsteadOfSimilarity, boolean useNGrams) { List<Topic> selection = new ArrayList<Topic>(); int count = 0; Topic t = null; boolean isSimilar = false; float similarity = 0.0f; try { while(topicIterator.hasNext()) { similarity = 0.0f; isSimilar = false; t = topicIterator.next(); if(t != null && !t.isRemoved()) { if(options.searchBasenames) { String n = t.getBaseName(); if(n != null && n.length() > 0) { similarity = getSimilarity(query, n, stringMetric, useNGrams); isSimilar = isSimilar(similarity, threshold, differenceInsteadOfSimilarity); } } if(!isSimilar && options.searchVariants) { String n = null; Set<Set<Topic>> scopes = t.getVariantScopes(); Iterator<Set<Topic>> scopeIterator = scopes.iterator(); Set<Topic> scope = null; while(!isSimilar && scopeIterator.hasNext()) { scope = scopeIterator.next(); if(scope != null) { n = t.getVariant(scope); if(n != null && n.length() > 0) { similarity = getSimilarity(query, n, stringMetric, useNGrams); isSimilar = isSimilar(similarity, threshold, differenceInsteadOfSimilarity); } } } } if(!isSimilar && options.searchOccurrences) { String o = null; Collection<Topic> types = t.getDataTypes(); Iterator<Topic> typeIterator = types.iterator(); Topic type = null; Hashtable<Topic, String> os = null; Enumeration<Topic> osEnumeration = null; Topic osTopic = null; while(!isSimilar && typeIterator.hasNext()) { type = typeIterator.next(); if(type != null && !type.isRemoved()) { os = t.getData(type); osEnumeration = os.keys(); while(osEnumeration.hasMoreElements() && !isSimilar) { osTopic = osEnumeration.nextElement(); o = os.get(osTopic); if(o != null && o.length() > 0) { similarity = getSimilarity(query, o, stringMetric, useNGrams); isSimilar = isSimilar(similarity, threshold, differenceInsteadOfSimilarity); } } } } } if(!isSimilar && options.searchSIs) { Collection<Locator> locs = t.getSubjectIdentifiers(); if(locs != null && locs.size() > 0) { Iterator<Locator> locIter = locs.iterator(); Locator loc = null; String l = null; while(locIter.hasNext() && !isSimilar) { loc = locIter.next(); if(loc != null) { l = loc.toExternalForm(); similarity = getSimilarity(query, l, stringMetric, useNGrams); isSimilar = isSimilar(similarity, threshold, differenceInsteadOfSimilarity); } } } } if(!isSimilar && options.searchSL) { Locator loc = t.getSubjectLocator(); if(loc != null) { String l = loc.toExternalForm(); similarity = getSimilarity(query, l, stringMetric, useNGrams); isSimilar = isSimilar(similarity, threshold, differenceInsteadOfSimilarity); } } // ***** IF TOPIC IS SIMILAR **** if(isSimilar) { selection.add(t); } } } } catch(Exception e) { e.printStackTrace(); } return selection; } public static float getSimilarity(String s1, String s2, InterfaceStringMetric stringMetric, boolean useNGrams) { float similarity = 0.0f; if(s1 != null && s2 != null && stringMetric != null) { if(useNGrams) { int l1 = s1.length(); int l2 = s2.length(); if(l2 > l1) { for(int i=0; i<l2-l1; i++) { float s = stringMetric.getSimilarity(s1, s2.substring(i, i+l1)); if(s > similarity) { similarity = s; } } } else { similarity = stringMetric.getSimilarity(s1, s2); } } else { similarity = stringMetric.getSimilarity(s1, s2); } } return similarity; } public static boolean isSimilar(float similarity, float threshold, boolean differenceInsteadOfSimilarity) { if(differenceInsteadOfSimilarity) { return (similarity < threshold); } else { return (similarity > threshold); } } }
7,632
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SearchPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/search/SearchPanel.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/>. * * * SearchPanel.java * * Created on 29. joulukuuta 2005, 16:34 */ package org.wandora.application.gui.search; import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.awt.event.MouseWheelListener; import java.util.Collection; import javax.swing.ComboBoxEditor; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; import org.wandora.application.Wandora; import org.wandora.application.gui.TopicSelector; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.simple.SimpleComboBox; import org.wandora.application.gui.table.TopicTable; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapSearchOptions; import org.wandora.utils.Textbox; /** * * @author akivela */ public class SearchPanel extends javax.swing.JPanel implements TopicSelector { private static final long serialVersionUID = 1L; public static final int HISTORYMAXSIZE = 40; private Wandora wandora; private TopicTable foundTable = null; private Collection<Topic> foundTopics = null; private Topic[] foundTopicsArray = null; private boolean allowMultiSelection = true; /** Creates new form SearchPanel */ public SearchPanel() { this.wandora = Wandora.getWandora(); initComponents(); searchWords.getEditor().getEditorComponent().addKeyListener( new java.awt.event.KeyAdapter() { @Override public void keyReleased(java.awt.event.KeyEvent evt){ if(evt.getKeyChar()==KeyEvent.VK_ENTER) { doSearch(); } } } ); toggleSearchOptionsVisibility(null); } public SearchPanel(boolean allowMultiSelection) { this(); this.allowMultiSelection = allowMultiSelection; } public void requestSearchFieldFocus() { searchWords.requestFocus(); ComboBoxEditor ed = searchWords.getEditor(); if(ed != null) { ed.selectAll(); } } public void removeResultScrollPanesMouseListeners() { MouseWheelListener[] mouseWheelListeners = resultPanelScroller.getMouseWheelListeners(); for(MouseWheelListener listener : mouseWheelListeners) { resultPanelScroller.removeMouseWheelListener(listener); } } public void doSearch() { try { String query = (String) searchWords.getSelectedItem(); query = Textbox.trimExtraSpaces(query); resultPanel.removeAll(); foundTopics = null; if(query != null && query.length() > 0) { resultPanel.add(messagePanel, BorderLayout.CENTER); messageField.setText("Executing query..."); messageField.setIcon(UIBox.getIcon("gui/icons/wait.png")); refresh(); TopicMap topicMap = wandora.getTopicMap(); //this.searchWords.setSelectedIndex(0); searchWords.addItem(query); if(searchWords.getItemCount() > HISTORYMAXSIZE) searchWords.removeItemAt(1); TopicMapSearchOptions searchOptions; if(searchAllCheckBox.isSelected()) { searchOptions = new TopicMapSearchOptions(); } else { searchOptions = new TopicMapSearchOptions( searchBasenamesCheckBox.isSelected(), searchVariantnamesCheckBox.isSelected(), searchTextdatasCheckBox.isSelected(), searchSIsCheckBox.isSelected(), searchSLsCheckBox.isSelected()); } foundTopics = topicMap.search(query, searchOptions); foundTopicsArray = foundTopics.toArray(new Topic[] {}); if(foundTopics != null && foundTopicsArray.length > 0) { foundTable = new TopicTable(wandora); foundTable.initialize(foundTopicsArray, null); foundTable.toggleSortOrder(0); if(!allowMultiSelection) { foundTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } resultPanel.removeAll(); resultPanel.add(foundTable, BorderLayout.CENTER); } else { //resultPanel.add(messagePanel, BorderLayout.CENTER); messageField.setText("Found no topics!"); messageField.setIcon(UIBox.getIcon("gui/icons/warn.png")); } } else { resultPanel.add(messagePanel, BorderLayout.CENTER); messageField.setText("Query was empty!"); messageField.setIcon(UIBox.getIcon("gui/icons/warn.png")); } refresh(); } catch (Exception e) { messageField.setText("Error!"); messageField.setIcon(UIBox.getIcon("gui/icons/warn.png")); wandora.handleError(e); } } public void refresh() { if(foundTable != null) { ((DefaultTableModel) foundTable.getModel()).fireTableDataChanged(); } resultPanel.revalidate(); resultPanelContainer.revalidate(); revalidate(); } // ------------------------------------------------------------------------- @Override public Topic getSelectedTopic() { if(foundTable != null) { Topic[] topics = foundTable.getSelectedTopics(); if(topics != null && topics.length > 0) { return topics[0]; } } return null; } @Override public Topic[] getSelectedTopics() { if(foundTable != null) { foundTable.getSelectedTopics(); } return null; } @Override public java.awt.Component getPanel() { return this; } @Override public String getSelectorName() { return "Finder"; } @Override public void init() { searchWords.setSelectedItem(""); } @Override public void cleanup() { } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- /** 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; messagePanel = new javax.swing.JPanel(); messageField = new org.wandora.application.gui.simple.SimpleLabel(); searchFieldPanel = new javax.swing.JPanel(); searchWords = new SimpleComboBox(); startSearchButton = new org.wandora.application.gui.simple.SimpleButton(); searchOptionsPanel = new javax.swing.JPanel(); searchAllCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); searchBasenamesCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); searchVariantnamesCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); searchTextdatasCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); searchSLsCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); searchSIsCheckBox = new org.wandora.application.gui.simple.SimpleCheckBox(); jSeparator1 = new javax.swing.JSeparator(); resultPanelContainer = new javax.swing.JPanel(); resultPanelScroller = new org.wandora.application.gui.simple.SimpleScrollPane(); resultPanel = new javax.swing.JPanel(); messagePanel.setBackground(new java.awt.Color(255, 255, 255)); messagePanel.setLayout(new java.awt.GridBagLayout()); messageField.setBackground(new java.awt.Color(255, 255, 255)); messageField.setForeground(new java.awt.Color(53, 56, 87)); messageField.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); messageField.setText("No topics found!"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; messagePanel.add(messageField, gridBagConstraints); setLayout(new java.awt.BorderLayout()); searchFieldPanel.setLayout(new java.awt.GridBagLayout()); searchWords.setEditable(true); searchWords.setPreferredSize(new java.awt.Dimension(29, 25)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 2, 0); searchFieldPanel.add(searchWords, gridBagConstraints); startSearchButton.setFont(org.wandora.application.gui.UIConstants.smallButtonLabelFont); startSearchButton.setText("Search"); startSearchButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); startSearchButton.setMaximumSize(new java.awt.Dimension(60, 25)); startSearchButton.setMinimumSize(new java.awt.Dimension(60, 25)); startSearchButton.setPreferredSize(new java.awt.Dimension(60, 25)); startSearchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { doSearch(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.insets = new java.awt.Insets(5, 2, 2, 5); searchFieldPanel.add(startSearchButton, gridBagConstraints); searchOptionsPanel.setLayout(new java.awt.GridBagLayout()); searchAllCheckBox.setSelected(true); searchAllCheckBox.setText("Search in all topic elements"); searchAllCheckBox.setMinimumSize(new java.awt.Dimension(155, 20)); searchAllCheckBox.setPreferredSize(new java.awt.Dimension(155, 20)); searchAllCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { toggleSearchOptionsVisibility(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); searchOptionsPanel.add(searchAllCheckBox, gridBagConstraints); searchBasenamesCheckBox.setText("Search in base names"); searchBasenamesCheckBox.setMinimumSize(new java.awt.Dimension(127, 20)); searchBasenamesCheckBox.setPreferredSize(new java.awt.Dimension(127, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); searchOptionsPanel.add(searchBasenamesCheckBox, gridBagConstraints); searchVariantnamesCheckBox.setText("Search in variant names"); searchVariantnamesCheckBox.setMinimumSize(new java.awt.Dimension(141, 20)); searchVariantnamesCheckBox.setPreferredSize(new java.awt.Dimension(141, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); searchOptionsPanel.add(searchVariantnamesCheckBox, gridBagConstraints); searchTextdatasCheckBox.setText("Search in occurrences"); searchTextdatasCheckBox.setMinimumSize(new java.awt.Dimension(123, 20)); searchTextdatasCheckBox.setPreferredSize(new java.awt.Dimension(81, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); searchOptionsPanel.add(searchTextdatasCheckBox, gridBagConstraints); searchSLsCheckBox.setText("Search in subject locators"); searchSLsCheckBox.setMinimumSize(new java.awt.Dimension(149, 20)); searchSLsCheckBox.setPreferredSize(new java.awt.Dimension(81, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); searchOptionsPanel.add(searchSLsCheckBox, gridBagConstraints); searchSIsCheckBox.setText("Search in subject identifiers"); searchSIsCheckBox.setMinimumSize(new java.awt.Dimension(157, 20)); searchSIsCheckBox.setPreferredSize(new java.awt.Dimension(81, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5); searchOptionsPanel.add(searchSIsCheckBox, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; searchFieldPanel.add(searchOptionsPanel, gridBagConstraints); 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(2, 0, 0, 0); searchFieldPanel.add(jSeparator1, gridBagConstraints); add(searchFieldPanel, java.awt.BorderLayout.NORTH); resultPanelContainer.setLayout(new java.awt.BorderLayout()); resultPanelScroller.setBorder(null); resultPanel.setLayout(new java.awt.BorderLayout()); resultPanelScroller.setViewportView(resultPanel); resultPanelContainer.add(resultPanelScroller, java.awt.BorderLayout.CENTER); add(resultPanelContainer, java.awt.BorderLayout.CENTER); }// </editor-fold>//GEN-END:initComponents private void toggleSearchOptionsVisibility(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toggleSearchOptionsVisibility boolean flag = false; if(!searchAllCheckBox.isSelected()) { flag = true; } searchBasenamesCheckBox.setVisible(flag); searchVariantnamesCheckBox.setVisible(flag); searchTextdatasCheckBox.setVisible(flag); searchSLsCheckBox.setVisible(flag); searchSIsCheckBox.setVisible(flag); }//GEN-LAST:event_toggleSearchOptionsVisibility private void doSearch(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_doSearch startSearchButton.setEnabled(false); Thread searchThread = new Thread() { public void run() { doSearch(); startSearchButton.setEnabled(true); }; }; searchThread.start(); }//GEN-LAST:event_doSearch // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JSeparator jSeparator1; private javax.swing.JLabel messageField; private javax.swing.JPanel messagePanel; private javax.swing.JPanel resultPanel; private javax.swing.JPanel resultPanelContainer; private javax.swing.JScrollPane resultPanelScroller; private javax.swing.JCheckBox searchAllCheckBox; private javax.swing.JCheckBox searchBasenamesCheckBox; private javax.swing.JPanel searchFieldPanel; private javax.swing.JPanel searchOptionsPanel; private javax.swing.JCheckBox searchSIsCheckBox; private javax.swing.JCheckBox searchSLsCheckBox; private javax.swing.JCheckBox searchTextdatasCheckBox; private javax.swing.JCheckBox searchVariantnamesCheckBox; private javax.swing.JComboBox searchWords; private javax.swing.JButton startSearchButton; // End of variables declaration//GEN-END:variables }
18,794
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SelectTopicPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/search/SelectTopicPanel.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/>. * * * SelectTopicPanel.java * * Created on 17. helmikuuta 2006, 11:33 */ package org.wandora.application.gui.search; import java.awt.Component; import java.awt.event.KeyEvent; import org.wandora.application.Wandora; import org.wandora.application.gui.TopicSelector; 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.SimpleRadioButton; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; /** * * @author olli */ public class SelectTopicPanel extends javax.swing.JPanel implements TopicSelector { private static final long serialVersionUID = 1L; private Wandora wandora; private Topic result; /** Creates new form SelectTopicPanel */ public SelectTopicPanel(Wandora wandora) { this.wandora=wandora; initComponents(); } /** 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; buttonGroup1 = new javax.swing.ButtonGroup(); searchLabel = new SimpleLabel(); radioPanel = new javax.swing.JPanel(); baseNameRadioButton = new SimpleRadioButton(); subjectIdentifierRadioButton = new SimpleRadioButton(); subjectLocatorRadioButton = new SimpleRadioButton(); searchPanel = new javax.swing.JPanel(); searchTextField = new SimpleField(); searchButton = new SimpleButton(); resultTextArea = new javax.swing.JTextArea(); setLayout(new java.awt.GridBagLayout()); searchLabel.setFont(org.wandora.application.gui.UIConstants.tabFont); searchLabel.setText("Select"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 3); add(searchLabel, gridBagConstraints); radioPanel.setLayout(new java.awt.GridBagLayout()); buttonGroup1.add(baseNameRadioButton); baseNameRadioButton.setSelected(true); baseNameRadioButton.setText("base name"); baseNameRadioButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); baseNameRadioButton.setFocusPainted(false); baseNameRadioButton.setMargin(new java.awt.Insets(0, 0, 0, 0)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4); radioPanel.add(baseNameRadioButton, gridBagConstraints); buttonGroup1.add(subjectIdentifierRadioButton); subjectIdentifierRadioButton.setText("subject identifier"); subjectIdentifierRadioButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); subjectIdentifierRadioButton.setFocusPainted(false); subjectIdentifierRadioButton.setMargin(new java.awt.Insets(0, 0, 0, 0)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4); radioPanel.add(subjectIdentifierRadioButton, gridBagConstraints); buttonGroup1.add(subjectLocatorRadioButton); subjectLocatorRadioButton.setText("subject locator"); subjectLocatorRadioButton.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); subjectLocatorRadioButton.setFocusPainted(false); subjectLocatorRadioButton.setMargin(new java.awt.Insets(0, 0, 0, 0)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4); radioPanel.add(subjectLocatorRadioButton, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(8, 0, 4, 8); add(radioPanel, gridBagConstraints); searchPanel.setLayout(new java.awt.GridBagLayout()); searchTextField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { searchTextFieldKeyReleased(evt); } public void keyTyped(java.awt.event.KeyEvent evt) { searchTextFieldKeyTyped(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(0, 0, 4, 0); searchPanel.add(searchTextField, gridBagConstraints); searchButton.setText("Seek"); searchButton.setMargin(new java.awt.Insets(0, 3, 0, 3)); searchButton.setMaximumSize(new java.awt.Dimension(60, 19)); searchButton.setMinimumSize(new java.awt.Dimension(60, 19)); searchButton.setPreferredSize(new java.awt.Dimension(60, 19)); searchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 2, 4, 0); searchPanel.add(searchButton, gridBagConstraints); resultTextArea.setColumns(20); resultTextArea.setEditable(false); resultTextArea.setFont(new java.awt.Font("SansSerif", 0, 11)); // NOI18N resultTextArea.setLineWrap(true); resultTextArea.setRows(6); resultTextArea.setText("Select identifier type and enter complete identifier. Finalize by clicking the Seek button. Select result is viewed in this field."); resultTextArea.setWrapStyleWord(true); resultTextArea.setOpaque(false); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; searchPanel.add(resultTextArea, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 4, 8, 8); add(searchPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void searchTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchTextFieldKeyReleased if(evt.getKeyCode()==evt.VK_ENTER){ doSearch(); } }//GEN-LAST:event_searchTextFieldKeyReleased @Override public void init(){} @Override public void cleanup(){} public void requestSearchFieldFocus() { searchTextField.requestFocus(); searchTextField.selectAll(); } public void doSearch(){ String text=searchTextField.getText().trim(); result=null; try { if(baseNameRadioButton.isSelected()){ result=wandora.getTopicMap().getTopicWithBaseName(text); } else if(subjectIdentifierRadioButton.isSelected()){ result=wandora.getTopicMap().getTopic(text); } else{ result=wandora.getTopicMap().getTopicBySubjectLocator(text); } }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION return; } if(result==null){ resultTextArea.setText("Topic not found"); } else{ try{ String resText="Found topic\n"+ "Base name: "+result.getBaseName()+"\n"+ "Subject identifiers:\n"; for(Locator l : result.getSubjectIdentifiers()){ resText+=" "+l.toExternalForm()+"\n"; } if(result.getSubjectLocator()!=null) resText+="Subject locator: "+result.getSubjectLocator().toExternalForm()+"\n"; resultTextArea.setText(resText); }catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION resultTextArea.setText("Exception retrieving topic info"); } } } @Override public Topic getSelectedTopic(){ return result; } @Override public Topic[] getSelectedTopics(){ if(result==null) return new Topic[0]; else return new Topic[]{result}; } @Override public Component getPanel() { return this; } @Override public String getSelectorName(){ return "Select"; } private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed doSearch(); }//GEN-LAST:event_searchButtonActionPerformed private void searchTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchTextFieldKeyTyped if(evt.getKeyCode()==KeyEvent.VK_ENTER){ doSearch(); } }//GEN-LAST:event_searchTextFieldKeyTyped // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JRadioButton baseNameRadioButton; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JPanel radioPanel; private javax.swing.JTextArea resultTextArea; private javax.swing.JButton searchButton; private javax.swing.JLabel searchLabel; private javax.swing.JPanel searchPanel; private javax.swing.JTextField searchTextField; private javax.swing.JRadioButton subjectIdentifierRadioButton; private javax.swing.JRadioButton subjectLocatorRadioButton; // End of variables declaration//GEN-END:variables }
11,754
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SearchTopicsResults.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/search/SearchTopicsResults.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/>. * * * SearchTopicsResults.java * * Created on 30. joulukuuta 2008, 22:23 */ package org.wandora.application.gui.search; import java.awt.BorderLayout; import java.util.Collection; import javax.swing.JScrollPane; import org.wandora.application.Wandora; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.table.MixedTopicTable; /** * * @author akivela */ public class SearchTopicsResults extends javax.swing.JDialog { private static final long serialVersionUID = 1L; private boolean searchAgain = false; /** Creates new form SearchTopicsResults */ public SearchTopicsResults(Wandora wandora, Collection results) { super(wandora, true); initComponents(); if(results != null && results.size() > 0) { MixedTopicTable table = new MixedTopicTable(wandora); table.initialize(results.toArray(new Object[] {} ), null); JScrollPane sp=new JScrollPane(table); resultPanel.add(sp, BorderLayout.CENTER); } else { resultPanel.add(emptyResultSetLabel, BorderLayout.CENTER); } searchAgain = false; this.setSize(800, 600); if(wandora != null) UIBox.centerWindow(this, wandora); } public SearchTopicsResults(Wandora wandora, MixedTopicTable table) { super(wandora, true); initComponents(); if(table != null) { JScrollPane sp=new JScrollPane(table); resultPanel.add(sp, BorderLayout.CENTER); } else { resultPanel.add(emptyResultSetLabel, BorderLayout.CENTER); } searchAgain = false; this.setSize(800, 600); if(wandora != null) UIBox.centerWindow(this, wandora); } // ------ public boolean doSearchAgain() { return searchAgain; } public void hideAgainButton() { this.againButton.setVisible(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. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; emptyResultSetLabel = new org.wandora.application.gui.simple.SimpleLabel(); resultPanel = new javax.swing.JPanel(); buttonPanel = new javax.swing.JPanel(); againButton = new org.wandora.application.gui.simple.SimpleButton(); closeButton = new org.wandora.application.gui.simple.SimpleButton(); emptyResultSetLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); emptyResultSetLabel.setText("<html><p align=\"center\">Found no topics!</p></html>"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Search results"); getContentPane().setLayout(new java.awt.GridBagLayout()); resultPanel.setLayout(new java.awt.BorderLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; getContentPane().add(resultPanel, gridBagConstraints); buttonPanel.setLayout(new java.awt.GridBagLayout()); againButton.setText("Again"); againButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); againButton.setMaximumSize(new java.awt.Dimension(70, 23)); againButton.setMinimumSize(new java.awt.Dimension(70, 23)); againButton.setPreferredSize(new java.awt.Dimension(70, 23)); againButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { againButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 3); buttonPanel.add(againButton, gridBagConstraints); closeButton.setText("Close"); closeButton.setMargin(new java.awt.Insets(2, 2, 2, 2)); closeButton.setMaximumSize(new java.awt.Dimension(70, 23)); closeButton.setMinimumSize(new java.awt.Dimension(70, 23)); closeButton.setPreferredSize(new java.awt.Dimension(70, 23)); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); buttonPanel.add(closeButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 4, 5); getContentPane().add(buttonPanel, gridBagConstraints); pack(); }// </editor-fold>//GEN-END:initComponents private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed searchAgain = false; setVisible(false); }//GEN-LAST:event_closeButtonActionPerformed private void againButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_againButtonActionPerformed searchAgain = true; setVisible(false); }//GEN-LAST:event_againButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton againButton; private javax.swing.JPanel buttonPanel; private javax.swing.JButton closeButton; private javax.swing.JLabel emptyResultSetLabel; private javax.swing.JPanel resultPanel; // End of variables declaration//GEN-END:variables }
6,760
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
QueryPanel.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/search/QueryPanel.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.search; import java.awt.BorderLayout; import java.awt.Desktop; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelListener; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import javax.script.ScriptEngine; import javax.script.ScriptException; import javax.swing.JScrollPane; import javax.swing.table.DefaultTableModel; import org.wandora.application.Wandora; import org.wandora.application.WandoraScriptManager; import org.wandora.application.contexts.Context; import org.wandora.application.contexts.LayeredTopicContext; import org.wandora.application.gui.TopicSelector; 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.SimpleComboBox; import org.wandora.application.gui.simple.SimpleLabel; import org.wandora.application.gui.simple.SimpleScrollPane; import org.wandora.application.gui.simple.SimpleTextPaneResizeable; import org.wandora.application.gui.table.MixedTopicTable; import org.wandora.application.gui.tree.TopicTreePanel; import org.wandora.query2.Directive; import org.wandora.query2.QueryContext; import org.wandora.query2.QueryException; import org.wandora.query2.ResultRow; import org.wandora.query2.Static; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.Options; import org.wandora.utils.Tuples; /** * * @author akivela */ public class QueryPanel extends javax.swing.JPanel implements TopicSelector { private static final long serialVersionUID = 1L; private Wandora wandora = null; private String SCRIPT_QUERY_OPTION_KEY = "scriptQueries"; private List<Tuples.T3<String,String,String>> storedQueryScripts = new ArrayList<Tuples.T3<String,String,String>>(); private MixedTopicTable resultsTable = null; private SimpleLabel message = null; /** * Creates new form QueryPanel */ public QueryPanel() { wandora = Wandora.getWandora(); initComponents(); message = new SimpleLabel(); message.setHorizontalAlignment(SimpleLabel.CENTER); message.setIcon(UIBox.getIcon("gui/icons/warn.png")); scriptTextPane.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); engineComboBox.setEditable(false); List<String> engines=WandoraScriptManager.getAvailableEngines(); engineComboBox.removeAllItems(); for(String e : engines) { if(e != null && e.length() > 0) { engineComboBox.addItem(e); } } queryComboBox.setEditable(false); clearResultsButton.setEnabled(false); readStoredScriptQueries(); } public void removeResultScrollPanesMouseListeners() { MouseWheelListener[] mouseWheelListeners = resultScrollPane.getMouseWheelListeners(); for(MouseWheelListener listener : mouseWheelListeners) { resultScrollPane.removeMouseWheelListener(listener); } } private void readStoredScriptQueries() { storedQueryScripts = new ArrayList<Tuples.T3<String,String,String>>(); if(wandora != null) { Options options = wandora.getOptions(); if(options != null) { int queryCount = 0; String queryScript = null; String queryEngine = null; String queryName = options.get(SCRIPT_QUERY_OPTION_KEY+".query["+queryCount+"].name"); while(queryName != null && queryName.length() > 0) { queryScript = options.get(SCRIPT_QUERY_OPTION_KEY+".query["+queryCount+"].script"); queryEngine = options.get(SCRIPT_QUERY_OPTION_KEY+".query["+queryCount+"].engine"); storedQueryScripts.add( new Tuples.T3(queryName, queryEngine, queryScript) ); queryCount++; queryName = options.get(SCRIPT_QUERY_OPTION_KEY+".query["+queryCount+"].name"); } updateQueryComboBox(); } } } private void writeScriptQueries() { if(wandora != null) { Options options = wandora.getOptions(); if(options != null) { options.removeAll(SCRIPT_QUERY_OPTION_KEY); int queryCount = 0; for( Tuples.T3<String,String,String> storedQuery : storedQueryScripts ) { if(storedQuery != null) { options.put(SCRIPT_QUERY_OPTION_KEY+".query["+queryCount+"].name", storedQuery.e1); options.put(SCRIPT_QUERY_OPTION_KEY+".query["+queryCount+"].engine", storedQuery.e2); options.put(SCRIPT_QUERY_OPTION_KEY+".query["+queryCount+"].script", storedQuery.e3); queryCount++; } } } } } public void updateQueryComboBox() { queryComboBox.removeAllItems(); String name = ""; String script = ""; String engine = ""; for( Tuples.T3<String,String,String> storedQuery : storedQueryScripts ) { if(storedQuery != null) { name = storedQuery.e1; engine = storedQuery.e2; script = storedQuery.e3; queryComboBox.addItem(name); } } queryComboBox.setSelectedItem(name); engineComboBox.setSelectedItem(engine); scriptTextPane.setText(script); } public void addScriptQuery() { String queryName = WandoraOptionPane.showInputDialog(wandora, "Give name for the query script?", "", "Name of the query script"); if(queryName != null && queryName.length() > 0) { String queryEngine = engineComboBox.getSelectedItem().toString(); String queryScript = scriptTextPane.getText(); storedQueryScripts.add( new Tuples.T3(queryName, queryEngine, queryScript) ); writeScriptQueries(); updateQueryComboBox(); } } public void deleteScriptQuery() { int index = queryComboBox.getSelectedIndex(); if(index < storedQueryScripts.size() && index >= 0) { String name = storedQueryScripts.get(index).e1; int a = WandoraOptionPane.showConfirmDialog(wandora, "Would you like to remove query script '"+name+"'?", "Delete query script?"); if(a == WandoraOptionPane.YES_OPTION) { storedQueryScripts.remove(index); writeScriptQueries(); updateQueryComboBox(); } } } public void selectScriptQuery() { int index = queryComboBox.getSelectedIndex(); if(index < storedQueryScripts.size() && index >= 0) { Tuples.T3<String,String,String> query = storedQueryScripts.get(index); // queryComboBox.setSelectedIndex(index); engineComboBox.setSelectedItem(query.e2); scriptTextPane.setText(query.e3); } } public MixedTopicTable getTopicsByQuery(Iterator<Topic> contextTopics) throws ScriptException, TopicMapException, Exception { String engineName = engineComboBox.getSelectedItem().toString(); String scriptStr = scriptTextPane.getText(); return getTopicsByQuery(wandora,engineName,scriptStr,contextTopics); } public static MixedTopicTable getTopicsByQuery(Wandora wandora,TopicMap tm,Directive query,Iterator<Topic> contextTopics) throws QueryException, TopicMapException { ArrayList<ResultRow> res = new ArrayList<>(); if(contextTopics!=null){ while(contextTopics.hasNext()){ Topic t=contextTopics.next(); if(t!=null && !t.isRemoved()) res.add( new ResultRow(t)); } } QueryContext context=new QueryContext(tm, "en"); // System.out.println("Query: "+query.debugString()); if(res.isEmpty()){} else if(res.size()==1){ res=query.doQuery(context, res.get(0)); } else{ res=query.from(new Static(res)).doQuery(context, res.get(0)); } ArrayList<String> columns=new ArrayList<>(); for(ResultRow row : res){ for(int i=0;i<row.getNumValues();i++){ String l=row.getRole(i); if(!columns.contains(l)) columns.add(l); } } ArrayList<Object> columnTopicsA=new ArrayList<>(); for(int i=0;i<columns.size();i++){ String l=columns.get(i); if(l.startsWith("~")){ columns.remove(i); i--; } else{ Topic t=tm.getTopic(l); if(t!=null) columnTopicsA.add(t); else columnTopicsA.add(l); } } Object[] columnTopics=columnTopicsA.toArray(new Object[columnTopicsA.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); ArrayList<String> roles=row.getRoles(); for(int j=0;j<columns.size();j++){ String r=columns.get(j); int ind=roles.indexOf(r); if(ind!=-1) data[i][j]=row.getValue(ind); else data[i][j]=null; } } MixedTopicTable table=new MixedTopicTable(wandora); table.initialize(data,columnTopics); return table; } return null; } public static MixedTopicTable getTopicsByQuery(Wandora wandora,String engineName,String scriptStr,Iterator<Topic> contextTopics) throws ScriptException, TopicMapException, Exception { TopicMap tm = wandora.getTopicMap(); WandoraScriptManager sm = new WandoraScriptManager(); ScriptEngine engine = sm.getScriptEngine(engineName); Directive query = null; Object o=engine.eval(scriptStr); if(o==null) o=engine.get("query"); if(o!=null && o instanceof Directive) { query = (Directive)o; } if(contextTopics==null || !contextTopics.hasNext()){ // if context is empty just add some (root of a tree chooser) topic HashMap<String,TopicTreePanel> trees=wandora.getTopicTreeManager().getTrees(); TopicTreePanel tree=trees.values().iterator().next(); Topic t=tm.getTopic(tree.getRootSI()); ArrayList<Topic> al=new ArrayList<>(); al.add(t); contextTopics=al.iterator(); } return getTopicsByQuery(wandora, wandora.getTopicMap(), query, contextTopics); } public void refresh() { if(resultsTable != null) { ((DefaultTableModel) resultsTable.getModel()).fireTableDataChanged(); } resultPanel.revalidate(); 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; queryPanel = new javax.swing.JPanel(); queryPanelInner = new javax.swing.JPanel(); selectQueryPanel = new javax.swing.JPanel(); queryComboBox = new SimpleComboBox(); addQueryButton = new SimpleButton(); delQueryButton = new SimpleButton(); scriptQueryPanel = new javax.swing.JPanel(); engineLabel = new SimpleLabel(); engineComboBox = new SimpleComboBox(); scriptLabel = new SimpleLabel(); scriptScrollPane = new javax.swing.JScrollPane(); scriptTextPane = new QueryTextPane(); scripButtonPanel = new javax.swing.JPanel(); runButton = new SimpleButton(); clearResultsButton = new SimpleButton(); resultContainerPanel = new javax.swing.JPanel(); resultScrollPane = new SimpleScrollPane(); resultPanel = new javax.swing.JPanel(); setLayout(new java.awt.GridBagLayout()); queryPanel.setLayout(new java.awt.GridBagLayout()); queryPanelInner.setLayout(new java.awt.GridBagLayout()); selectQueryPanel.setLayout(new java.awt.GridBagLayout()); queryComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); queryComboBox.setPreferredSize(new java.awt.Dimension(56, 25)); queryComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { queryComboBoxActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); selectQueryPanel.add(queryComboBox, gridBagConstraints); addQueryButton.setText("Add"); addQueryButton.setMargin(new java.awt.Insets(1, 4, 1, 4)); addQueryButton.setPreferredSize(new java.awt.Dimension(50, 25)); addQueryButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addQueryButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4); selectQueryPanel.add(addQueryButton, gridBagConstraints); delQueryButton.setText("Del"); delQueryButton.setMargin(new java.awt.Insets(1, 4, 1, 4)); delQueryButton.setPreferredSize(new java.awt.Dimension(50, 25)); delQueryButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { delQueryButtonActionPerformed(evt); } }); selectQueryPanel.add(delQueryButton, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 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, 5, 0); queryPanelInner.add(selectQueryPanel, gridBagConstraints); scriptQueryPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); scriptQueryPanel.setLayout(new java.awt.GridBagLayout()); engineLabel.setFont(org.wandora.application.gui.UIConstants.tabFont); engineLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); engineLabel.setText("Engine"); engineLabel.setMinimumSize(new java.awt.Dimension(70, 14)); engineLabel.setPreferredSize(new java.awt.Dimension(70, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(2, 0, 0, 4); scriptQueryPanel.add(engineLabel, gridBagConstraints); engineComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(2, 0, 0, 2); scriptQueryPanel.add(engineComboBox, gridBagConstraints); scriptLabel.setFont(org.wandora.application.gui.UIConstants.tabFont); scriptLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); scriptLabel.setIcon(org.wandora.application.gui.UIBox.getIcon("gui/icons/help_in_context.png")); scriptLabel.setText("Script"); scriptLabel.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT); scriptLabel.setIconTextGap(0); scriptLabel.setMinimumSize(new java.awt.Dimension(70, 14)); scriptLabel.setPreferredSize(new java.awt.Dimension(70, 14)); scriptLabel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { scriptLabelMouseReleased(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; gridBagConstraints.insets = new java.awt.Insets(4, 0, 2, 4); scriptQueryPanel.add(scriptLabel, gridBagConstraints); scriptScrollPane.setMinimumSize(new java.awt.Dimension(23, 100)); scriptScrollPane.setPreferredSize(new java.awt.Dimension(8, 150)); scriptTextPane.setMinimumSize(new java.awt.Dimension(6, 100)); scriptScrollPane.setViewportView(scriptTextPane); 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(2, 0, 2, 2); scriptQueryPanel.add(scriptScrollPane, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; queryPanelInner.add(scriptQueryPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4); queryPanel.add(queryPanelInner, gridBagConstraints); scripButtonPanel.setMaximumSize(new java.awt.Dimension(2147483647, 40)); scripButtonPanel.setMinimumSize(new java.awt.Dimension(83, 40)); scripButtonPanel.setPreferredSize(new java.awt.Dimension(83, 40)); scripButtonPanel.setLayout(new java.awt.GridBagLayout()); runButton.setText("Run query"); runButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { runButtonActionPerformed(evt); } }); scripButtonPanel.add(runButton, new java.awt.GridBagConstraints()); clearResultsButton.setText("Clear results"); clearResultsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearResultsButtonActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0); scripButtonPanel.add(clearResultsButton, 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(5, 5, 5, 5); queryPanel.add(scripButtonPanel, gridBagConstraints); resultContainerPanel.setLayout(new java.awt.BorderLayout()); resultScrollPane.setBorder(null); resultPanel.setLayout(new java.awt.BorderLayout()); resultScrollPane.setViewportView(resultPanel); resultContainerPanel.add(resultScrollPane, java.awt.BorderLayout.CENTER); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; queryPanel.add(resultContainerPanel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(queryPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void queryComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_queryComboBoxActionPerformed if((evt.getModifiers() | ActionEvent.MOUSE_EVENT_MASK) != 0) { selectScriptQuery(); } }//GEN-LAST:event_queryComboBoxActionPerformed private void addQueryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addQueryButtonActionPerformed if((evt.getModifiers() | ActionEvent.MOUSE_EVENT_MASK) != 0) { addScriptQuery(); } }//GEN-LAST:event_addQueryButtonActionPerformed private void delQueryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delQueryButtonActionPerformed if((evt.getModifiers() | ActionEvent.MOUSE_EVENT_MASK) != 0) { deleteScriptQuery(); } }//GEN-LAST:event_delQueryButtonActionPerformed private void scriptLabelMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_scriptLabelMouseReleased try { Desktop desktop = Desktop.getDesktop(); desktop.browse(new URI("http://wandora.org/wiki/Query_language")); } catch(Exception e) { e.printStackTrace(); } }//GEN-LAST:event_scriptLabelMouseReleased private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runButtonActionPerformed // Iterator contextObjects = (new ArrayList()).iterator(); // TODO: Get global context objects and pass them into the getTopicsByQuery. // if(context != null) contextObjects = context.getContextObjects(); Context context = new LayeredTopicContext(); context.initialize(wandora, null, null); Iterator contextObjects = context.getContextObjects(); try { resultPanel.removeAll(); resultScrollPane.setColumnHeaderView(null); clearResultsButton.setEnabled(false); resultsTable = getTopicsByQuery(contextObjects); if(resultsTable != null) { resultScrollPane.setColumnHeaderView(resultsTable.getTableHeader()); // resultPanel.add(resultsTable.getTableHeader(), BorderLayout.NORTH); resultPanel.add(resultsTable, BorderLayout.CENTER); clearResultsButton.setEnabled(true); } else { message.setText("No search results!"); resultPanel.add(message, BorderLayout.CENTER); } } catch(ScriptException se) { message.setText("Script error!"); resultPanel.add(message, BorderLayout.CENTER); revalidate(); repaint(); wandora.handleError(se); } catch(TopicMapException tme) { message.setText("Topic map exception!"); resultPanel.add(message, BorderLayout.CENTER); tme.printStackTrace(); //wandora.handleError(tme); } catch(Exception e) { message.setText("Error!"); resultPanel.add(message, BorderLayout.CENTER); wandora.handleError(e); } revalidate(); repaint(); }//GEN-LAST:event_runButtonActionPerformed private void clearResultsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearResultsButtonActionPerformed resultPanel.removeAll(); resultsTable = null; clearResultsButton.setEnabled(false); revalidate(); repaint(); }//GEN-LAST:event_clearResultsButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addQueryButton; private javax.swing.JButton clearResultsButton; private javax.swing.JButton delQueryButton; private javax.swing.JComboBox engineComboBox; private javax.swing.JLabel engineLabel; private javax.swing.JComboBox queryComboBox; private javax.swing.JPanel queryPanel; private javax.swing.JPanel queryPanelInner; private javax.swing.JPanel resultContainerPanel; private javax.swing.JPanel resultPanel; private javax.swing.JScrollPane resultScrollPane; private javax.swing.JButton runButton; private javax.swing.JPanel scripButtonPanel; private javax.swing.JLabel scriptLabel; private javax.swing.JPanel scriptQueryPanel; private javax.swing.JScrollPane scriptScrollPane; private javax.swing.JTextPane scriptTextPane; private javax.swing.JPanel selectQueryPanel; // End of variables declaration//GEN-END:variables // ------------------------------------------------------- QueryTextPane --- private class QueryTextPane extends SimpleTextPaneResizeable { private int scriptQueryPanelWidth = 100; private int scriptQueryPanelHeight = scriptQueryPanel.getHeight(); public QueryTextPane() { super(); try { //JavaScriptSyntaxKit syntaxKit = new JavaScriptSyntaxKit(); //syntaxKit.install(this); //DefaultSyntaxKit.initKit(); //setContentType("text/javascript"); } catch(Exception e) { e.printStackTrace(); } } @Override public void mouseDragged(MouseEvent e) { Point p = e.getPoint(); if(mousePressedInTriangle) { inTheTriangleZone = true; int yDiff = (mousePressedPoint.y - p.y); newSize = new Dimension(100, sizeAtPress.height - yDiff); JScrollPane sp = getScrollPane(); if(scrollPane != null) { sp.getViewport().setSize(newSize); sp.getViewport().setPreferredSize(newSize); sp.getViewport().setMinimumSize(newSize); sp.setSize(newSize); sp.setPreferredSize(newSize); sp.setMinimumSize(newSize); } scriptQueryPanel.setSize(scriptQueryPanelWidth, scriptQueryPanelHeight - yDiff); scriptQueryPanel.revalidate(); scriptQueryPanel.repaint(); } } @Override public void mousePressed(MouseEvent e) { super.mousePressed(e); if(mousePressedInTriangle) { scriptQueryPanelHeight = scriptQueryPanel.getHeight(); } } } // ------------------------------------------------------- TopicSelector --- @Override public Topic getSelectedTopic() { if(resultsTable != null) { Topic[] topics = resultsTable.getSelectedTopics(); if(topics != null && topics.length > 0) { return topics[0]; } } return null; } @Override public Topic[] getSelectedTopics() { if(resultsTable != null) { resultsTable.getSelectedTopics(); } return null; } @Override public java.awt.Component getPanel() { return this; } @Override public String getSelectorName() { return "Query"; } @Override public void init() { } @Override public void cleanup() { } }
29,483
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SearchTable.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/gui/search/SearchTable.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/>. * * * SearchTable.java * * Created on 27. joulukuuta 2005, 20:57 * */ package org.wandora.application.gui.search; import java.awt.Component; import java.awt.Font; import javax.swing.AbstractCellEditor; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellEditor; import javax.swing.table.TableColumn; import org.wandora.application.Wandora; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMapException; import org.wandora.utils.swing.TableSorter; /** * @author akivela */ public class SearchTable extends JTable { private static final long serialVersionUID = 1L; private Object[][] data; private TableSorter sorter; private Wandora wandora; private String[] res; private JDialog dialog; /** Creates a new instance of SearchTable */ public SearchTable(String[] res, Wandora parent, JDialog dialog) { this.wandora=parent; this.res=res; this.dialog=dialog; data=new Object[res.length/3][2]; for(int i=0;i<res.length/3;i++){ try { data[i][0]=Double.valueOf(res[i*3]); } catch (Exception e) { data[i][0]=Double.valueOf( 0 ); } data[i][1]=res[i*3+2]; } this.setColumnSelectionAllowed(false); this.setRowSelectionAllowed(false); sorter=new TableSorter(new SearchTableModel()); this.setAutoCreateColumnsFromModel(false); this.setModel(sorter); TableColumn column=new TableColumn(0,80,null,null); column.setMaxWidth(80); this.addColumn(column); this.addColumn(new TableColumn(1,80,null,new TopicCellEditor())); sorter.setTableHeader(this.getTableHeader()); } @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==0) return null; else return sorter.getValueAt(row,realCol).toString(); } private class TopicCellEditor extends AbstractCellEditor implements TableCellEditor, java.awt.event.MouseListener { private int topic; private JLabel label; public TopicCellEditor(){ label= new JLabel(); Font f=label.getFont(); label.setFont(new Font(f.getName(),Font.PLAIN,f.getSize())); label.addMouseListener(this); } @Override public Object getCellEditorValue() { return res[topic*3+2]; } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { topic=sorter.modelIndex(row); label.setText(res[topic*3+2]); return label; } @Override public void mouseReleased(java.awt.event.MouseEvent e) { fireEditingStopped(); if(label.contains(e.getPoint())){ try { Topic t=wandora.getTopicMap().getTopic(res[topic*3+1]); dialog.setVisible(false); if(t!=null) wandora.openTopic(t); } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION dialog.setVisible(false); } } } @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 SearchTableModel extends AbstractTableModel { @Override public int getColumnCount() { return 2; } @Override public int getRowCount() { return res.length/3; } @Override public Object getValueAt(int rowIndex, int columnIndex) { return data[rowIndex][columnIndex]; } @Override public String getColumnName(int columnIndex){ if(columnIndex==0) return "Score"; else return "Topic"; } @Override public boolean isCellEditable(int row,int col){ if(col==1) return true; else return false; } } }
5,511
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RoleContextCollected.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/RoleContextCollected.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/>. * * * RoleContextCollected.java * * Created on 8. huhtikuuta 2006, 21:07 */ package org.wandora.application.contexts; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; /** * @author akivela */ public class RoleContextCollected extends AssociationContext implements Context { /** * Creates a new instance of RoleContextCollected */ public RoleContextCollected() { } @Override public Iterator getContextObjects() { return getRolesOf( super.getContextObjects() ); } public Iterator getRolesOf(Iterator associations) { if(associations == null) return null; List<Topic> contextTopics = new ArrayList<>(); Association association = null; Collection<Topic> roleTopics = null; Topic roleTopic = null; while(associations.hasNext()) { try { association = (Association) associations.next(); if(association == null) continue; roleTopics = association.getRoles(); if(roleTopics != null && roleTopics.size() > 0) { for(Iterator roleIterator = roleTopics.iterator(); roleIterator.hasNext(); ) { try { roleTopic = (Topic) roleIterator.next(); if(removeDuplicates) { if( !contextTopics.contains(roleTopic) ) { contextTopics.add( roleTopic ); } } else { contextTopics.add( roleTopic ); } } catch(Exception e) { log(e); } } } } catch(Exception e) { log(e); } } return contextTopics.iterator(); } }
2,958
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
SIContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/SIContext.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/>. * * * SIContext.java * * Created on 23. lokakuuta 2007, 12:49 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.swing.table.JTableHeader; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.simple.TopicLinkBasename; import org.wandora.application.gui.table.LocatorTable; import org.wandora.application.gui.table.TopicTable; import org.wandora.application.gui.topicpanels.GraphTopicPanel; import org.wandora.application.gui.tree.TopicTree; import org.wandora.application.gui.tree.TopicTreePanel; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class SIContext implements Context { private Object contextSource; protected WandoraTool contextOwner = null; protected ActionEvent actionEvent = null; protected Wandora wandora = null; /** Creates a new instance of SIContext */ public SIContext() { } public SIContext(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { initialize(wandora, actionEvent, contextOwner); } @Override public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { this.wandora = wandora; this.actionEvent = actionEvent; this.contextOwner = contextOwner; Object proposedContextSource = UIBox.getActionsRealSource(actionEvent); if( !isContextSource(proposedContextSource) ) { proposedContextSource = wandora.getFocusOwner(); if( !isContextSource(proposedContextSource) ) { proposedContextSource = wandora; } } setContextSource( proposedContextSource ); } @Override public ActionEvent getContextEvent() { return actionEvent; } @Override public Iterator getContextObjects() { return getContextObjects( getContextSource() ); } public void digSIs(List<Locator> locators, Topic topic) { if(topic == null) return; try { Collection<Locator> sis = topic.getSubjectIdentifiers(); for(Iterator<Locator> i=sis.iterator(); i.hasNext(); ) { locators.add(i.next()); } } catch(Exception e) { e.printStackTrace(); } } public void digSIs(List<Locator> locators, Collection<Topic> topics) { if(topics == null) return; for(Iterator<Topic> i=topics.iterator(); i.hasNext(); ) { digSIs(locators, (Topic) i.next()); } } public Iterator getContextObjects(Object contextSource) { if(contextSource == null) return null; List<Locator> contextLocators = new ArrayList<>(); if(contextSource instanceof LocatorTable) { try { Locator[] selection = ((LocatorTable) contextSource).getSelectedLocators(); contextLocators.addAll(Arrays.asList(selection)); } catch (Exception e) { log(e); } } else if(contextSource instanceof Wandora) { try { Wandora w = (Wandora) contextSource; Topic currentTopic = w.getOpenTopic(); if(currentTopic != null) { digSIs(contextLocators, currentTopic); } } catch (Exception e) { log(e); } } else if(contextSource instanceof TopicLinkBasename) { try { digSIs(contextLocators, ((TopicLinkBasename) contextSource).getTopic()); } catch (Exception e) { log(e); } } else if(contextSource instanceof Topic) { digSIs(contextLocators, (Topic) contextSource ); } else if(contextSource instanceof Topic[]) { Topic[] topicArray = (Topic[]) contextSource; for(int i=0; i<topicArray.length; i++) { digSIs(contextLocators, topicArray[i] ); } } else if(contextSource instanceof GraphTopicPanel) { digSIs(contextLocators, ((GraphTopicPanel) contextSource).getContextTopics() ); } else if(contextSource instanceof TopicTable) { Topic[] topicArray = ((TopicTable) contextSource).getSelectedTopics(); for(int i=0; i<topicArray.length; i++) { digSIs(contextLocators, topicArray[i] ); } } else if(contextSource instanceof JTableHeader) { if(((JTableHeader) contextSource).getTable() instanceof TopicTable) { TopicTable topicTable = (TopicTable) ((JTableHeader) contextSource).getTable(); digSIs(contextLocators, topicTable.getSelectedHeaderTopic() ); } } else if(contextSource instanceof TopicTreePanel) { digSIs(contextLocators, ((TopicTreePanel) contextSource).getSelection() ); } else if(contextSource instanceof TopicTree) { TopicTree tree = (TopicTree) contextSource; if( tree.getSelection() instanceof Topic ) { digSIs(contextLocators, tree.getSelection() ); } } /* else if(contextSource instanceof LayerStatusPanel) { try { Iterator i = ((LayerStatusPanel) contextSource).getLayer().getTopicMap().getTopics(); return i; } catch(Exception e) { log(e); } } else if(contextSource instanceof TopicMap) { TopicMap topicmap = (TopicMap) contextSource; try { digSIs(contextLocators, topicmap.getTopics()); } catch(TopicMapException tme){ log(tme); } } **/ return contextLocators.iterator(); } @Override public void setContextSource(Object proposedContextSource) { if(isContextSource(proposedContextSource)) { contextSource = proposedContextSource; } else { contextSource = null; } } public boolean isContextSource(Object contextSource) { if(contextSource != null && ( contextSource instanceof LocatorTable || contextSource instanceof Wandora || contextSource instanceof TopicLinkBasename || contextSource instanceof Topic || contextSource instanceof Topic[] || contextSource instanceof GraphTopicPanel || contextSource instanceof TopicTable || contextSource instanceof TopicTreePanel || contextSource instanceof TopicTree || // contextSource instanceof LayerStatusPanel || contextSource instanceof JTableHeader && ((JTableHeader) contextSource).getTable() instanceof TopicTable)) { return true; } return false; } @Override public Object getContextSource() { return contextSource; } // ------------------------------------------------------------------------- public void log(Exception e) { if(contextOwner != null) contextOwner.log(e); else e.printStackTrace(); } }
8,549
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/TopicContext.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/>. * * * TopicContext.java * * Created on 7.6.2006, 18:23 * */ package org.wandora.application.contexts; import java.util.Iterator; import org.wandora.application.contexts.iterators.TopicIteratorForCurrentLayer; /** * * @author akivela */ public class TopicContext extends LayeredTopicContext implements Context { @Override public Iterator getContextObjects() { TopicIteratorForCurrentLayer iterator = new TopicIteratorForCurrentLayer(); iterator.initialize(super.getContextObjects(), wandora); return iterator; } }
1,375
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PlayerContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/PlayerContext.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/>. * * * PlayerContext.java * * Created on 13. huhtikuuta 2006, 11:33 */ package org.wandora.application.contexts; import java.util.Iterator; import org.wandora.application.contexts.iterators.PlayerIterator; /** * * @author akivela */ public class PlayerContext extends LayeredTopicContext implements Context { @Override public Iterator getContextObjects() { PlayerIterator iterator = new PlayerIterator(); iterator.initialize(super.getContextObjects(), wandora); return iterator; } }
1,335
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApplicationlessContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/ApplicationlessContext.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/>. * * * ApplicationlessContext.java * * Created on 22. huhtikuuta 2006, 11:15 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; /** * * @author akivela */ public class ApplicationlessContext extends LayeredTopicContext { /** * Creates a new instance of ApplicationlessContext */ public ApplicationlessContext() { } @Override public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { this.wandora = wandora; this.actionEvent = actionEvent; this.contextOwner = contextOwner; Object proposedContextSource = UIBox.getActionsRealSource(actionEvent); setContextSource( proposedContextSource ); } @Override public Iterator getContextObjects() { Object contextSource = getContextSource(); if(contextSource != null && !(contextSource instanceof Wandora)) { return getContextObjects( getContextSource() ); } else { return null; } } }
2,042
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ClassContextCollected.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/ClassContextCollected.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/>. * * * ClassContextCollected.java * * Created on 8. huhtikuuta 2006, 20:04 * */ package org.wandora.application.contexts; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class ClassContextCollected extends LayeredTopicContext implements Context { public boolean removeDuplicates = true; /** * Creates a new instance of ClassContextCollected */ public ClassContextCollected() { } @Override public Iterator getContextObjects() { return getClassesOf( super.getContextObjects() ); } public Iterator getClassesOf(Iterator topics) { if(topics == null) return null; List<Topic> contextTopics = new ArrayList<>(); Collection<Topic> classTopics = null; Topic topic = null; Topic classTopic = null; while(topics.hasNext()) { try { topic = (Topic) topics.next(); if(topic == null) continue; if(removeDuplicates) { classTopics = topic.getTypes(); for(Iterator<Topic> classIterator = classTopics.iterator(); classIterator.hasNext(); ) { classTopic = classIterator.next(); if(classTopic != null && !contextTopics.contains(classTopic)) { contextTopics.add(classTopic); } } } else { contextTopics.addAll( topic.getTypes() ); } } catch(Exception e) { log(e); } } return contextTopics.iterator(); } }
2,633
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PreContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/PreContext.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/>. * * * PreContext.java * * Created on 15. elokuuta 2006, 20:42 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class PreContext implements Context { private Object contextSource; protected WandoraTool contextOwner = null; protected ActionEvent actionEvent = null; protected Wandora wandora = null; private Collection<Object> contextObjects; /** Creates a new instance of PreContext */ public PreContext(Locator locator) { contextObjects = new ArrayList<>(); contextObjects.add(locator); } public PreContext(Locator[] locators) { contextObjects = new ArrayList<>(); contextObjects.addAll(Arrays.asList(locators)); } public PreContext(Topic locator) { contextObjects = new ArrayList<>(); contextObjects.add(locator); } public PreContext(Topic[] locators) { contextObjects = new ArrayList<>(); contextObjects.addAll(Arrays.asList(locators)); } // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- @Override public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { this.wandora = wandora; this.actionEvent = actionEvent; this.contextOwner = contextOwner; } /** * Returns Iterator for accessible object in context ie. object the tool may * modify or otherwise access. Generally returned iterator contains Topic(s) found in * the GUI element that originated tool's action event. * * @return <tt>Iterator</tt> containing all the context objects. */ @Override public Iterator getContextObjects() { return new Iterator() { Iterator iterator = contextObjects.iterator(); Object next = solveNext(); @Override public boolean hasNext() { if(next == null) return false; return true; } @Override public Object next() { Object current = next; next = solveNext(); return current; } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } private Object solveNext() { if(iterator != null && iterator.hasNext()) { try { Object o = iterator.next(); if(o instanceof Topic) { return o; } if(o instanceof Locator) { return wandora.getTopicMap().getTopic((Locator) o); } } catch(Exception e) { e.printStackTrace(); } } return null; } }; } /** * Sets the origin of context. Normally context origin is a GUI element * that triggered the tool execution. */ @Override public void setContextSource(Object contextSource) { // DO NOTHING } /** * Returns the origin of context. Normally context origin is a GUI element * that triggered the tool execution. <code>PreContext</pre> has no context * source as the context is set during construction. */ @Override public Object getContextSource() { return null; } @Override public ActionEvent getContextEvent() { return actionEvent; } }
5,041
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GraphAllNodesContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/GraphAllNodesContext.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/>. * * * GraphAllNodesContext.java * * Created on 14.6.2007, 13:18 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.topicpanels.GraphTopicPanel; import org.wandora.application.gui.topicpanels.TopicPanel; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; /** * * @author akivela */ public class GraphAllNodesContext implements Context { private Object contextSource; protected WandoraTool contextOwner = null; protected ActionEvent actionEvent = null; protected Wandora wandora = null; /** Creates a new instance of GraphAllNodesContext */ public GraphAllNodesContext() { } @Override public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { this.wandora = wandora; this.actionEvent = actionEvent; this.contextOwner = contextOwner; Object proposedContextSource = UIBox.getActionsRealSource(actionEvent); if( !isContextSource(proposedContextSource) ) { proposedContextSource = wandora.getFocusOwner(); if( !isContextSource(proposedContextSource) ) { proposedContextSource = wandora; } } setContextSource( proposedContextSource ); } @Override public ActionEvent getContextEvent() { return actionEvent; } @Override public Iterator getContextObjects() { return getContextObjects( getContextSource() ); } public Iterator getContextObjects(Object contextSource) { if(contextSource == null) return null; List<VNode> contextNodes = new ArrayList<>(); if(contextSource instanceof Wandora) { try { Wandora w = (Wandora) contextSource; TopicPanel currentTopicPanel = w.getTopicPanel(); if(currentTopicPanel instanceof GraphTopicPanel) { contextNodes.addAll( ((GraphTopicPanel) currentTopicPanel).getGraphPanel().getModel().getNodes() ); } } catch (Exception e) { log(e); } } else if(contextSource instanceof GraphTopicPanel) { contextNodes.addAll( ((GraphTopicPanel) contextSource).getGraphPanel().getModel().getNodes() ); } else if(contextSource instanceof TopicMapGraphPanel) { contextNodes.addAll( ((TopicMapGraphPanel) contextSource).getModel().getNodes() ); } return contextNodes.iterator(); } @Override public void setContextSource(Object proposedContextSource) { if(isContextSource(proposedContextSource)) { contextSource = proposedContextSource; } else { contextSource = null; } } public boolean isContextSource(Object contextSource) { if(contextSource != null && ( contextSource instanceof Wandora || contextSource instanceof GraphTopicPanel) ) { return true; } return false; } @Override public Object getContextSource() { return contextSource; } // ------------------------------------------------------------------------- public void log(Exception e) { if(contextOwner != null) contextOwner.log(e); else e.printStackTrace(); } }
4,625
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApplicationAssociationContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/ApplicationAssociationContext.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/>. * * * ApplicationAssociationContext.java * * Created on 23. huhtikuuta 2006, 13:38 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class ApplicationAssociationContext implements Context { private Object contextSource; protected WandoraTool contextOwner = null; protected ActionEvent actionEvent = null; protected Wandora wandora = null; /** Creates a new instance of ApplicationAssociationContext */ public ApplicationAssociationContext() { } @Override public Iterator getContextObjects() { List<Association> contextAssociations = new ArrayList<>(); try { Wandora w = (Wandora) contextSource; Topic currentTopic = w.getOpenTopic(); if(currentTopic != null) { return currentTopic.getAssociations().iterator(); } } catch (Exception e) { log(e); } return contextAssociations.iterator(); } @Override public ActionEvent getContextEvent() { return actionEvent; } @Override public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { this.wandora = wandora; this.actionEvent = actionEvent; this.contextOwner = contextOwner; setContextSource( wandora ); } @Override public void setContextSource(Object proposedContextSource) { contextSource = proposedContextSource; } @Override public Object getContextSource() { return contextSource; } // ------------------------------------------------------------------------- public void log(Exception e) { if(contextOwner != null) contextOwner.log(e); else e.printStackTrace(); } }
2,972
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
LayeredTopicContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/LayeredTopicContext.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/>. * * * LayeredTopicContext.java * * Created on 7. huhtikuuta 2006, 13:47 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import javax.swing.table.JTableHeader; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.LayerTree; import org.wandora.application.gui.OccurrenceTable; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.simple.TopicLinkBasename; import org.wandora.application.gui.table.MixedTopicTable; import org.wandora.application.gui.table.SITable; import org.wandora.application.gui.table.TopicGrid; import org.wandora.application.gui.table.TopicTable; import org.wandora.application.gui.texteditor.OccurrenceTextEditor; import org.wandora.application.gui.topicpanels.GraphTopicPanel; import org.wandora.application.gui.topicpanels.webview.WebViewPanel; import org.wandora.application.gui.tree.TopicTree; import org.wandora.application.gui.tree.TopicTreePanel; import org.wandora.topicmap.Locator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; import org.wandora.topicmap.layered.Layer; /** * This is basic context for topics. LayeredTopicContext is used to pass topics into tools * from various UI components of Wandora application. * * @author akivela */ public class LayeredTopicContext implements Context { private Object contextSource; protected WandoraTool contextOwner = null; protected ActionEvent actionEvent = null; protected Wandora wandora = null; /** * Creates a new instance of LayeredTopicContext */ public LayeredTopicContext() { // Nothing here } public LayeredTopicContext(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { initialize(wandora, actionEvent, contextOwner); } @Override public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { this.wandora = wandora; this.actionEvent = actionEvent; this.contextOwner = contextOwner; Object proposedContextSource = UIBox.getActionsRealSource(actionEvent); if( !isContextSource(proposedContextSource) ) { proposedContextSource = wandora.getFocusOwner(); if( !isContextSource(proposedContextSource) ) { proposedContextSource = wandora; } } // *** IF CONTEXT WAS WANDORA THEN TRY TO SOLVE WANDORA'S FOCUS OWNER *** else { if( proposedContextSource instanceof Wandora ) { Object wandoraRegisteredContext = ((Wandora) proposedContextSource).getFocusOwner(); if( isContextSource(wandoraRegisteredContext) ) { proposedContextSource = wandoraRegisteredContext; } } } setContextSource( proposedContextSource ); } @Override public ActionEvent getContextEvent() { return actionEvent; } @Override public Iterator getContextObjects() { return getContextObjects( getContextSource() ); } public Iterator getContextObjects(Object contextSource) { if(contextSource == null) return null; List<Topic> contextTopics = new ArrayList<>(); // ***** Wandora ***** if(contextSource instanceof Wandora) { try { Wandora wandora = (Wandora) contextSource; Topic currentTopic = wandora.getOpenTopic(); if(currentTopic != null) { contextTopics.add(currentTopic); } } catch (Exception e) { log(e); } } // ***** TopicLinkBasename ***** else if(contextSource instanceof TopicLinkBasename) { try { contextTopics.add( ((TopicLinkBasename) contextSource).getTopic() ); } catch (Exception e) { log(e); } } // ***** Topic ***** else if(contextSource instanceof Topic) { contextTopics.add( (Topic) contextSource ); } // ***** Topic[] ***** else if(contextSource instanceof Topic[]) { Topic[] topicArray = (Topic[]) contextSource; contextTopics.addAll(Arrays.asList(topicArray)); } // ***** GraphTopicPanel ***** else if(contextSource instanceof GraphTopicPanel) { contextTopics.addAll( ((GraphTopicPanel) contextSource).getContextTopics() ); } // ***** WebViewPanel ***** else if(contextSource instanceof WebViewPanel) { try { contextTopics.add( ((WebViewPanel) contextSource).getTopic()); } catch(Exception e) { /*Ignore*/ } } // ***** TopicTable ***** else if(contextSource instanceof TopicTable) { Topic[] topicArray = ((TopicTable) contextSource).getSelectedTopics(); contextTopics.addAll(Arrays.asList(topicArray)); } // ***** TopicGrid ***** else if(contextSource instanceof TopicGrid) { Topic[] topicArray = ((TopicGrid) contextSource).getSelectedTopics(); contextTopics.addAll(Arrays.asList(topicArray)); } // ***** MixedTopicTable ***** else if(contextSource instanceof MixedTopicTable) { Topic[] topicArray = ((MixedTopicTable) contextSource).getSelectedTopics(); contextTopics.addAll(Arrays.asList(topicArray)); } // ***** JTableHeader ***** else if(contextSource instanceof JTableHeader) { if(((JTableHeader) contextSource).getTable() instanceof TopicTable) { TopicTable topicTable = (TopicTable) ((JTableHeader) contextSource).getTable(); contextTopics.add( topicTable.getSelectedHeaderTopic() ); } } // ***** TopicTreePanel ***** else if(contextSource instanceof TopicTreePanel) { contextTopics.add(((TopicTreePanel) contextSource).getSelection() ); } // ***** TopicTree ***** else if(contextSource instanceof TopicTree) { TopicTree tree = (TopicTree) contextSource; if( tree.getSelection() instanceof Topic ) { contextTopics.add( tree.getSelection() ); } } // ***** LayerTree ***** else if(contextSource instanceof LayerTree) { TopicMap atm = wandora.getTopicMap(); LayerTree layerTree=(LayerTree)contextSource; Layer l=layerTree.getLastClickedLayer(); TopicMap tm = null; if(l==null) { tm = wandora.getTopicMap(); } else { tm = l.getTopicMap(); } try { Iterator<Topic> topics = tm.getTopics(); Topic t = null; while(topics.hasNext()) { t = (Topic) topics.next(); if(t != null && !t.isRemoved()) { Topic t2 = atm.getTopic(t.getOneSubjectIdentifier()); if(t2 != null && !t2.isRemoved()) { contextTopics.add(t2); } } } } catch(Exception e) { log(e); } } // ***** Layer ***** else if(contextSource instanceof Layer){ TopicMap topicmap = ((Layer)contextSource).getTopicMap(); try { TopicMap tm = wandora.getTopicMap(); Iterator<Topic> topics = topicmap.getTopics(); Topic t = null; while(topics.hasNext()) { t = (Topic) topics.next(); if(t != null && !t.isRemoved()) { Topic t2 = tm.getTopic(t.getOneSubjectIdentifier()); if(t2 != null && !t2.isRemoved()) { contextTopics.add(t2); } } } } catch(TopicMapException tme){ log(tme); } } // ***** SITable ***** else if(contextSource instanceof SITable) { Locator[] locators = ((SITable) contextSource).getSelectedLocators(); TopicMap topicmap = wandora.getTopicMap(); Topic t = null; for(int i=0; i<locators.length; i++) { try { t = topicmap.getTopic(locators[i]); if(!contextTopics.contains(t)) { contextTopics.add(t); } } catch(Exception e) { log(e); } } } // ***** TopicMap ***** else if(contextSource instanceof TopicMap) { TopicMap topicmap = (TopicMap) contextSource; try { TopicMap tm = wandora.getTopicMap(); Iterator<Topic> topics = topicmap.getTopics(); Topic t = null; while(topics.hasNext()) { t = (Topic) topics.next(); if(t != null && !t.isRemoved()) { Topic t2 = tm.getTopic(t.getOneSubjectIdentifier()); if(t2 != null && !t2.isRemoved()) { contextTopics.add(t2); } } } } catch(TopicMapException tme){ log(tme); } } // ***** OccurrenceTable ***** else if(contextSource instanceof OccurrenceTable) { OccurrenceTable otable = (OccurrenceTable) contextSource; contextTopics.add(otable.getTopic()); } // ***** OccurrenceTextEditor ***** else if(contextSource instanceof OccurrenceTextEditor) { OccurrenceTextEditor editor = (OccurrenceTextEditor) contextSource; contextTopics.add(editor.getOccurrenceTopic()); } return contextTopics.iterator(); } @Override public void setContextSource(Object proposedContextSource) { if(isContextSource(proposedContextSource)) { contextSource = proposedContextSource; } else { contextSource = null; } } public boolean isContextSource(Object contextSource) { if(contextSource != null && ( contextSource instanceof Wandora || contextSource instanceof TopicLinkBasename || contextSource instanceof Topic || contextSource instanceof Topic[] || contextSource instanceof GraphTopicPanel || contextSource instanceof WebViewPanel || contextSource instanceof TopicTable || contextSource instanceof TopicGrid || contextSource instanceof MixedTopicTable || contextSource instanceof OccurrenceTable || contextSource instanceof OccurrenceTextEditor || contextSource instanceof TopicTreePanel || contextSource instanceof TopicTree || contextSource instanceof SITable || contextSource instanceof LayerTree || contextSource instanceof Layer || contextSource instanceof JTableHeader && ((JTableHeader) contextSource).getTable() instanceof TopicTable)) { return true; } return false; } @Override public Object getContextSource() { return contextSource; } // ------------------------------------------------------------------------- public void log(Exception e) { if(contextOwner != null) contextOwner.log(e); else e.printStackTrace(); } }
13,292
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
InstanceContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/InstanceContext.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/>. * * * InstanceContext.java * * Created on 8. huhtikuuta 2006, 12:24 * */ package org.wandora.application.contexts; import java.util.Iterator; import org.wandora.application.contexts.iterators.InstanceIterator; /** * @author akivela */ public class InstanceContext extends LayeredTopicContext implements Context { @Override public Iterator getContextObjects() { InstanceIterator instanceIterator = new InstanceIterator(); instanceIterator.initialize(super.getContextObjects(), wandora); return instanceIterator; } }
1,369
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PlayerContextCollected.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/PlayerContextCollected.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/>. * * * PlayerContextCollected.java * * Created on 8. huhtikuuta 2006, 20:15 * */ package org.wandora.application.contexts; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; /** * @author akivela */ public class PlayerContextCollected extends AssociationContext implements Context { /** * Creates a new instance of PlayerContextCollected */ public PlayerContextCollected() { } @Override public Iterator getContextObjects() { return getPlayersOf( super.getContextObjects() ); } public Iterator getPlayersOf(Iterator associations) { if(associations == null) return null; List<Topic> contextTopics = new ArrayList<>(); Association association = null; Collection<Topic> roleTopics = null; Topic playerTopic = null; Topic roleTopic = null; while(associations.hasNext()) { try { association = (Association) associations.next(); if(association == null) continue; roleTopics = association.getRoles(); if(roleTopics != null && roleTopics.size() > 0) { for(Iterator<Topic> roleIterator = roleTopics.iterator(); roleIterator.hasNext(); ) { try { roleTopic = (Topic) roleIterator.next(); playerTopic = association.getPlayer(roleTopic); if(playerTopic == null) continue; if(removeDuplicates) { if( !contextTopics.contains(playerTopic) ) { contextTopics.add( playerTopic ); } } else { contextTopics.add( playerTopic ); } } catch(Exception e) { log(e); } } } } catch(Exception e) { log(e); } } return contextTopics.iterator(); } }
3,170
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
InstanceContextCollected.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/InstanceContextCollected.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/>. * * * InstanceContextCollected.java * * Created on 13. huhtikuuta 2006, 9:45 * */ package org.wandora.application.contexts; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public class InstanceContextCollected extends LayeredTopicContext implements Context { public static final int GATHER_TOPICS_FROM_LAYERSTACK = 1; public static final int GATHER_TOPICS_FROM_OWNER_TOPICMAP = 2; public int gatherStyle = GATHER_TOPICS_FROM_LAYERSTACK; public boolean removeDuplicates = true; @Override public Iterator getContextObjects() { return collectInstancesOf( super.getContextObjects() ); } public Iterator collectInstancesOf(Iterator topics) { if(topics == null) return null; List<Topic> contextTopics = new ArrayList<>(); Collection<Topic> instanceTopics = null; Topic topic = null; Topic instance = null; TopicMap topicmap = null; if(gatherStyle == GATHER_TOPICS_FROM_LAYERSTACK) { topicmap = this.wandora.getTopicMap(); } while(topics.hasNext()) { try { topic = (Topic) topics.next(); if(topic == null) continue; if(gatherStyle == GATHER_TOPICS_FROM_OWNER_TOPICMAP) { topicmap = topic.getTopicMap(); } if(removeDuplicates) { instanceTopics = topicmap.getTopicsOfType(topic); for(Iterator<Topic> instanceIterator = instanceTopics.iterator(); instanceIterator.hasNext(); ) { instance = instanceIterator.next(); if(instance != null && !contextTopics.contains(instance)) { contextTopics.add(instance); } } } else { contextTopics.addAll( topicmap.getTopicsOfType(topic) ); } } catch(Exception e) { log(e); } } return contextTopics.iterator(); } }
3,102
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AssociationTypeContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/AssociationTypeContext.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/>. * * * AssociationTypeContext.java * * Created on 13. huhtikuuta 2006, 12:00 * */ package org.wandora.application.contexts; import java.util.Iterator; import org.wandora.application.contexts.iterators.AssociationTypeIterator; /** * * @author akivela */ public class AssociationTypeContext extends LayeredTopicContext implements Context { @Override public Iterator getContextObjects() { AssociationTypeIterator iterator = new AssociationTypeIterator(); iterator.initialize(super.getContextObjects(), wandora); return iterator; } }
1,385
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GraphEdgeContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/GraphEdgeContext.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/>. * * * GraphEdgeContext.java * * Created on 13.6.2007, 15:58 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.topicpanels.DockingFramePanel; import org.wandora.application.gui.topicpanels.GraphTopicPanel; import org.wandora.application.gui.topicpanels.TopicPanel; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VEdge; /** * * @author akivela */ public class GraphEdgeContext implements Context { private Object contextSource; protected WandoraTool contextOwner = null; protected ActionEvent actionEvent = null; protected Wandora wandora = null; /** Creates a new instance of GraphEdgeContext */ public GraphEdgeContext() { } @Override public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { this.wandora = wandora; this.actionEvent = actionEvent; this.contextOwner = contextOwner; Object proposedContextSource = UIBox.getActionsRealSource(actionEvent); if( !isContextSource(proposedContextSource) ) { proposedContextSource = wandora.getFocusOwner(); if( !isContextSource(proposedContextSource) ) { proposedContextSource = wandora; } } setContextSource( proposedContextSource ); } @Override public ActionEvent getContextEvent() { return actionEvent; } @Override public Iterator getContextObjects() { return getContextObjects( getContextSource() ); } public Iterator getContextObjects(Object contextSource) { if(contextSource == null) return null; List<VEdge> contextEdges = new ArrayList<>(); if(contextSource instanceof Wandora) { try { Wandora w = (Wandora) contextSource; TopicPanel currentTopicPanel = w.getTopicPanel(); if(currentTopicPanel != null && currentTopicPanel instanceof DockingFramePanel) { currentTopicPanel = ((DockingFramePanel) currentTopicPanel).getCurrentTopicPanel(); } if(currentTopicPanel != null && currentTopicPanel instanceof GraphTopicPanel) { contextEdges.addAll( ((GraphTopicPanel) currentTopicPanel).getGraphPanel().getSelectedEdges() ); if(contextEdges.isEmpty()) { //contextEdges.add( ((GraphTopicPanel) currentTopicPanel).getGraphPanel().getMouseOverEdge() ); } } if(currentTopicPanel != null && currentTopicPanel instanceof TopicMapGraphPanel) { contextEdges.addAll( ((TopicMapGraphPanel) currentTopicPanel).getSelectedEdges() ); if(contextEdges.isEmpty()) { //contextEdges.add( ((TopicMapGraphPanel) currentTopicPanel).getMouseOverEdge() ); } } } catch (Exception e) { log(e); } } else if(contextSource instanceof GraphTopicPanel) { contextEdges.addAll( ((GraphTopicPanel) contextSource).getGraphPanel().getSelectedEdges() ); } else if(contextSource instanceof TopicMapGraphPanel) { contextEdges.addAll( ((TopicMapGraphPanel) contextSource).getSelectedEdges() ); } return contextEdges.iterator(); } @Override public void setContextSource(Object proposedContextSource) { if(isContextSource(proposedContextSource)) { contextSource = proposedContextSource; } else { contextSource = null; } } public boolean isContextSource(Object contextSource) { if(contextSource != null && ( contextSource instanceof Wandora || contextSource instanceof GraphTopicPanel) ) { return true; } return false; } @Override public Object getContextSource() { return contextSource; } // ------------------------------------------------------------------------- public void log(Exception e) { if(contextOwner != null) contextOwner.log(e); else e.printStackTrace(); } }
5,505
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ClassContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/ClassContext.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/>. * * * ClassContext.java * * Created on 8. huhtikuuta 2006, 12:24 * */ package org.wandora.application.contexts; import java.util.Iterator; import org.wandora.application.contexts.iterators.ClassIterator; /** * @author akivela */ public class ClassContext extends LayeredTopicContext implements Context { @Override public Iterator getContextObjects() { ClassIterator iterator = new ClassIterator(); iterator.initialize(super.getContextObjects(), wandora); return iterator; } }
1,332
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RoleContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/RoleContext.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/>. * * * RoleContext.java * * Created on 13. huhtikuuta 2006, 11:32 * */ package org.wandora.application.contexts; import java.util.Iterator; import org.wandora.application.contexts.iterators.RoleIterator; /** * * @author akivela */ public class RoleContext extends LayeredTopicContext implements Context { @Override public Iterator getContextObjects() { RoleIterator iterator = new RoleIterator(); iterator.initialize(super.getContextObjects(), wandora); return iterator; } }
1,332
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
MultiContextCollected.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/MultiContextCollected.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/>. * * * MultiContextCollected.java * * Created on 8. huhtikuuta 2006, 20:36 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; /** * * @author akivela */ public class MultiContextCollected implements Context { private List<Context> multiContext = new ArrayList<>(); public boolean removeDuplicates = true; private Object contextSource; private ActionEvent contextEvent; /** * Creates a new instance of MultiContextCollected */ public MultiContextCollected() { } public MultiContextCollected(Context context) { addContext(context); } public MultiContextCollected(ArrayList<Context> contexts) { addContexts(contexts); } //-------------------------------------------------------------------------- public void addContext(Context context) { multiContext.add(context); } public void addContexts(ArrayList<Context> contexts) { for(Iterator<Context> contextIterator=contexts.iterator(); contextIterator.hasNext(); ) { multiContext.add(contextIterator.next()); } } public void clearContext() { multiContext = new ArrayList(); } @Override public Iterator getContextObjects() { Collection<Object> contextObjects = new ArrayList<>(); Iterator<Object> tempContextObjects; Object contextObject = null; Context context = null; for(Iterator<Context> contextIterator=multiContext.iterator(); contextIterator.hasNext(); ) { context = contextIterator.next(); if(context != null) { if(removeDuplicates) { tempContextObjects = context.getContextObjects(); while(tempContextObjects.hasNext()) { contextObject = tempContextObjects.next(); if( !contextObjects.contains(contextObject) ) { contextObjects.add(contextObject); } } } else { tempContextObjects = context.getContextObjects(); while(tempContextObjects.hasNext()) { contextObjects.add( tempContextObjects.next() ); } } } } return contextObjects.iterator(); } @Override public ActionEvent getContextEvent() { return contextEvent; } @Override public void setContextSource(Object proposedContextSource) { contextSource = proposedContextSource; Context context = null; for(Iterator<Context> contextIterator=multiContext.iterator(); contextIterator.hasNext(); ) { context = contextIterator.next(); if(context != null) { context.setContextSource(proposedContextSource); } } } @Override public Object getContextSource() { return contextSource; } @Override public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { contextEvent = actionEvent; Context context = null; for(Iterator<Context> contextIterator=multiContext.iterator(); contextIterator.hasNext(); ) { context = contextIterator.next(); if(context != null) { context.initialize(wandora, actionEvent, contextOwner); } } } }
4,557
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ApplicationContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/ApplicationContext.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/>. * * * ApplicationContext.java * * Created on 22. huhtikuuta 2006, 10:38 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.topicmap.Topic; /** * ApplicationContext uses application ie. the Wandora as a context source. * Context object is a topic opened in topic panel. * * @author akivela */ public class ApplicationContext implements Context { private Object contextSource; protected WandoraTool contextOwner = null; protected ActionEvent actionEvent = null; protected Wandora wandora = null; /** Creates a new instance of ApplicationContext */ public ApplicationContext() { } @Override public Iterator getContextObjects() { List<Topic> contextTopics = new ArrayList<>(); try { Wandora w = (Wandora) contextSource; Topic currentTopic = w.getOpenTopic(); if(currentTopic != null) { contextTopics.add(currentTopic); } } catch (Exception e) { log(e); } return contextTopics.iterator(); } @Override public ActionEvent getContextEvent() { return actionEvent; } @Override public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { this.wandora = wandora; this.actionEvent = actionEvent; this.contextOwner = contextOwner; setContextSource( wandora ); } @Override public void setContextSource(Object proposedContextSource) { contextSource = proposedContextSource; } @Override public Object getContextSource() { return contextSource; } // ------------------------------------------------------------------------- public void log(Exception e) { if(contextOwner != null) contextOwner.log(e); else e.printStackTrace(); } }
2,963
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
Context.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/Context.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/>. * * * Context.java * * Created on 7. huhtikuuta 2006, 12:30 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; /** * <p> * Context contains the execution environment of a tool. * </p> * <p> * Context must always initialized before usage. * </p> * * @author akivela */ public interface Context { /** * Initializes context with * - Wandora: The Application. * - ActionEvent: Event that triggered the execution of tool. * - AdminTool: The Tool to be executed. Note that Context _is not_ executing the tool! */ public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner); /** * Returns Iterator for accessible object in context ie. object the tool may * modify or otherwise access. Generally returned iterator contains Topic(s) found in * the GUI element that originated tool's action event. * * @return <tt>Iterator</tt> containing all the context objects. */ public Iterator getContextObjects(); /** * Sets the origin of context. Normally context origin is a GUI element * that triggered the tool execution. */ public void setContextSource(Object contextSource); /** * Returns the origin of context. Normally context origin is a GUI element * that triggered the tool execution. */ public Object getContextSource(); /** * @return The event that triggered the tool execution. */ public ActionEvent getContextEvent(); }
2,470
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
EmptyContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/EmptyContext.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/>. * * * EmptyContext.java * * Created on 15.6.2006, 14:36 */ package org.wandora.application.contexts; import java.util.ArrayList; import java.util.Iterator; /** * * @author olli */ public class EmptyContext extends LayeredTopicContext implements Context { @Override public Iterator getContextObjects() { return new ArrayList().iterator(); } }
1,180
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AssociationContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/AssociationContext.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/>. * * * AssociationContext.java * * Created on 7. huhtikuuta 2006, 12:29 * */ package org.wandora.application.contexts; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.wandora.application.gui.simple.AssociationTypeLinkBasename; import org.wandora.application.gui.table.AssociationTable; import org.wandora.application.gui.topicpanels.GraphTopicPanel; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; /** * * @author akivela */ public class AssociationContext extends LayeredTopicContext implements Context { public boolean removeDuplicates = true; @Override public Iterator getContextObjects() { Object contextSource = getContextSource(); if(contextSource instanceof AssociationTable) { return ((AssociationTable) contextSource).getSelectedAssociations().iterator(); } else if(contextSource instanceof AssociationTypeLinkBasename) { return ((AssociationTypeLinkBasename) contextSource).getAssociationTable().getAllAssociations().iterator(); } else if(contextSource instanceof GraphTopicPanel) { return ((GraphTopicPanel) contextSource).getContextAssociations().iterator(); } else { return getAssociationsOf( super.getContextObjects() ); } } public Iterator<Association> getAssociationsOf(Iterator topics) { if(topics == null) return null; List<Association> contextAssociations = new ArrayList<>(); Collection<Association> associations = null; Topic topic = null; Association association = null; while(topics.hasNext()) { try { topic = (Topic) topics.next(); if(topic == null) continue; if(removeDuplicates) { associations = topic.getAssociations(); for(Iterator<Association> associationIterator = associations.iterator(); associationIterator.hasNext(); ) { association = associationIterator.next(); if(association != null && !contextAssociations.contains(association)) { contextAssociations.add(association); } } } else { contextAssociations.addAll( topic.getAssociations() ); } } catch(Exception e) { log(e); } } return contextAssociations.iterator(); } }
3,453
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
GraphNodeContext.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/GraphNodeContext.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/>. * * * NodeContext.java * * Created on 13.6.2007, 15:04 * */ package org.wandora.application.contexts; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.wandora.application.Wandora; import org.wandora.application.WandoraTool; import org.wandora.application.gui.UIBox; import org.wandora.application.gui.topicpanels.DockingFramePanel; import org.wandora.application.gui.topicpanels.GraphTopicPanel; import org.wandora.application.gui.topicpanels.TopicPanel; import org.wandora.application.gui.topicpanels.graphpanel.TopicMapGraphPanel; import org.wandora.application.gui.topicpanels.graphpanel.VNode; /** * * @author akivela */ public class GraphNodeContext implements Context { private Object contextSource; protected WandoraTool contextOwner = null; protected ActionEvent actionEvent = null; protected Wandora wandora = null; /** Creates a new instance of GraphNodeContext */ public GraphNodeContext() { } public GraphNodeContext(TopicMapGraphPanel gp) { } @Override public void initialize(Wandora wandora, ActionEvent actionEvent, WandoraTool contextOwner) { this.wandora = wandora; this.actionEvent = actionEvent; this.contextOwner = contextOwner; Object proposedContextSource = UIBox.getActionsRealSource(actionEvent); if( !isContextSource(proposedContextSource) ) { proposedContextSource = wandora.getFocusOwner(); if( !isContextSource(proposedContextSource) ) { proposedContextSource = wandora; } } setContextSource( proposedContextSource ); } @Override public ActionEvent getContextEvent() { return actionEvent; } @Override public Iterator getContextObjects() { return getContextObjects( getContextSource() ); } public Iterator getContextObjects(Object contextSource) { if(contextSource == null) return null; List<VNode> contextNodes = new ArrayList<>(); if(contextSource instanceof Wandora) { try { Wandora wandora = (Wandora) contextSource; TopicPanel currentTopicPanel = wandora.getTopicPanel(); if(currentTopicPanel != null && currentTopicPanel instanceof DockingFramePanel) { currentTopicPanel = ((DockingFramePanel) currentTopicPanel).getCurrentTopicPanel(); } if(currentTopicPanel != null && currentTopicPanel instanceof GraphTopicPanel) { contextNodes.addAll( ((GraphTopicPanel) currentTopicPanel).getGraphPanel().getSelectedNodes() ); if(contextNodes.isEmpty()) { //contextNodes.add( ((GraphTopicPanel) currentTopicPanel).getGraphPanel().getMouseOverNode() ); } } if(currentTopicPanel != null && currentTopicPanel instanceof TopicMapGraphPanel) { contextNodes.addAll( ((TopicMapGraphPanel) currentTopicPanel).getSelectedNodes() ); if(contextNodes.isEmpty()) { //contextNodes.add( ((TopicMapGraphPanel) currentTopicPanel).getMouseOverNode() ); } } } catch (Exception e) { log(e); } } else if(contextSource instanceof GraphTopicPanel) { contextNodes.addAll( ((GraphTopicPanel) contextSource).getGraphPanel().getSelectedNodes() ); if(contextNodes.isEmpty()) { //contextNodes.add( ((GraphTopicPanel) contextSource).getGraphPanel().getMouseOverNode() ); } } else if(contextSource instanceof TopicMapGraphPanel) { contextNodes.addAll( ((TopicMapGraphPanel) contextSource).getSelectedNodes() ); if(contextNodes.isEmpty()) { //contextNodes.add( ((TopicMapGraphPanel) contextSource).getMouseOverNode() ); } } return contextNodes.iterator(); } @Override public void setContextSource(Object proposedContextSource) { if(isContextSource(proposedContextSource)) { contextSource = proposedContextSource; } else { contextSource = null; } } public boolean isContextSource(Object contextSource) { if(contextSource != null && ( contextSource instanceof Wandora || contextSource instanceof GraphTopicPanel) ) { return true; } return false; } @Override public Object getContextSource() { return contextSource; } // ------------------------------------------------------------------------- public void log(Exception e) { if(contextOwner != null) contextOwner.log(e); else e.printStackTrace(); } }
5,881
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
PlayerIterator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/iterators/PlayerIterator.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/>. * * * PlayerIterator.java * * Created on 13. huhtikuuta 2006, 11:02 * */ package org.wandora.application.contexts.iterators; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class PlayerIterator extends TopicIterator { @Override public Iterator solveIteratorForTopic(Topic topic, TopicMap topicmap, Iterator oldIterator) { Collection playerTopics = new ArrayList(); Collection associations = null; Association association = null; Iterator associationIterator = null; Collection roleTopics = null; Topic roleTopic = null; Topic playerTopic = null; if(topic != null) { try{ associations = topic.getAssociations(); if(associations != null) { associationIterator = associations.iterator(); while(associationIterator.hasNext()) { association = (Association) associationIterator.next(); if(association == null) continue; roleTopics = association.getRoles(); if(roleTopics != null && roleTopics.size() > 0) { for(Iterator roleIterator = roleTopics.iterator(); roleIterator.hasNext(); ) { roleTopic = (Topic) roleIterator.next(); playerTopic = association.getPlayer(roleTopic); if(playerTopic != null) { playerTopics.add( playerTopic ); } } } } } } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } } return playerTopics.iterator(); } }
2,909
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
InstanceIterator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/iterators/InstanceIterator.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/>. * * * InstanceIterator.java * * Created on 13. huhtikuuta 2006, 10:19 * */ package org.wandora.application.contexts.iterators; import java.util.Iterator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class InstanceIterator extends TopicIterator { @Override public Iterator solveIteratorForTopic(Topic topic, TopicMap topicmap, Iterator oldIterator) { Iterator it = oldIterator; if(topic != null && topicmap != null) { try{ collection = topicmap.getTopicsOfType(topic); } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION collection=null; } if(collection != null) it = collection.iterator(); } return it; } }
1,709
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
ClassIterator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/iterators/ClassIterator.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/>. * * * ClassIterator.java * * Created on 13. huhtikuuta 2006, 10:49 * */ package org.wandora.application.contexts.iterators; import java.util.Iterator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class ClassIterator extends TopicIterator { @Override public Iterator solveIteratorForTopic(Topic topic, TopicMap topicmap, Iterator oldIterator) { Iterator it = oldIterator; if(topic != null) { try{ collection = topic.getTypes(); } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } if(collection != null) it = collection.iterator(); } return it; } }
1,631
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
AssociationTypeIterator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/iterators/AssociationTypeIterator.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/>. * * * AssociationTypeIterator.java * * Created on 13. huhtikuuta 2006, 12:01 * */ package org.wandora.application.contexts.iterators; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class AssociationTypeIterator extends TopicIterator { @Override public Iterator solveIteratorForTopic(Topic topic, TopicMap topicmap, Iterator oldIterator) { Collection<Topic> associationTypeTopics = new ArrayList<>(); Collection<Association> associations = null; Association association = null; Iterator<Association> associationIterator = null; if(topic != null) { try{ associations = topic.getAssociations(); if(associations != null) { associationIterator = associations.iterator(); while(associationIterator.hasNext()) { association = associationIterator.next(); if(association == null) continue; associationTypeTopics.add(association.getType()); } } } catch(TopicMapException tme){ tme.printStackTrace(); // TODO EXCEPTION } } return associationTypeTopics.iterator(); } }
2,324
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
RoleIterator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/iterators/RoleIterator.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/>. * * * RoleIterator.java * * Created on 13. huhtikuuta 2006, 11:03 * */ package org.wandora.application.contexts.iterators; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.wandora.topicmap.Association; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.TopicMapException; /** * * @author akivela */ public class RoleIterator extends TopicIterator { @Override public Iterator solveIteratorForTopic(Topic topic, TopicMap topicmap, Iterator oldIterator) { Collection allRoleTopics = new ArrayList(); Collection associations = null; Association association = null; Iterator associationIterator = null; Collection roleTopics = null; Topic roleTopic = null; Topic playerTopic = null; if(topic != null) { try{ associations = topic.getAssociations(); if(associations != null) { associationIterator = associations.iterator(); while(associationIterator.hasNext()) { association = (Association) associationIterator.next(); if(association == null) continue; roleTopics = association.getRoles(); if(roleTopics != null && roleTopics.size() > 0) { for(Iterator roleIterator = roleTopics.iterator(); roleIterator.hasNext(); ) { roleTopic = (Topic) roleIterator.next(); if(roleTopic != null) { allRoleTopics.add(roleTopic); } } } } } } catch(TopicMapException tme) { tme.printStackTrace();// TODO EXCEPTION } } return allRoleTopics.iterator(); } }
2,828
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicIterator.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/iterators/TopicIterator.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/>. * * * TopicIterator.java * * Created on 13. huhtikuuta 2006, 10:05 * */ package org.wandora.application.contexts.iterators; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.wandora.application.Wandora; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; /** * * @author akivela */ public abstract class TopicIterator implements Iterator { Iterator source = null; TopicMap topicmap = null; Topic topic = null; Object next = null; Iterator iterator = null; Collection collection = null; Collection cache = null; boolean removeDuplicates = true; public TopicIterator() { } public void initialize(Iterator source, Wandora wandora) { this.source = source; this.topicmap = wandora.getTopicMap(); if(removeDuplicates) { cache = new ArrayList(); next = solveNextUncached(); } else { next = solveNext(); } } @Override public boolean hasNext() { if(next != null) return true; else return false; } @Override public Object next() { Object current = next; next = removeDuplicates ? solveNextUncached() : solveNext(); return current; } @Override public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } public void removeDuplicates(boolean should) { this.removeDuplicates = should; } // ------------------------------------------------------------------------- // ----------------------------------------------- HIDDEN IMPLEMENTATION --- // ------------------------------------------------------------------------- private Object solveNextUncached() { Object nextUncached = null; do { nextUncached = solveNext(); } while(cache.contains(nextUncached) && nextUncached != null); if(nextUncached != null) cache.add(nextUncached); return nextUncached; } private Object solveNext() { Iterator iterator = solveIterator(); if(iterator != null && iterator.hasNext()) return iterator.next(); else return null; } private Iterator solveIterator() { while(iterator == null || !iterator.hasNext()) { if(source != null && source.hasNext()) { topic = (Topic) source.next(); while(topic == null && source.hasNext()) topic = (Topic) source.next(); iterator = solveIteratorForTopic(topic, topicmap, iterator); } else { break; } } return iterator; } // ------------------------------------------------------------------------- // ----------- Overwrite next method in your own topic element iterator! --- // ------------------------------------------------------------------------- public Iterator solveIteratorForTopic(Topic topic, TopicMap topicmap, Iterator oldIterator) { Iterator it = oldIterator; return it; } }
4,061
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
TopicIteratorForCurrentLayer.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/wandora/application/contexts/iterators/TopicIteratorForCurrentLayer.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/>. * * * TopicIteratorForCurrentLayer.java * * Created on 7.6.2006, 18:16 * */ package org.wandora.application.contexts.iterators; import java.util.ArrayList; import java.util.Iterator; import org.wandora.topicmap.Topic; import org.wandora.topicmap.TopicMap; import org.wandora.topicmap.layered.LayeredTopic; /** * * @author akivela */ public class TopicIteratorForCurrentLayer extends TopicIterator { @Override public Iterator solveIteratorForTopic(Topic topic, TopicMap topicmap, Iterator oldIterator) { Iterator it = oldIterator; if(topic != null && topicmap != null) { try { if(topic instanceof LayeredTopic) { collection = ((LayeredTopic) topic).getTopicsForSelectedLayer(); } else { ArrayList list = new ArrayList(); list.add(topic); collection = list; //collection = null; } } catch(Exception e) { e.printStackTrace(); collection=null; } if(collection != null) { it = collection.iterator(); } } return it; } }
2,063
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z
WandoraLoggerAdapter.java
/FileExtraction/Java_unseen/wandora-team_wandora/src/main/java/org/slf4j/impl/WandoraLoggerAdapter.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.slf4j.impl; import org.slf4j.Logger; import org.slf4j.Marker; /** * * @author akivela */ public class WandoraLoggerAdapter implements Logger { public static final int LOG_ALL=0; public static final int LOG_TRACE=0; public static final int LOG_DEBUG=1; public static final int LOG_INFO=2; public static final int LOG_WARN=3; public static final int LOG_ERROR=4; public static final int LOG_FATAL=5; public static final int LOG_NONE=6; private StringBuilder logData = null; private int logLevel = LOG_ERROR; public WandoraLoggerAdapter(String name) { logData = new StringBuilder(); } public WandoraLoggerAdapter(String name, int level) { logData = new StringBuilder(); logLevel = level; } @Override public String getName() { return "Wandora logger"; } // ------------------------------------------------------------------------- public void setLogLevel(int logLevel) { this.logLevel = logLevel; } // ------------------------------------------------------------------------- @Override public boolean isTraceEnabled() { return logLevel <= LOG_TRACE; } @Override public void trace(String string) { if(isTraceEnabled()) { log(string); } } @Override public void trace(String string, Object o) { if(isTraceEnabled()) { log(string); log(o); } } @Override public void trace(String string, Object o, Object o1) { if(isTraceEnabled()) { log(string); log(o); log(o1); } } @Override public void trace(String string, Object[] os) { if(isTraceEnabled()) { log(string); log(os); } } @Override public void trace(String string, Throwable thrwbl) { if(isTraceEnabled()) { log(string); log(thrwbl); } } @Override public boolean isTraceEnabled(Marker marker) { return logLevel <= LOG_TRACE; } @Override public void trace(Marker marker, String string) { if(isTraceEnabled(marker)) { log(string); } } @Override public void trace(Marker marker, String string, Object o) { if(isTraceEnabled(marker)) { log(string); log(o); } } @Override public void trace(Marker marker, String string, Object o, Object o1) { if(isTraceEnabled(marker)) { log(string); log(o); log(o1); } } @Override public void trace(Marker marker, String string, Object[] os) { if(isTraceEnabled(marker)) { log(string); log(os); } } @Override public void trace(Marker marker, String string, Throwable thrwbl) { if(isTraceEnabled(marker)) { log(string); log(thrwbl); } } // ------------------------------------------------------------------------- @Override public boolean isDebugEnabled() { return logLevel <= LOG_DEBUG; } @Override public void debug(String string) { if(isDebugEnabled()) { log(string); } } @Override public void debug(String string, Object o) { if(isDebugEnabled()) { log(string); log(o); } } @Override public void debug(String string, Object o, Object o1) { if(isDebugEnabled()) { log(string); log(o); log(o1); } } @Override public void debug(String string, Object[] os) { if(isDebugEnabled()) { log(string); log(os); } } @Override public void debug(String string, Throwable thrwbl) { if(isDebugEnabled()) { log(string); log(thrwbl); } } @Override public boolean isDebugEnabled(Marker marker) { return logLevel <= LOG_DEBUG; } @Override public void debug(Marker marker, String string) { if(isDebugEnabled(marker)) { log(string); } } @Override public void debug(Marker marker, String string, Object o) { if(isDebugEnabled(marker)) { log(string); log(o); } } @Override public void debug(Marker marker, String string, Object o, Object o1) { if(isDebugEnabled(marker)) { log(string); log(o); log(o1); } } @Override public void debug(Marker marker, String string, Object[] os) { if(isDebugEnabled(marker)) { log(string); log(os); } } @Override public void debug(Marker marker, String string, Throwable thrwbl) { if(isDebugEnabled(marker)) { log(string); log(thrwbl); } } // ------------------------------------------------------------------------- @Override public boolean isInfoEnabled() { return logLevel <= LOG_INFO; } @Override public void info(String string) { if(isInfoEnabled()) { log(string); } } @Override public void info(String string, Object o) { if(isInfoEnabled()) { log(string); log(o); } } @Override public void info(String string, Object o, Object o1) { if(isInfoEnabled()) { log(string); log(o); log(o1); } } @Override public void info(String string, Object[] os) { if(isInfoEnabled()) { log(string); log(os); } } @Override public void info(String string, Throwable thrwbl) { if(isInfoEnabled()) { log(string); log(thrwbl); } } @Override public boolean isInfoEnabled(Marker marker) { return logLevel <= LOG_INFO; } @Override public void info(Marker marker, String string) { if(isInfoEnabled(marker)) { log(string); } } @Override public void info(Marker marker, String string, Object o) { if(isInfoEnabled(marker)) { log(string); log(o); } } @Override public void info(Marker marker, String string, Object o, Object o1) { if(isInfoEnabled(marker)) { log(string); log(o1); } } @Override public void info(Marker marker, String string, Object[] os) { if(isInfoEnabled(marker)) { log(string); log(os); } } @Override public void info(Marker marker, String string, Throwable thrwbl) { if(isInfoEnabled(marker)) { log(string); log(thrwbl); } } // ------------------------------------------------------------------------- @Override public boolean isWarnEnabled() { return logLevel <= LOG_WARN; } @Override public void warn(String string) { if(isWarnEnabled()) { log(string); } } @Override public void warn(String string, Object o) { if(isWarnEnabled()) { log(string); log(o); } } @Override public void warn(String string, Object[] os) { if(isWarnEnabled()) { log(string); log(os); } } @Override public void warn(String string, Object o, Object o1) { if(isWarnEnabled()) { log(string); log(o); log(o1); } } @Override public void warn(String string, Throwable thrwbl) { if(isWarnEnabled()) { log(string); log(thrwbl); } } @Override public boolean isWarnEnabled(Marker marker) { return logLevel <= LOG_WARN; } @Override public void warn(Marker marker, String string) { if(isWarnEnabled(marker)) { log(string); } } @Override public void warn(Marker marker, String string, Object o) { if(isWarnEnabled(marker)) { log(string); log(o); } } @Override public void warn(Marker marker, String string, Object o, Object o1) { if(isWarnEnabled(marker)) { log(string); log(o); log(o1); } } @Override public void warn(Marker marker, String string, Object[] os) { if(isWarnEnabled(marker)) { log(string); log(os); } } @Override public void warn(Marker marker, String string, Throwable thrwbl) { if(isWarnEnabled(marker)) { log(string); log(thrwbl); } } // ------------------------------------------------------------------------- @Override public boolean isErrorEnabled() { return logLevel <= LOG_ERROR; } @Override public void error(String string) { if(isErrorEnabled()) { log(string); } } @Override public void error(String string, Object o) { if(isErrorEnabled()) { log(string); log(o); } } @Override public void error(String string, Object o, Object o1) { if(isErrorEnabled()) { log(string); log(o); log(o1); } } @Override public void error(String string, Object[] os) { if(isErrorEnabled()) { log(string); log(os); } } @Override public void error(String string, Throwable thrwbl) { if(isErrorEnabled()) { log(string); log(thrwbl); } } @Override public boolean isErrorEnabled(Marker marker) { return logLevel <= LOG_ERROR; } @Override public void error(Marker marker, String string) { if(isErrorEnabled(marker)) { log(string); } } @Override public void error(Marker marker, String string, Object o) { if(isErrorEnabled(marker)) { log(string); log(o); } } @Override public void error(Marker marker, String string, Object o, Object o1) { if(isErrorEnabled(marker)) { log(string); log(o); log(o1); } } @Override public void error(Marker marker, String string, Object[] os) { if(isErrorEnabled(marker)) { log(string); log(os); } } @Override public void error(Marker marker, String string, Throwable thrwbl) { if(isErrorEnabled(marker)) { log(string); log(thrwbl); } } // ------------------------------------------------------------------------- private void log(Object o) { if(o == null) return; if(o instanceof String) { System.out.println(o); } else if(o instanceof Throwable) { Throwable thrwbl = (Throwable) o; // thrwbl.printStackTrace(); } else { System.out.println(o.toString()); } } }
12,304
Java
.java
wandora-team/wandora
126
26
0
2014-06-30T10:25:42Z
2023-09-09T07:13:29Z