repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/TestLudemeDialog.java
package app.display.dialogs; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import app.PlayerApp; import app.display.dialogs.util.DialogUtil; import compiler.Compiler; import game.equipment.component.Component; import game.types.board.SiteType; import game.util.directions.DirectionFacing; import gnu.trove.list.array.TIntArrayList; import grammar.Grammar; import main.StringRoutines; import main.grammar.Report; import main.grammar.Symbol; import other.concept.Concept; import other.concept.ConceptType; import other.context.Context; import other.topology.TopologyElement; /** * Dialog that can be used to compile a given string, using the current game context. * * @author Matthew.Stephenson and cambolbro and Eric.Piette */ public class TestLudemeDialog extends JDialog { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- private final JPanel contentPanel = new JPanel(); /** * Launch the dialog. */ public static void showDialog(final PlayerApp app) { try { final TestLudemeDialog dialog = new TestLudemeDialog(app); DialogUtil.initialiseDialog(dialog, "Test Ludeme Dialog", null); } catch (final Exception e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Create the dialog. */ public TestLudemeDialog(final PlayerApp app) { super(null, java.awt.Dialog.ModalityType.DOCUMENT_MODAL); setBounds(100, 100, 650, 509); getContentPane().setLayout(new BorderLayout()); { { contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(new GridLayout(2,2)); // Margin size around each panel. final int marginSize = 10; // Panel 1 final JPanel panel_1 = new JPanel(); panel_1.setBorder(BorderFactory.createEmptyBorder(marginSize, marginSize, marginSize, marginSize)); contentPanel.add(panel_1); panel_1.setLayout(new BorderLayout(0, 0)); final JTextPane textPane_1 = new JTextPane(); final JScrollPane scrollpane_1 = new JScrollPane(textPane_1); panel_1.add(scrollpane_1, BorderLayout.CENTER); textPane_1.setPreferredSize(new Dimension(5000, panel_1.getHeight()-20)); final JPanel panel_11 = new JPanel(); panel_1.add(panel_11, BorderLayout.NORTH); panel_11.setLayout(new BorderLayout(0, 0)); final JLabel label_1 = new JLabel("Enter a ludeme:"); panel_11.add(label_1, BorderLayout.WEST); final JPanel panel = new JPanel(); panel_11.add(panel, BorderLayout.EAST); final JButton button_1 = new JButton("Test"); panel.add(button_1); button_1.setEnabled(false); final JButton button_5 = new JButton("Concepts"); panel.add(button_5); button_5.setEnabled(false); // Panel 2 final JPanel panel_2 = new JPanel(); panel_2.setBorder(BorderFactory.createEmptyBorder(marginSize, marginSize, marginSize, marginSize)); contentPanel.add(panel_2); panel_2.setLayout(new BorderLayout(0, 0)); final JTextPane textPane_2 = new JTextPane(); final JScrollPane scrollpane_2 = new JScrollPane(textPane_2); panel_2.add(scrollpane_2, BorderLayout.CENTER); textPane_2.setPreferredSize(new Dimension(5000, panel_2.getHeight()-20)); final JPanel panel_22 = new JPanel(); panel_2.add(panel_22, BorderLayout.NORTH); panel_22.setLayout(new BorderLayout(0, 0)); final JLabel label_2 = new JLabel("Enter a ludeme:"); panel_22.add(label_2, BorderLayout.WEST); final JPanel panel_5 = new JPanel(); panel_22.add(panel_5, BorderLayout.EAST); final JButton button_2 = new JButton("Test"); panel_5.add(button_2); button_2.setEnabled(false); final JButton button_6 = new JButton("Concepts"); button_6.setEnabled(false); panel_5.add(button_6); // Panel 3 final JPanel panel_3 = new JPanel(); panel_3.setBorder(BorderFactory.createEmptyBorder(marginSize, marginSize, marginSize, marginSize)); contentPanel.add(panel_3); panel_3.setLayout(new BorderLayout(0, 0)); final JTextPane textPane_3 = new JTextPane(); final JScrollPane scrollpane_3 = new JScrollPane(textPane_3); panel_3.add(scrollpane_3, BorderLayout.CENTER); textPane_3.setPreferredSize(new Dimension(5000, panel_3.getHeight()-20)); final JPanel panel_33 = new JPanel(); panel_3.add(panel_33, BorderLayout.NORTH); panel_33.setLayout(new BorderLayout(0, 0)); final JLabel label_3 = new JLabel("Enter a ludeme:"); panel_33.add(label_3, BorderLayout.WEST); final JPanel panel_6 = new JPanel(); panel_33.add(panel_6, BorderLayout.EAST); final JButton button_3 = new JButton("Test"); panel_6.add(button_3); button_3.setEnabled(false); final JButton button_7 = new JButton("Concepts"); button_7.setEnabled(false); panel_6.add(button_7); // Panel 4 final JPanel panel_4 = new JPanel(); panel_4.setBorder(BorderFactory.createEmptyBorder(marginSize, marginSize, marginSize, marginSize)); contentPanel.add(panel_4); panel_4.setLayout(new BorderLayout(0, 0)); final JTextPane textPane_4 = new JTextPane(); final JScrollPane scrollpane_4 = new JScrollPane(textPane_4); panel_4.add(scrollpane_4, BorderLayout.CENTER); textPane_4.setPreferredSize(new Dimension(5000, panel_4.getHeight()-20)); final JPanel panel_44 = new JPanel(); panel_4.add(panel_44, BorderLayout.NORTH); panel_44.setLayout(new BorderLayout(0, 0)); final JLabel label_4 = new JLabel("Enter a ludeme:"); panel_44.add(label_4, BorderLayout.WEST); final JPanel panel_7 = new JPanel(); panel_44.add(panel_7, BorderLayout.EAST); final JButton button_4 = new JButton("Test"); panel_7.add(button_4); button_4.setEnabled(false); final JButton button_8 = new JButton("Concepts"); button_8.setEnabled(false); panel_7.add(button_8); // Action listeners for each button final ActionListener listener_1 = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { testLudemeString(app, textPane_1.getText()); } }; final ActionListener listener_2 = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { testLudemeString(app, textPane_2.getText()); } }; final ActionListener listener_3 = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { testLudemeString(app, textPane_3.getText()); } }; final ActionListener listener_4 = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { testLudemeString(app, textPane_4.getText()); } }; button_1.addActionListener(listener_1); button_2.addActionListener(listener_2); button_3.addActionListener(listener_3); button_4.addActionListener(listener_4); // Action listeners for each button final ActionListener listener_5 = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { testLudemeStringConcepts(app, textPane_1.getText()); } }; final ActionListener listener_6 = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { testLudemeStringConcepts(app, textPane_2.getText()); } }; final ActionListener listener_7 = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { testLudemeStringConcepts(app, textPane_3.getText()); } }; final ActionListener listener_8 = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { testLudemeStringConcepts(app, textPane_4.getText()); } }; button_5.addActionListener(listener_5); button_6.addActionListener(listener_6); button_7.addActionListener(listener_7); button_8.addActionListener(listener_8); // Action listeners for each textpane final DocumentListener listenerText_1 = new DocumentListener() { @Override public void changedUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_1, button_1); checkButtonEnabled(textPane_1, button_5); app.settingsPlayer().setTestLudeme1(textPane_1.getText()); } @Override public void insertUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_1, button_1); checkButtonEnabled(textPane_1, button_5); app.settingsPlayer().setTestLudeme1(textPane_1.getText()); } @Override public void removeUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_1, button_1); checkButtonEnabled(textPane_1, button_5); app.settingsPlayer().setTestLudeme1(textPane_1.getText()); } }; final DocumentListener listenerText_2 = new DocumentListener() { @Override public void changedUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_2, button_2); checkButtonEnabled(textPane_2, button_6); app.settingsPlayer().setTestLudeme2(textPane_2.getText()); } @Override public void insertUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_2, button_2); checkButtonEnabled(textPane_2, button_6); app.settingsPlayer().setTestLudeme2(textPane_2.getText()); } @Override public void removeUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_2, button_2); checkButtonEnabled(textPane_2, button_6); app.settingsPlayer().setTestLudeme2(textPane_2.getText()); } }; final DocumentListener listenerText_3 = new DocumentListener() { @Override public void changedUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_3, button_3); checkButtonEnabled(textPane_3, button_7); app.settingsPlayer().setTestLudeme3(textPane_3.getText()); } @Override public void insertUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_3, button_3); checkButtonEnabled(textPane_3, button_7); app.settingsPlayer().setTestLudeme3(textPane_3.getText()); } @Override public void removeUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_3, button_3); checkButtonEnabled(textPane_3, button_7); app.settingsPlayer().setTestLudeme3(textPane_3.getText()); } }; final DocumentListener listenerText_4 = new DocumentListener() { @Override public void changedUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_4, button_4); checkButtonEnabled(textPane_4, button_8); app.settingsPlayer().setTestLudeme4(textPane_4.getText()); } @Override public void insertUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_4, button_4); checkButtonEnabled(textPane_4, button_8); app.settingsPlayer().setTestLudeme4(textPane_4.getText()); } @Override public void removeUpdate(final DocumentEvent e) { checkButtonEnabled(textPane_4, button_4); checkButtonEnabled(textPane_4, button_8); app.settingsPlayer().setTestLudeme4(textPane_4.getText()); } }; textPane_1.getDocument().addDocumentListener(listenerText_1); textPane_2.getDocument().addDocumentListener(listenerText_2); textPane_3.getDocument().addDocumentListener(listenerText_3); textPane_4.getDocument().addDocumentListener(listenerText_4); textPane_1.setText(app.settingsPlayer().testLudeme1()); textPane_2.setText(app.settingsPlayer().testLudeme2()); textPane_3.setText(app.settingsPlayer().testLudeme3()); textPane_4.setText(app.settingsPlayer().testLudeme4()); } } } static void checkButtonEnabled(final JTextPane textPane_1, final JButton button_1) { if (textPane_1.getText().length() > 0) button_1.setEnabled(true); else button_1.setEnabled(false); } //------------------------------------------------------------------------- // Tests a specified ludeme string when a test button is pressed in the dialog static void testLudemeString(final PlayerApp app, final String str) { if (str == null || str.equals("")) return; try { final Object compiledObject = compileString(str); if (compiledObject != null) { final String error = evalCompiledObject(app, compiledObject, app.manager().ref().context()); if (error != null) app.addTextToStatusPanel(error + "\n"); } else { app.addTextToStatusPanel("Couldn't compile ludeme \"" + str + "\".\n"); } } catch (final Exception ex) { app.addTextToStatusPanel("Couldn't evaluate ludeme.\n"); } } //------------------------------------------------------------------------- /** * Tests a specified ludeme string when a test button is pressed in the * dialog * * @param app The app. * @param str The string to check. */ static void testLudemeStringConcepts ( final PlayerApp app, final String str ) { if (str == null || str.equals("")) return; try { final Object compiledObject = compileString(str); if (compiledObject != null) { final String error = evalConceptCompiledObject(app, compiledObject, app.manager().ref().context()); if (error != null) app.addTextToStatusPanel(error + "\n"); } else { app.addTextToStatusPanel("Couldn't compile ludeme \"" + str + "\".\n"); } } catch (final Exception ex) { app.addTextToStatusPanel("Couldn't evaluate ludeme.\n"); } } //------------------------------------------------------------------------- /** * Attempts to compile a given string for every possible symbol class. * @return Compiled object if possible, else null. */ static Object compileString(final String str) { Object obj = null; final String token = StringRoutines.getFirstToken(str); final List<Symbol> symbols = Grammar.grammar().symbolsWithPartialKeyword(token); // Try each possible symbol for this token for (final Symbol symbol : symbols) { final String className = symbol.cls().getName(); final Report report = new Report(); try { obj = Compiler.compileObject(str, className, report); } catch (final Exception ex) { //System.out.println("Couldn't compile."); } if (obj == null) continue; } return obj; } //------------------------------------------------------------------------- /** * Attempts to evaluate a compiled object. * * @author Eric.Piette */ static String evalCompiledObject(final PlayerApp app, final Object obj, final Context context) { String error = null; boolean foundEval = false; boolean success = false; // Need to preprocess the ludemes before to call the eval method. Method preprocess = null; try { preprocess = obj.getClass().getDeclaredMethod("preprocess", context.game().getClass()); if (preprocess != null) preprocess.invoke(obj, context.game()); } catch (final Exception e) { e.printStackTrace(); } // Get the right eval method according to the ludeme, in general // eval(context) but not always. Method eval = null; String className = ""; try { className = obj.getClass().toString(); if (className.contains("game.functions.graph")) eval = obj.getClass().getDeclaredMethod("eval", Context.class, SiteType.class); else if (className.contains("game.functions.directions")) eval = obj.getClass().getDeclaredMethod("convertToAbsolute", SiteType.class, TopologyElement.class, Component.class, DirectionFacing.class, Integer.class, Context.class); else eval = obj.getClass().getDeclaredMethod("eval", context.getClass()); } catch (final Exception e) { e.printStackTrace(); } // Call the right eval method. if (eval != null) { // Found eval method, try calling it foundEval = true; try { String result; if (className.contains("game.functions.graph")) result = eval.invoke(obj, context, context.board().defaultSite()).toString(); else if (className.contains("game.functions.directions")) result = eval.invoke(obj, context.board().defaultSite(), context.topology().centre(context.board().defaultSite()).get(0), null, null, null, context) .toString(); else if (className.contains("game.functions.intArray")) { final int[] sites = ((int[]) eval.invoke(obj, context)); result = new TIntArrayList(sites).toString(); } // else if (className.contains("game.rules.play.moves")) // { // final int[] sites = ((M) eval.invoke(obj, context)); // result = new TIntArrayList(sites).toString(); // } else result = eval.invoke(obj, context).toString(); success = true; if (result.trim().length() > 0) app.addTextToStatusPanel(result + "\n"); else app.addTextToStatusPanel("Ludeme compiles, but no result produced.\n"); } catch (final Exception e) { e.printStackTrace(); } } else if (!foundEval) error = "Couldn't evaluate ludeme \"" + obj.getClass() + "\"."; else if (!success) error = "Couldn't invoke ludeme \"" + obj.getClass() + "\"."; return error; } /** * Attempts to evaluate a compiled object. * * @author Eric.Piette */ static String evalConceptCompiledObject(final PlayerApp app, final Object obj, final Context context) { // Need to preprocess the ludemes before to call the eval method. Method preprocess = null; try { preprocess = obj.getClass().getDeclaredMethod("preprocess", context.game().getClass()); if (preprocess != null) preprocess.invoke(obj, context.game()); } catch (final Exception e) { e.printStackTrace(); } Method conceptMethod = null; BitSet concepts = new BitSet(); try { conceptMethod = obj.getClass().getDeclaredMethod("concepts", context.game().getClass()); if (preprocess != null) concepts = ((BitSet) conceptMethod.invoke(obj, context.game())); } catch (final Exception e) { e.printStackTrace(); } final List<List<String>> conceptsPerCategories = new ArrayList<List<String>>(); for (int i = 0; i < ConceptType.values().length; i++) conceptsPerCategories.add(new ArrayList<String>()); for (int i = 0; i < Concept.values().length; i++) { final Concept concept = Concept.values()[i]; final ConceptType type = concept.type(); if (concepts.get(concept.id())) conceptsPerCategories.get(type.ordinal()).add(concept.name()); } final StringBuffer properties = new StringBuffer("The boolean concepts of this ludeme are: \n\n"); for (int i = 0; i < conceptsPerCategories.size(); i++) { if(!conceptsPerCategories.get(i).isEmpty()) { final ConceptType type = ConceptType.values()[i]; properties.append("******* " + type.name() + " concepts *******\n"); for(int j = 0; j < conceptsPerCategories.get(i).size();j++) { final String concept = conceptsPerCategories.get(i).get(j); properties.append(concept + "\n"); } properties.append("\n"); } } return properties.toString(); } }
20,097
27.752504
103
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/MoveDialog/MoveDialog.java
package app.display.dialogs.MoveDialog; import java.awt.GridLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import app.PlayerApp; import app.display.dialogs.util.DialogUtil; import metadata.graphics.util.colour.ColourRoutines; import other.context.Context; import other.move.Move; /** * Dialog for showing various moves. * * @author Matthew.Stephenson */ public abstract class MoveDialog extends JDialog { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** Additional height to add to account for the menu bar. */ final static int menuBarHeight = 30; /** Border space around each button. */ final static int buttonBorderSize = 20; /** Number of columns of buttons. */ int columnNumber = 0; /** Number of rows of buttons. */ int rowNumber = 0; /** Size of images on buttons. */ int imageSize = 0; //------------------------------------------------------------------------- /** * Create the dialog. */ protected MoveDialog() { // Don't initialise. } //------------------------------------------------------------------------- /** * Changes the size of the dialog, to account for a newly added button. * @param button * @param columnNumber * @param rowNumber * @param buttonBorderSize */ protected void setDialogSize(final JButton button, final int columnNumber, final int rowNumber, final int buttonBorderSize) { final int maxWidth = Math.max(getWidth(), (int)((button.getPreferredSize().getWidth()) * columnNumber)); final int maxHeight = Math.max(getHeight(), (int)((button.getPreferredSize().getHeight() + buttonBorderSize) * rowNumber) + menuBarHeight); this.setSize(maxWidth, maxHeight); } //------------------------------------------------------------------------- /** * Adds a button to apply a specified move * @param move The move to apply * @param image The image for the button's icon * @param text The text for the button */ protected JButton AddButton(final PlayerApp app, final Move move, final BufferedImage image, final String text) { final JButton button = new JButton(); button.setBackground(app.bridge().settingsColour().getBoardColours()[2]); button.setForeground(ColourRoutines.getContrastColorFavourDark(app.bridge().settingsColour().getBoardColours()[2])); if (image != null) button.setIcon(new ImageIcon(image)); if (text.length() > 0) { final String htmlText = "<html><center> " + text + " </center></html>"; button.setText(DialogUtil.getWrappedText(button.getGraphics(), button, htmlText)); } button.setFocusPainted(false); getContentPane().add(button); button.addMouseListener(new MouseListener() { @Override public void mouseClicked(final MouseEvent e) { // do nothing } @Override public void mousePressed(final MouseEvent e) { // do nothing } @Override public void mouseReleased(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { buttonMove(app, move); dispose(); } } @Override public void mouseEntered(final MouseEvent e) { // do nothing } @Override public void mouseExited(final MouseEvent e) { // do nothing } }); return button; } //------------------------------------------------------------------------- /** * Perform this code when a button is pressed */ protected void buttonMove(final PlayerApp app, final Move m) { // do nothing; } //------------------------------------------------------------------------- /** * Set the layout of this dialog. */ protected void setDialogLayout(final PlayerApp app, final Context context, final int numButtons) { columnNumber = (int) Math.ceil(Math.sqrt(numButtons)); rowNumber = (int) Math.ceil((double) numButtons / (double) columnNumber); imageSize = Math.min(100, app.bridge().getContainerStyle(context.board().index()).cellRadiusPixels() * 2); getContentPane().setLayout(new GridLayout(0, columnNumber, 0, 0)); } }
4,218
25.36875
141
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/MoveDialog/PossibleMovesDialog.java
package app.display.dialogs.MoveDialog; import java.awt.BasicStroke; import java.awt.Color; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import javax.swing.JButton; import org.jfree.graphics2d.svg.SVGGraphics2D; import app.DesktopApp; import app.PlayerApp; import app.display.dialogs.util.DialogUtil; import app.move.MoveHandler; import app.move.MoveUtil; import app.utils.BufferedImageUtil; import app.utils.SVGUtil; import app.utils.SettingsExhibition; import game.equipment.component.Component; import graphics.ImageUtil; import graphics.svg.SVGtoImage; import main.collections.FastArrayList; import other.action.Action; import other.action.ActionType; import other.action.cards.ActionSetTrumpSuit; import other.action.move.move.ActionMove; import other.action.others.ActionPropose; import other.action.others.ActionVote; import other.action.state.ActionBet; import other.action.state.ActionSetNextPlayer; import other.action.state.ActionSetRotation; import other.context.Context; import other.move.Move; import other.state.container.ContainerState; import util.ContainerUtil; import util.HiddenUtil; import view.component.ComponentStyle; /** * Dialog for showing different special moves that cannot be displayed on the board directly. * * @author Matthew.Stephenson */ public class PossibleMovesDialog extends MoveDialog { private static final long serialVersionUID = 1L; //------------------------------------------------------------------------- /** * Show the Dialog. */ public static void createAndShowGUI(final PlayerApp app, final Context context, final FastArrayList<Move> validMoves, final boolean centerOnBoard) { if (SettingsExhibition.exhibitionVersion) { app.manager().ref().applyHumanMoveToGame(app.manager(), validMoves.get(0)); return; } try { final PossibleMovesDialog dialog = new PossibleMovesDialog(app, context, validMoves); Point drawPosn = new Point(MouseInfo.getPointerInfo().getLocation().x - dialog.getWidth() / 2, MouseInfo.getPointerInfo().getLocation().y - dialog.getHeight() / 2); if (centerOnBoard) drawPosn = new Point( (int)(DesktopApp.frame().getX() + DesktopApp.view().getBoardPanel().placement().getCenterX() - dialog.getWidth() / 2), (int)(DesktopApp.frame().getY() + DesktopApp.view().getBoardPanel().placement().getCenterY() - dialog.getHeight() / 2) + menuBarHeight); DialogUtil.initialiseForcedDialog(dialog, "Possible Moves", new Rectangle(drawPosn)); } catch (final Exception e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Create the dialog. */ public PossibleMovesDialog(final PlayerApp app, final Context context, final FastArrayList<Move> validMoves) { setDialogLayout(app, context, validMoves.size()); for (final Move m : validMoves) { boolean moveShown = false; // Check for displaying special actions for (final Action a : m.actions()) { final int fromContainerIndex = ContainerUtil.getContainerId(context, m.from(), m.fromType()); // Rotation move if (a instanceof ActionSetRotation) { final int componentValue = app.contextSnapshot().getContext(app).containerState(fromContainerIndex).what(m.from(), m.fromType()); if (componentValue != 0) { final Component c = context.components()[componentValue]; final BufferedImage componentImage = app.graphicsCache().getComponentImage(app.bridge(), fromContainerIndex, c, c.owner(), 0, 0, m.from(), 0, m.fromType(), imageSize, app.contextSnapshot().getContext(app), 0, a.rotation(), true); final JButton button = AddButton(app, m, componentImage, ""); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); moveShown = true; break; } } // Adding/Promoting a component else if (a.actionType() == ActionType.Add || a.actionType() == ActionType.Promote) { final ContainerState cs = app.contextSnapshot().getContext(app).containerState(fromContainerIndex); final int hiddenValue = HiddenUtil.siteHiddenBitsetInteger(context, cs, a.levelFrom(), a.levelFrom(), a.who(), a.fromType()); final int componentWhat = a.what(); final int componentValue = a.value(); final int componentState = a.state(); final ComponentStyle componentStyle = app.bridge().getComponentStyle(componentWhat); componentStyle.renderImageSVG(context, fromContainerIndex, imageSize, componentState, componentValue, true, hiddenValue, a.rotation()); final SVGGraphics2D svg = componentStyle.getImageSVG(componentState); BufferedImage componentImage = null; if (svg != null) componentImage = SVGUtil.createSVGImage(svg.getSVGDocument(),imageSize,imageSize); final JButton button = AddButton(app, m, componentImage, ""); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); moveShown = true; break; } // Set trump move else if (a instanceof ActionSetTrumpSuit) { final int trumpValue = ((ActionSetTrumpSuit) a).what(); String trumpImage = ""; Color imageColor = Color.BLACK; switch(trumpValue) { case 1: trumpImage = "card-suit-club"; break; case 2: trumpImage = "card-suit-spade"; break; case 3: trumpImage = "card-suit-diamond"; imageColor = Color.RED; break; case 4: trumpImage = "card-suit-heart"; imageColor = Color.RED; break; } BufferedImage componentImage = SVGUtil.createSVGImage(trumpImage, (int) (imageSize*0.8), (int) (imageSize*0.8)); componentImage = BufferedImageUtil.setPixelsToColour(componentImage, imageColor); final JButton button = AddButton(app, m, componentImage, ""); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); moveShown = true; break; } // Set next player move else if (a instanceof ActionSetNextPlayer && !m.isSwap()) { final int nextPlayerValue = ((ActionSetNextPlayer) a).who(); final String buttonText = "Next player: " + nextPlayerValue; final JButton button = AddButton(app, m, null, buttonText); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); moveShown = true; break; } // Pick the bet else if (a instanceof ActionBet) { final int betValue = ((ActionBet) a).count(); final int betWho = ((ActionBet) a).who(); final String buttonText = "P" + betWho + ", Bet: " + betValue; final JButton button = AddButton(app, m, null, buttonText); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); moveShown = true; break; } // Propose else if (a instanceof ActionPropose) { final String proposition = ((ActionPropose) a).proposition(); final String buttonText = "Propose: " + proposition; final JButton button = AddButton(app, m, null, buttonText); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); moveShown = true; break; } // Vote else if (a instanceof ActionVote) { final String vote = ((ActionVote) a).vote(); final String buttonText = "Vote: " + vote; final JButton button = AddButton(app, m, null, buttonText); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); moveShown = true; break; } // Moving a large piece if (a instanceof ActionMove) { final int componentValue = app.contextSnapshot().getContext(app).containerState(fromContainerIndex).what(m.from(), m.fromType()); if (componentValue != 0) { final Component c = context.components()[componentValue]; if (c.isLargePiece()) { final ComponentStyle componentStyle = app.bridge().getComponentStyle(c.index()); final int maxSize = Math.max(componentStyle.largePieceSize().x, componentStyle.largePieceSize().y); final double scaleFactor = 0.9 * imageSize / maxSize; BufferedImage componentImage = app.graphicsCache().getComponentImage(app.bridge(), fromContainerIndex, c, c.owner(), a.state(), 0, m.from(), 0, m.fromType(), imageSize, app.contextSnapshot().getContext(app), 0, 0, true); componentImage = BufferedImageUtil.resize(componentImage, (int)(scaleFactor * componentStyle.largePieceSize().x), (int)(scaleFactor * componentStyle.largePieceSize().y)); final JButton button = AddButton(app, m, componentImage, ""); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); moveShown = true; break; } } } } // If no "special" action found if (!moveShown) { // Pass if (m.isPass()) { final SVGGraphics2D g2d = new SVGGraphics2D(imageSize, imageSize); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setColor(Color.BLACK); g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND)); SVGtoImage.loadFromFilePath ( g2d, ImageUtil.getImageFullPath("button-pass"), new Rectangle(0,0,imageSize,imageSize), Color.BLACK, Color.WHITE, 0 ); final BufferedImage swapImage = SVGUtil.createSVGImage(g2d.getSVGDocument(), imageSize, imageSize); final JButton button = AddButton(app, m, swapImage, ""); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); } // Swap else if (m.isSwap()) { final SVGGraphics2D g2d = new SVGGraphics2D(imageSize, imageSize); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setColor(Color.BLACK); g2d.setStroke(new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND)); SVGtoImage.loadFromFilePath ( g2d, ImageUtil.getImageFullPath("button-swap"), new Rectangle(0,0,imageSize,imageSize), Color.BLACK, Color.WHITE, 0 ); final BufferedImage swapImage = SVGUtil.createSVGImage(g2d.getSVGDocument(), imageSize, imageSize); final JButton button = AddButton(app, m, swapImage, ""); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); } // Default fallback else { // // Only display non-duplicated moves. // final List<Action> moveActions = m.getActionsWithConsequences(context.currentInstanceContext()); // final List<Action> nonDuplicateActions = new ArrayList<>(); // for (final Action a1 : moveActions) // { // for (final Move m2 : validMoves) // { // if (!m2.getActionsWithConsequences(context.currentInstanceContext()).contains(a1)) // { // nonDuplicateActions.add(a1); // break; // } // } // } // // if (nonDuplicateActions.size() > 0) // for (final Action a : nonDuplicateActions) // actionString += a.toString() + "<br>"; // else // actionString += moveActions.toString() + "<br>"; final String actionString = MoveUtil.getMoveFormat(app, m, context); final JButton button = AddButton(app, m, null, actionString); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); } } } } //------------------------------------------------------------------------- @Override protected void buttonMove(final PlayerApp app, final Move move) { if (MoveHandler.moveChecks(app, move)) app.manager().ref().applyHumanMoveToGame(app.manager(), move); } //------------------------------------------------------------------------- }
12,110
35.92378
235
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/MoveDialog/PuzzleDialog.java
package app.display.dialogs.MoveDialog; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import app.PlayerApp; import app.display.dialogs.util.DialogUtil; import app.move.MoveHandler; import game.types.board.SiteType; import other.action.puzzle.ActionReset; import other.action.puzzle.ActionSet; import other.action.puzzle.ActionToggle; import other.context.Context; import other.move.Move; import other.state.container.ContainerState; /** * Dialog for selecting moves in deduction puzzles. * * @author Matthew.Stephenson */ public class PuzzleDialog extends JDialog { private static final long serialVersionUID = 1L; /** List of all JButtons on this dialog. */ final List<JButton> buttonList = new ArrayList<>(); //------------------------------------------------------------------------- /** * Show the Dialog. */ public static void createAndShowGUI(final PlayerApp app, final Context context, final int site) { try { final PuzzleDialog dialog = new PuzzleDialog(app, context, site); final Point drawPosn = new Point(MouseInfo.getPointerInfo().getLocation().x - dialog.getWidth() / 2, MouseInfo.getPointerInfo().getLocation().y - dialog.getHeight() / 2); DialogUtil.initialiseForcedDialog(dialog, "Puzzle Values", new Rectangle(drawPosn)); } catch (final Exception e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Create the dialog. */ public PuzzleDialog(final PlayerApp app, final Context context, final int site) { final int maxValue = context.board().getRange(context.board().defaultSite()).max(context); final int minValue = context.board().getRange(context.board().defaultSite()).min(context); final int numButtonsNeeded = maxValue - minValue + 2; int columnNumber = 0; int rowNumber = 0; columnNumber = (int) Math.ceil(Math.sqrt(numButtonsNeeded)); rowNumber = (int) Math.ceil((double) (numButtonsNeeded) / (double) columnNumber); final int buttonSize = 80; this.setSize(buttonSize * columnNumber, buttonSize * rowNumber + 30); getContentPane().setLayout(new GridLayout(0, columnNumber, 0, 0)); final ContainerState cs = context.state().containerStates()[0]; // Add in button that sets all bit values to true (i.e. reset button) final JButton buttonReset = new JButton(); buttonReset.setFocusPainted(false); getContentPane().add(buttonReset); if (app.bridge().settingsColour().getBoardColours()[2] == null) { buttonReset.setBackground(app.bridge().settingsColour().getBoardColours()[2]); } else if (app.bridge().settingsColour().getBoardColours()[2] != null) { buttonReset.setBackground(app.bridge().settingsColour().getBoardColours()[2]); } buttonReset.addMouseListener(new MouseListener() { @Override public void mouseClicked(final MouseEvent e) { // do nothing } @Override public void mousePressed(final MouseEvent e) { // do nothing } @Override public void mouseReleased(final MouseEvent e) { final Move resetMove = new Move(new ActionReset(context.board().defaultSite(), site, maxValue + 1)); resetMove.setDecision(true); if (MoveHandler.moveChecks(app, resetMove)) app.manager().ref().applyHumanMoveToGame(app.manager(), resetMove); dispose(); } @Override public void mouseEntered(final MouseEvent e) { // do nothing } @Override public void mouseExited(final MouseEvent e) { // do nothing } }); for (int i = minValue; i <= maxValue; i++) { final int puzzleValue = i; other.action.puzzle.ActionSet a = null; a = new ActionSet(context.board().defaultSite(), site, puzzleValue); a.setDecision(true); final Move m = new Move(a); m.setFromNonDecision(site); m.setToNonDecision(site); m.setEdgeMove(site); m.setDecision(true); final JButton button = new JButton(); try { final BufferedImage puzzleImage = new BufferedImage(buttonSize,buttonSize,BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = puzzleImage.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setFont(new Font("Arial", Font.PLAIN, 30)); g2d.setColor(Color.BLACK); app.bridge().getContainerStyle(0).drawPuzzleValue(puzzleValue, site, context, g2d, new Point(buttonSize/2,buttonSize/2), buttonSize/2); button.setIcon(new ImageIcon(puzzleImage)); } catch (final Exception ex) { System.out.println(ex); } button.setFocusPainted(false); getContentPane().add(button); if (!context.moves(context).moves().contains(m) && !app.settingsPlayer().illegalMovesValid()) { button.setEnabled(false); } else { paintButton(app, context, button, site, puzzleValue, context.board().defaultSite()); other.action.puzzle.ActionToggle a2 = null; a2 = new ActionToggle(context.board().defaultSite(), site, puzzleValue); a2.setDecision(true); final Move m2 = new Move(a2); m2.setFromNonDecision(site); m2.setToNonDecision(site); m2.setEdgeMove(site); m2.setDecision(true); button.addMouseListener(new MouseListener() { @Override public void mouseClicked(final MouseEvent e) { // do nothing } @Override public void mousePressed(final MouseEvent e) { // do nothing } @Override public void mouseReleased(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { MoveHandler.puzzleMove(app, site, puzzleValue, true, context.board().defaultSite()); dispose(); } else if (e.getButton() == MouseEvent.BUTTON3) { if (context.moves(context).moves().contains(m2) || app.settingsPlayer().illegalMovesValid()) { MoveHandler.puzzleMove(app, site, puzzleValue, false, context.board().defaultSite()); EventQueue.invokeLater(() -> { final ArrayList<Integer> optionsLeft = new ArrayList<>(); for (int j = minValue; j <= maxValue; j++) { if (cs.bit(site, j, context.board().defaultSite()) && buttonList.get(j - minValue).isEnabled()) { optionsLeft.add(Integer.valueOf(j)); } } if (optionsLeft.size() == 1) { MoveHandler.puzzleMove(app, site, optionsLeft.get(0).intValue(), true, context.board().defaultSite()); } paintButton(app, context, button, site, puzzleValue, context.board().defaultSite()); }); } } } @Override public void mouseEntered(final MouseEvent e) { // do nothing } @Override public void mouseExited(final MouseEvent e) { // do nothing } }); } buttonList.add(button); } } //------------------------------------------------------------------------- @SuppressWarnings("static-method") void paintButton(final PlayerApp app, final Context context, final JButton button, final int site, final int puzzleValue, final SiteType siteType) { final ContainerState cs = context.state().containerStates()[0]; if (!cs.bit(site, puzzleValue, siteType)) { button.setBackground(Color.GRAY); } else { if (app.bridge().settingsColour().getBoardColours()[2] == null) { button.setBackground(app.bridge().settingsColour().getBoardColours()[2]); } else if (app.bridge().settingsColour().getBoardColours()[2] != null) { button.setBackground(app.bridge().settingsColour().getBoardColours()[2]); } else { button.setBackground(Color.white); } } } }
8,291
27.791667
173
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/MoveDialog/SandboxDialog.java
package app.display.dialogs.MoveDialog; import java.awt.EventQueue; import java.awt.MouseInfo; import java.awt.Point; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import app.DesktopApp; import app.PlayerApp; import app.display.dialogs.util.DialogUtil; import app.utils.sandbox.SandboxUtil; import app.utils.sandbox.SandboxValueType; import game.equipment.component.Component; import game.types.board.SiteType; import main.Constants; import other.action.Action; import other.action.move.ActionAdd; import other.action.move.ActionInsert; import other.action.state.ActionSetCount; import other.action.state.ActionSetState; import other.action.state.ActionSetValue; import other.context.Context; import other.location.FullLocation; import other.location.Location; import other.move.Move; import other.state.container.ContainerState; import util.ContainerUtil; /** * Dialog for showing sandbox options. * * @author Matthew.Stephenson */ public class SandboxDialog extends MoveDialog { private static final long serialVersionUID = 1L; List<JButton> buttonList = new ArrayList<>(); //------------------------------------------------------------------------- /** * Show the Dialog. */ public static void createAndShowGUI(final PlayerApp app, final Location location, final SandboxValueType sandboxValueType) { try { final Context context = app.manager().ref().context(); if (context.components().length == 1) { DesktopApp.view().setTemporaryMessage("No valid components."); return; } final SandboxDialog dialog = new SandboxDialog(app, context, location, sandboxValueType); final Point drawPosn = new Point(MouseInfo.getPointerInfo().getLocation().x - dialog.getWidth() / 2, MouseInfo.getPointerInfo().getLocation().y - dialog.getHeight() / 2); DialogUtil.initialiseForcedDialog(dialog, "Sandbox (" + sandboxValueType.name() + ")", new Rectangle(drawPosn)); } catch (final Exception e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Create the dialog. */ public SandboxDialog(final PlayerApp app, final Context context, final Location location, final SandboxValueType sandboxValueType) { final int locnUpSite = location.site(); final SiteType locnType = location.siteType(); final int containerId = ContainerUtil.getContainerId(context, locnUpSite, locnType); if ( (containerId == -1) || !SandboxUtil.isSandboxAllowed(app, location) || app.manager().settingsNetwork().getActiveGameId() > 0 // Shouldn't have been able to get here if playing online game, but better safe than sorry! ) { EventQueue.invokeLater(() -> { dispose(); return; }); } else { final ContainerState cs = context.state().containerStates()[containerId]; final int numButtonsNeeded = SandboxUtil.numSandboxButtonsNeeded(app, sandboxValueType); setDialogLayout(app, context, numButtonsNeeded); // Setting some property of a component. if (sandboxValueType != SandboxValueType.Component) { for (int i = 0; i < numButtonsNeeded; i++) { final String buttonText = Integer.toString(i); final Move move = SandboxUtil.getSandboxVariableMove(app, location, sandboxValueType, i); final JButton button = AddButton(app, move, null, buttonText); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); } } // Adding/Removing a component. else { // Add in button to remove existing component final Move move = SandboxUtil.getSandboxRemoveMove(app, location); final JButton button = AddButton(app, move, null, ""); setDialogSize(button, columnNumber, rowNumber, buttonBorderSize); // Add in button for each possible component. for (int componentIndex = 1; componentIndex < context.components().length; componentIndex++) { final Component c = context.components()[componentIndex]; final BufferedImage im = app.graphicsCache().getComponentImage(app.bridge(), containerId, c, c.owner(), 0, 0, 0, 0, locnType,imageSize, app.contextSnapshot().getContext(app), 0, 0, true); // If not a stacking game, need to remove piece first if (!context.game().isStacking() || cs.sizeStack(locnUpSite, locnType) == 0) { final Move removeMove = SandboxUtil.getSandboxRemoveMove(app, location); final Move addMove = SandboxUtil.getSandboxAddMove(app, location, componentIndex); removeMove.actions().addAll(addMove.actions()); final JButton buttonAdd = AddButton(app, removeMove, im, ""); setDialogSize(buttonAdd, columnNumber, rowNumber, buttonBorderSize); } else { final Move insertMove = SandboxUtil.getSandboxInsertMove(app, location, componentIndex); final JButton buttonAdd = AddButton(app, insertMove, im, ""); setDialogSize(buttonAdd, columnNumber, rowNumber, buttonBorderSize); } } } } } //------------------------------------------------------------------------- @Override protected void buttonMove(final PlayerApp app, final Move move) { final Context context = app.manager().ref().context(); final int currentMover = context.state().mover(); final int nextMover = context.state().next(); final int previousMover = context.state().prev(); move.apply(context, true); context.state().setMover(currentMover); context.state().setNext(nextMover); context.state().setPrev(previousMover); EventQueue.invokeLater(() -> { app.contextSnapshot().setContext(app); app.updateTabs(context); app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED)); app.repaint(); }); dispose(); // Determine if there are any follow up values to set. if (context.game().requiresLocalState() && context.game().maximalLocalStates() > 1) { for (final Action action : move.actions()) { if (action instanceof ActionInsert || action instanceof ActionAdd) { createAndShowGUI(app, move.getFromLocation(), SandboxValueType.LocalState); return; } } } if (context.game().requiresCount() && context.game().maxCount() > 1) { for (final Action action : move.actions()) { if (action instanceof ActionInsert || action instanceof ActionAdd || action instanceof ActionSetState) { createAndShowGUI(app, move.getFromLocation(), SandboxValueType.Count); return; } } } if (context.game().requiresPieceValue() && context.game().maximalValue() > 1) { for (final Action action : move.actions()) { if (action instanceof ActionInsert || action instanceof ActionAdd || action instanceof ActionSetState || action instanceof ActionSetCount) { createAndShowGUI(app, move.getFromLocation(), SandboxValueType.Value); return; } } } if (context.game().requiresRotation() && context.game().maximalRotationStates() > 1) { for (final Action action : move.actions()) { if (action instanceof ActionInsert || action instanceof ActionAdd || action instanceof ActionSetState || action instanceof ActionSetCount || action instanceof ActionSetValue) { createAndShowGUI(app, move.getFromLocation(), SandboxValueType.Rotation); return; } } } } //------------------------------------------------------------------------- }
7,445
32.241071
192
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/editor/EditorActions.java
package app.display.dialogs.editor; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; public enum EditorActions { UNDO, REDO, DELETE_LINE, AUTOSUGGEST, COPY_SELECTION, REMOVE_SELECTION, PASTE_BUFFER, NO_ACTION, TAB; /** * @param e * @return action requested by the user */ public static EditorActions fromKeyEvent (KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_TAB) return TAB; if ((e.getModifiers() & InputEvent.CTRL_MASK) == 0) return NO_ACTION; switch (e.getKeyCode()) { case KeyEvent.VK_D: return DELETE_LINE; case KeyEvent.VK_Y: return REDO; case KeyEvent.VK_Z: return UNDO; case KeyEvent.VK_PERIOD: return AUTOSUGGEST; case KeyEvent.VK_C: return COPY_SELECTION; case KeyEvent.VK_X: return REMOVE_SELECTION; case KeyEvent.VK_V: return PASTE_BUFFER; } return NO_ACTION; } }
852
19.804878
71
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/editor/EditorDialog.java
package app.display.dialogs.editor; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.InputEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.border.EmptyBorder; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultEditorKit; import javax.swing.text.DefaultHighlighter; import javax.swing.text.DocumentFilter; import javax.swing.text.Highlighter; import javax.swing.text.Highlighter.HighlightPainter; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyleContext; import javax.swing.text.StyledDocument; import app.DesktopApp; import app.PlayerApp; import app.display.dialogs.util.DialogUtil; import app.utils.GameSetup; import graphics.ImageProcessing; import main.Constants; import main.EditorHelpData; import main.grammar.Description; import main.grammar.Report; import manager.Manager; import other.location.FullLocation; import parser.Parser; import parser.SelectionType; import parser.TokenRange; /** * Editor dialog. * @author cambolbro & matthew.stephenson & mrraow */ public class EditorDialog extends JDialog { private static final long serialVersionUID = -3636781014267129575L; private static final String TAB_STRING = "\t"; private static final String TAB_REPLACEMENT = " "; /** If the length of time between key presses is less than this, change is not stored in undoDescriptions */ public final static int TIMERLENGTH = 500; private final JPanel contentPanel = new JPanel(); private final List<UndoRecord> undoRecords = new ArrayList<>(); private int undoDescriptionsMarker = 0; static EditorDialog dialog; final EditorHelpData editorHelpData = EditorHelpData.get(); // Pre-initialise the EditorhelpData final boolean useColouredText; final JTextPane textArea; final JLabel verifiedByParser; String pasteBuffer = ""; SuggestionDialog suggestion = null; static boolean trace = false; //------------------------------------------------------------------------- /** * @param longDescription * @param textColoured * @param shortcutsActive */ public static void createAndShowGUI(final PlayerApp app, final boolean longDescription, final boolean textColoured, final boolean shortcutsActive) { try { dialog = new EditorDialog(app, longDescription, textColoured, shortcutsActive); DialogUtil.initialiseSingletonDialog(dialog, "Editor", null); dialog.addWindowListener(new WindowAdapter() { @Override public void windowClosed(final WindowEvent e) { DesktopApp.frame().setContentPane(DesktopApp.view()); DesktopApp.view().invalidate(); // WAS: setSize(DesktopApp.view().getSize()); let's see if anybody screams! app.repaint(); app.bridge().settingsVC().setSelectedFromLocation(new FullLocation(Constants.UNDEFINED)); } }); } catch (final Exception e) { e.printStackTrace(); } } //------------------------------------------------------------------------- /** * Create the dialog. */ private EditorDialog (final PlayerApp app, final boolean longDescription, final boolean useColouredText, final boolean shortcutsActive) { super(null, java.awt.Dialog.ModalityType.DOCUMENT_MODAL); this.useColouredText = useColouredText; setBounds(100, 100, 759, 885); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(new BorderLayout(0, 0)); textArea = createTextPane(); final JPanel noWrapPanel = new JPanel( new BorderLayout() ); noWrapPanel.add (textArea); final JScrollPane scrollPane = new JScrollPane( noWrapPanel ); contentPanel.add(scrollPane); final JPanel topPane = new JPanel(); topPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(topPane, BorderLayout.NORTH); JCheckBox verifiedByParserCheckbox = new JCheckBox(); verifiedByParserCheckbox.setHorizontalAlignment(SwingConstants.RIGHT); verifiedByParserCheckbox.setText("Parse Text"); verifiedByParserCheckbox.setSelected(app.settingsPlayer().isEditorParseText()); topPane.add(verifiedByParserCheckbox, BorderLayout.NORTH); final ActionListener parserListener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { app.settingsPlayer().setEditorParseText(verifiedByParserCheckbox.isSelected()); verifiedByParserCheckbox.setSelected(app.settingsPlayer().isEditorParseText()); app.addTextToStatusPanel("Please close and reopen the editor for this change to apply.\n"); } }; verifiedByParserCheckbox.addActionListener(parserListener); verifiedByParser = new JLabel(); verifiedByParser.setHorizontalAlignment(SwingConstants.RIGHT); topPane.add(verifiedByParser, BorderLayout.NORTH); final JPanel bottomPane = new JPanel(); bottomPane.setLayout(new BoxLayout(bottomPane, BoxLayout.LINE_AXIS)); getContentPane().add(bottomPane, BorderLayout.SOUTH); final JPanel buttonPaneLeft = new JPanel(); buttonPaneLeft.setLayout(new FlowLayout(FlowLayout.LEFT)); bottomPane.add(buttonPaneLeft); final JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); bottomPane.add(buttonPane); addNewButton(app, buttonPaneLeft); addCompileButton(app, buttonPane); addLoadButton(app, buttonPane); addDebugButton(app, buttonPane); addSaveButton(app, buttonPane); addNewFileButton(app, buttonPane); addCancelButton(buttonPane); final String gameDescription = getGameDescription(app, longDescription); setText(app, gameDescription.replace("\r", "")); // This character can cause discrepancies between internal model and document model for textArea if (useColouredText) { setTextUpdateMonitor(app); } if (shortcutsActive){ addUndoHandler(app); } addMouseListener(app); // addMouseMotionListener(textArea); } //------------------------------------------------------------------------- private static JTextPane createTextPane() { final JTextPane jTextPane = new JTextPane(); // This prevents switching between getText(0 and getDocument().getText(...) causing weird discrepancies in the character positions jTextPane.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "\n"); jTextPane.setFocusTraversalKeysEnabled(false); jTextPane.addFocusListener(new FocusListener() { @Override public void focusGained(final FocusEvent e) { jTextPane.getCaret().setVisible(true); } @Override public void focusLost(final FocusEvent e) { jTextPane.getCaret().setVisible(true); } }); final StyledDocument styledDoc = jTextPane.getStyledDocument(); if (styledDoc instanceof AbstractDocument) { final AbstractDocument doc = (AbstractDocument)styledDoc; doc.setDocumentFilter(new DocumentFilter() { @Override public void insertString(final FilterBypass fb, final int offset, final String text, final AttributeSet attrs) throws BadLocationException { super.insertString(fb, offset, text.replace(TAB_STRING, TAB_REPLACEMENT), attrs); } @Override public void replace(final FilterBypass fb, final int offset, final int length, final String text, final AttributeSet attrs) throws BadLocationException { if (text.equals(TAB_STRING)) { indentRange(jTextPane); return; // Dealt with elsewhere! } super.replace(fb, offset, length, text.replace(TAB_STRING, TAB_REPLACEMENT), attrs); } }); } return jTextPane; } //------------------------------------------------------------------------- private void addUndoHandler(final PlayerApp app) { undoRecords.add(new UndoRecord(textArea)); final Timer undoRecordTimer = new Timer(TIMERLENGTH, new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { storeUndoText(); } }); undoRecordTimer.setRepeats(false); // undo, redo and delete line textArea.addKeyListener(new KeyAdapter() { @Override public void keyPressed(final KeyEvent e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { highlightMatchingBracket(); if (trace) System.out.println(">>EVENT: textArea/keypressed"); undoRecordTimer.stop(); storeUndoText(); switch (EditorActions.fromKeyEvent(e)) { case DELETE_LINE: if (trace) System.out.println(">>EVENT: textArea/keypressed delete line"); storeUndoText(); deleteLine(app); break; case REDO: if (trace) System.out.println(">>EVENT: textArea/keypressed redo"); storeUndoText(); redo(); break; case UNDO: if (trace) System.out.println(">>EVENT: textArea/keypressed undo"); storeUndoText(); undo(); break; case NO_ACTION: if (trace) System.out.println(">>EVENT: textArea/keypressed ignored "+KeyEvent.getKeyText(e.getKeyChar())); break; case COPY_SELECTION: copySelection(); if (trace) System.out.println(">>EVENT: textArea/keypressed copy selection "+pasteBuffer); break; case REMOVE_SELECTION: storeUndoText(); removeSelection(app); if (trace) System.out.println(">>EVENT: textArea/keypressed remove selection "+pasteBuffer); break; case PASTE_BUFFER: storeUndoText(); pasteBuffer(app); if (trace) System.out.println(">>EVENT: textArea/keypressed paste "+pasteBuffer); break; case AUTOSUGGEST: // Get current location if (trace) System.out.println(">>EVENT: textArea/keypressed autosuggest"); storeUndoText(); showAutosuggest(app, TextPaneUtils.cursorCoords(textArea), true); break; case TAB: // Handled in the text filter! //if (trace) System.out.println(">>EVENT: textArea/keypressed autosuggest"); //storeUndoText(); //indentRange(); break; } undoRecordTimer.start(); } }); } @Override public void keyTyped(final KeyEvent e) { if ((e.getModifiers() & InputEvent.CTRL_MASK) != 0) return; // Ignore control keys - they are dealt with elsewhere if (e.getKeyChar()==KeyEvent.CHAR_UNDEFINED) return; // Not a display character if (Character.isWhitespace(e.getKeyChar())) return; // Context menu not appropriate after a space? if (trace) System.out.println(">>EVENT: textArea/keytyped - maybe showing autosuggest"); storeUndoText(); // let typing finish first, then show the suggestions dialogue EventQueue.invokeLater(new Runnable() { @Override public void run() { showAutosuggest(app, TextPaneUtils.cursorCoords(textArea), true); } }); } }); } //------------------------------------------------------------------------- void deleteLine(final PlayerApp app) { final int newCaretPosition = TextPaneUtils.startOfCaretCurrentRow(textArea); final int caretRowNumber = TextPaneUtils.getCaretRowNumber(textArea); // remove the current caret line final String[] lines = textAreaFullDocument().split("\n"); final StringBuilder newDesc = new StringBuilder(); for (int s = 0; s < lines.length; s++) if (s != caretRowNumber-1) newDesc.append(lines[s]).append("\n"); setText(app, newDesc.toString()); textArea.setCaretPosition(newCaretPosition); } void storeUndoText () { if (undoRecords.get(undoDescriptionsMarker).ignoreChanges(textArea)) return; // Roll back to current cursor for (int i = undoRecords.size()-1; i > undoDescriptionsMarker ; i--) undoRecords.remove(i); // Add new text undoDescriptionsMarker++; undoRecords.add(new UndoRecord(textArea)); } //------------------------------------------------------------------------- void redo() { if (undoDescriptionsMarker >= undoRecords.size()-1) return; undoDescriptionsMarker++; undoRecords.get(undoDescriptionsMarker).apply(textArea); } //------------------------------------------------------------------------- void undo() { if (undoDescriptionsMarker <= 0) return; undoDescriptionsMarker--; undoRecords.get(undoDescriptionsMarker).apply(textArea); } //------------------------------------------------------------------------- private void addMouseListener(final PlayerApp app) { textArea.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { if (trace) System.out.println(">>EVENT: textArea/mouseClicked"); if (SwingUtilities.isRightMouseButton(e)) { if (trace) System.out.println(">>EVENT: textArea/mouseClicked/right click"); showAutosuggest(app, e.getPoint(), false); } else if (e.getClickCount()==1) { if (trace) System.out.println(">>EVENT: textArea/mouseClicked/single click"); if (suggestion != null) suggestion.setVisible(false); } else if (e.getClickCount()==2) { if (trace) System.out.println(">>EVENT: textArea/mouseClicked/double click"); final int caretPos = textArea.getCaretPosition(); final TokenRange range = Parser.tokenScope(textArea.getText(), caretPos, true, SelectionType.SELECTION); if (range != null) { textArea.setSelectionStart(range.from()); textArea.setSelectionEnd(range.to()); } } highlightMatchingBracket(); } // @Override public void mousePressed(MouseEvent e) // @Override public void mouseReleased(MouseEvent e) // @Override public void mouseEntered(MouseEvent e) // @Override public void mouseExited(MouseEvent e) }); } //------------------------------------------------------------------------- void highlightMatchingBracket() { textArea.getHighlighter().removeAllHighlights(); final int caretPos = textArea.getCaretPosition(); String prevChar; try { prevChar = textArea.getText(caretPos-1, 1); int matchingCharLocation = -1; if (prevChar.equals("(")) matchingCharLocation = findMatching("(", ")", caretPos, true); else if (prevChar.equals(")")) matchingCharLocation = findMatching(")", "(", caretPos, false); else if (prevChar.equals("{")) matchingCharLocation = findMatching("{", "}", caretPos, true); else if (prevChar.equals("}")) matchingCharLocation = findMatching("}", "{", caretPos, false); else if (prevChar.equals("[")) matchingCharLocation = findMatching("[", "]", caretPos, true); else if (prevChar.equals("]")) matchingCharLocation = findMatching("]", "[", caretPos, false); if (matchingCharLocation != -1) { Highlighter highlighter = textArea.getHighlighter(); HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW); highlighter.addHighlight(matchingCharLocation, matchingCharLocation+1, painter); } } catch (BadLocationException e) { // carry on } } int findMatching(final String selectedString, final String matchingString, final int initialPosition, final boolean checkForward) { int caretPos = initialPosition; int numSelectedString = 1; String textToCheck; try { if (checkForward) { textToCheck = textArea.getText(caretPos, textArea.getText().length()-caretPos); while (textToCheck.length() > 0) { if (String.valueOf(textToCheck.charAt(0)).equals(matchingString)) numSelectedString--; else if (String.valueOf(textToCheck.charAt(0)).equals(selectedString)) numSelectedString++; if (numSelectedString == 0) return caretPos; caretPos++; textToCheck = textToCheck.substring(1); } } else { textToCheck = textArea.getText(0, caretPos-1); while (textToCheck.length() > 0) { if (String.valueOf(textToCheck.charAt(textToCheck.length()-1)).equals(matchingString)) numSelectedString--; else if (String.valueOf(textToCheck.charAt(textToCheck.length()-1)).equals(selectedString)) numSelectedString++; if (numSelectedString == 0) return caretPos-2; caretPos--; textToCheck = textToCheck.substring(0,textToCheck.length()-1); } } } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } return -1; } //------------------------------------------------------------------------- void showAutosuggest(final PlayerApp app, final Point point, final boolean usePartial) { if (suggestion != null) suggestion.setVisible(false); if (!app.settingsPlayer().editorAutocomplete()) return; if (trace) System.out.println("### Showing Autosuggest"); if (!usePartial) { final int posn = textArea.viewToModel(point); textArea.setCaretPosition(posn); } try { final Rectangle rect = textArea.modelToView(textArea.getCaretPosition()); final Point screenPos = new Point(rect.x, rect.y); SwingUtilities.convertPointToScreen(screenPos, textArea); screenPos.y += rect.height; suggestion = new SuggestionDialog(app, EditorDialog.this, screenPos, usePartial); } catch (final Exception e) { e.printStackTrace(); } } //------------------------------------------------------------------------- private static String getGameDescription (final PlayerApp app, final boolean longDescription) { String gameDescription = ""; if (longDescription) { gameDescription = app.manager().ref().context().game().description().expanded(); } else { gameDescription = app.manager().ref().context().game().description().raw(); } return gameDescription; } //------------------------------------------------------------------------- private void setTextUpdateMonitor(final PlayerApp app) { final Timer colourRecordTimer = new Timer(TIMERLENGTH, new ActionListener() { @Override public void actionPerformed(final ActionEvent arg0) { setText(app, textAreaFullDocument()); } }); colourRecordTimer.setRepeats(false); textArea.addKeyListener(new KeyAdapter() { @Override public void keyPressed(final KeyEvent e) { EventQueue.invokeLater(new Runnable() { @Override public void run() { colourRecordTimer.stop(); colourRecordTimer.start(); } }); } }); } //------------------------------------------------------------------------- final String textAreaFullDocument() { return textArea.getText(); } //------------------------------------------------------------------------- final String documentForSave() { final String full = textAreaFullDocument(); return full.replace("\n", System.lineSeparator()); } //------------------------------------------------------------------------- private static JButton addButton(final JPanel buttonPane, final String label, final ActionListener listener) { final JButton button = new JButton(label); button.setActionCommand(label); button.addActionListener(listener); buttonPane.add(button); return button; } //------------------------------------------------------------------------- private static JButton addCancelButton(final JPanel buttonPane) { final ActionListener listener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final Component component = (Component) e.getSource(); final JDialog dialog1 = (JDialog) SwingUtilities.getRoot(component); dialog1.dispose(); } }; return addButton (buttonPane, "Cancel", listener); } //------------------------------------------------------------------------- private JButton addNewFileButton(final PlayerApp app, final JPanel buttonPane) { final ActionListener listener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { saveGameDescription(app, documentForSave()); } }; return addButton (buttonPane, "Save new file", listener); } //------------------------------------------------------------------------- private JButton addSaveButton(final PlayerApp app, final JPanel buttonPane) { final ActionListener listener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { // TDO: Consider an "are you sure?" option. try (PrintWriter out = new PrintWriter(app.manager().savedLudName())) { out.println(documentForSave()); System.out.println(app.manager().savedLudName() + " overridden"); } catch (final FileNotFoundException e2) { // Fixme - report to user System.out.println("You cannot override a game description loaded from memory. Use the 'Save new file' option"); } } }; return addButton (buttonPane, "Override existing file", listener); } //------------------------------------------------------------------------- private JButton addNewButton(final PlayerApp app, final JPanel buttonPane) { final ActionListener listener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { setText(app, "(game <string> [<players>] [<mode>] [<equipment>] [<rules>])"); } }; final JButton newButton = addButton (buttonPane, "New", listener); return newButton; } //------------------------------------------------------------------------- private JButton addCompileButton(final PlayerApp app, final JPanel buttonPane) { final ActionListener listener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { GameSetup.compileAndShowGame(app, textAreaFullDocument(), false); } }; final JButton okButton = addButton (buttonPane, "Compile", listener); getRootPane().setDefaultButton(okButton); return okButton; } //------------------------------------------------------------------------- private JButton addLoadButton(final PlayerApp app, final JPanel buttonPane) { final ActionListener listener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final int fcReturnVal = DesktopApp.gameFileChooser().showOpenDialog(DesktopApp.frame()); if (fcReturnVal == JFileChooser.APPROVE_OPTION) { app.manager().ref().interruptAI(app.manager()); final File file = DesktopApp.gameFileChooser().getSelectedFile(); try { setText(app, String.join("\n", Files.readAllLines(file.toPath()))); dialog.toFront(); } catch (final IOException e1) { e1.printStackTrace(); } } } }; final JButton okButton = addButton (buttonPane, "Load", listener); return okButton; } //------------------------------------------------------------------------- private JButton addDebugButton(final PlayerApp app, final JPanel buttonPane) { final ActionListener listener = new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { GameSetup.compileAndShowGame(app, textAreaFullDocument(), true); } }; final JButton okButton = addButton (buttonPane, "Debug", listener); return okButton; } //------------------------------------------------------------------------- void setText(final PlayerApp app, final String gameDescription) { final int pos = textArea.getCaretPosition(); final int selStart = textArea.getSelectionStart(); final int selEnd = textArea.getSelectionEnd(); if (useColouredText) { textArea.setText(""); final String[] tokens = new LudiiTokeniser(gameDescription).getTokens(); int bracketCount = 0; int curlyCount = 0; boolean inAngle = false; EditorTokenType lastTokenType = null; for (final String token : tokens) { final EditorTokenType ttype = LudiiTokeniser.typeForToken(token, inAngle, lastTokenType); switch (ttype) { case OPEN_CURLY: appendToPane(app, textArea, token, EditorLookAndFeel.bracketColourByDepthAndType(ttype, curlyCount), ttype.isBold()); curlyCount++; break; case OPEN_ROUND: case OPEN_SQUARE: appendToPane(app, textArea, token, EditorLookAndFeel.bracketColourByDepthAndType(ttype, bracketCount), ttype.isBold()); bracketCount++; break; case CLOSE_CURLY: curlyCount--; appendToPane(app, textArea, token, EditorLookAndFeel.bracketColourByDepthAndType(ttype, curlyCount), ttype.isBold()); break; case CLOSE_ROUND: case CLOSE_SQUARE: bracketCount--; appendToPane(app, textArea, token, EditorLookAndFeel.bracketColourByDepthAndType(ttype, bracketCount), ttype.isBold()); break; case OPEN_ANGLE: inAngle = true; appendToPane(app, textArea, token, ttype.fgColour(), ttype.isBold()); break; case CLOSE_ANGLE: appendToPane(app, textArea, token, ttype.fgColour(), ttype.isBold()); inAngle = false; break; case WHITESPACE: case INT: case FLOAT: case OTHER: case STRING: case LABEL: case CLASS: case ENUM: case RULE: appendToPane(app, textArea, token, ttype.fgColour(), ttype.isBold()); break; } lastTokenType = ttype; } } else { textArea.setText(gameDescription); } textArea.setCaretPosition(pos); if (selStart != selEnd) { textArea.setSelectionStart(selStart); textArea.setSelectionEnd(selEnd); } if (app.settingsPlayer().isEditorParseText()) checkParseState(app.manager(), gameDescription); highlightMatchingBracket(); } //------------------------------------------------------------------------- private final void checkParseState(final Manager manager, final String gameStr) { try { final Description gameDescription = new Description(gameStr); final boolean success = Parser.parseTest ( gameDescription, manager.settingsManager().userSelections(), new Report(), false ); wasVerifiedByParser(success ? true : false); } catch (final Exception e) { wasVerifiedByParser(false); } } //------------------------------------------------------------------------- /** * Called with the result of the parser when trying to verify the game description. */ private void wasVerifiedByParser(final boolean b) { final int r = 7; final Color markerColour = b ? Color.GREEN : Color.RED; final BufferedImage image = new BufferedImage(r*4, r*3, BufferedImage.TYPE_INT_ARGB); final Graphics2D g2d = image.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); ImageProcessing.ballImage(g2d, r, r, r, markerColour); final ImageIcon icon = new ImageIcon(image); verifiedByParser.setIcon(icon); } //------------------------------------------------------------------------- public static String saveGameDescription (final PlayerApp app, final String desc) { final int fcReturnVal = DesktopApp.saveGameFileChooser().showSaveDialog(DesktopApp.frame()); if (fcReturnVal == JFileChooser.APPROVE_OPTION) { File file = DesktopApp.saveGameFileChooser().getSelectedFile(); final String filePath = file.getAbsolutePath(); if (!filePath.endsWith(".lud")) { file = new File(filePath + ".lud"); } try (PrintWriter out = new PrintWriter(file.getAbsolutePath())) { out.println(desc); } catch (final FileNotFoundException e) { e.printStackTrace(); } return filePath; } return null; } //------------------------------------------------------------------------- private static void appendToPane ( final PlayerApp app, final JTextPane tp, final String msg, final Color c, final boolean isBold ) { final StyleContext sc = StyleContext.getDefaultStyleContext(); AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); aset = sc.addAttribute(aset, StyleConstants.Size, Integer.valueOf(app.settingsPlayer().editorFontSize())); aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Arial"); aset = sc.addAttribute(aset, StyleConstants.Bold, Boolean.valueOf(isBold)); aset = sc.addAttribute(aset, StyleConstants.Alignment, Integer.valueOf(StyleConstants.ALIGN_JUSTIFIED)); final int len = tp.getDocument().getLength(); tp.setCaretPosition(len); tp.setCharacterAttributes(aset, false); tp.replaceSelection(msg); } //------------------------------------------------------------------------- final String getText() { return textArea.getText(); } final int getCaretPosition() { return textArea.getCaretPosition(); } final void applyBackspace(final PlayerApp app) { final int pos = textArea.getCaretPosition(); textArea.select(pos-1, pos); textArea.replaceSelection(""); setText(app, textArea.getText()); } final void applyDelete(final PlayerApp app) { final int pos = textArea.getCaretPosition(); textArea.select(pos, pos+1); textArea.replaceSelection(""); setText(app, textArea.getText()); } final void insertCharacter(final PlayerApp app, final char keyChar) { final String keyVal = Character.toString(keyChar); TextPaneUtils.insertAtCaret(textArea, keyVal); setText(app, textArea.getText()); } final void cursorLeft() { final int pos = textArea.getCaretPosition(); if (pos > 0) textArea.setCaretPosition(pos-1); if (trace) System.out.println("LEFT"); } final void cursorRight() { final int pos = textArea.getCaretPosition(); if (pos < textArea.getText().length()) textArea.setCaretPosition(pos+1); if (trace) System.out.println("RIGHT"); } final void replaceTokenScopeWith(final PlayerApp app, final String substitution, final boolean isPartial) { try { final int caretPos = textArea.getCaretPosition(); final TokenRange range = Parser.tokenScope(textArea.getText(), caretPos, isPartial, isPartial ? SelectionType.TYPING : SelectionType.CONTEXT); if (range == null) { if (trace) System.out.println("No range available"); return; } final String pre = textArea.getText(0, range.from()); final String post = textArea.getText(range.to(), textArea.getText().length() - range.to()); final String after = pre + substitution + post; setText(app, after); textArea.setCaretPosition(pre.length()+substitution.length()); } catch (final BadLocationException e) { e.printStackTrace(); } } final void pasteBuffer(final PlayerApp app) { if (!pasteBuffer.isEmpty()) { textArea.replaceSelection(pasteBuffer); setText(app, textArea.getText()); } } final void removeSelection(final PlayerApp app) { final int start = textArea.getSelectionStart(); final int end = textArea.getSelectionEnd(); if (start > end) { pasteBuffer = textArea.getSelectedText(); textArea.replaceSelection(""); setText(app, textArea.getText()); } } final void copySelection() { final int start = textArea.getSelectionStart(); final int end = textArea.getSelectionEnd(); if (start > end) { pasteBuffer = textArea.getSelectedText(); } } static final void indentRange(final JTextPane textArea) { if (trace) System.out.println("### INDENT ###"); final int start = textArea.getSelectionStart(); final int end = textArea.getSelectionEnd(); if (trace) System.out.println("start: "+start+", end: "+end); if (start < end) { final String test = textArea.getSelectedText(); final String[] lines = test.split("\\R"); final String fixed = TAB_REPLACEMENT + String.join("\n"+TAB_REPLACEMENT, lines); textArea.replaceSelection(fixed); textArea.setSelectionStart(start); textArea.setSelectionEnd(start+fixed.length()); } else { textArea.replaceSelection(TAB_REPLACEMENT); } } void returnFocus() { textArea.requestFocus(); } public String charsBeforeCursor() { if (textArea.getText().isEmpty()) return ""; final int pos = textArea.getCaretPosition(); int start = pos-1; try { while (start > 0 && Character.isLetterOrDigit(textArea.getText(start-1,1).charAt(0))) start--; final String result = textArea.getText(Math.max(0,start),pos-start); if (trace) System.out.println("charsBeforeCursor returning "+start+":"+pos+":"+result); return result; } catch (final Exception e) { e.printStackTrace(); return ""; } } //------------------------------------------------------------------------- }
34,296
28.979895
165
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/editor/EditorHelpDataHelper.java
package app.display.dialogs.editor; import static app.display.dialogs.editor.EditorLookAndFeel.BR; import static app.display.dialogs.editor.EditorLookAndFeel.CELL_END; import static app.display.dialogs.editor.EditorLookAndFeel.CELL_START; import static app.display.dialogs.editor.EditorLookAndFeel.DOC_ROW_START; import static app.display.dialogs.editor.EditorLookAndFeel.DOC_TABLE_START; import static app.display.dialogs.editor.EditorLookAndFeel.HEADING_END; import static app.display.dialogs.editor.EditorLookAndFeel.HEADING_START; import static app.display.dialogs.editor.EditorLookAndFeel.KEYWORD_END; import static app.display.dialogs.editor.EditorLookAndFeel.KEYWORD_START; import static app.display.dialogs.editor.EditorLookAndFeel.MIN_CELL_DISTANCE; import static app.display.dialogs.editor.EditorLookAndFeel.PARAM_TABLE_START; import static app.display.dialogs.editor.EditorLookAndFeel.ROW_END; import static app.display.dialogs.editor.EditorLookAndFeel.ROW_START; import static app.display.dialogs.editor.EditorLookAndFeel.TABLE_END; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import parser.KnownDefines; import main.EditorHelpData; //----------------------------------------------------------------------------- /** * Formats the editor help data. * * @author mrraow and cambolbro */ public final class EditorHelpDataHelper { private static boolean VERBOSE = true; /** * @param type * @param n * @return full document for a given constructor */ public static final String fullDocumentForConstructor(final EditorHelpData data, final String type, final int n) { //System.out.println("type: " + type); final StringBuilder sb = new StringBuilder(); sb.append(DOC_TABLE_START); sb.append(DOC_ROW_START); sb.append(CELL_START); sb.append(escapeForHTML(data.typeDocString(type))); final String remarks = data.typeRemarksString(type); if (remarks != null && !remarks.isEmpty()) { //sb.append(REMARK_START); sb.append(" <br> "); sb.append(escapeForHTML(remarks)); //sb.append(REMARK_END); } sb.append(CELL_END); sb.append(ROW_END); // If there are no distinct constructors, we're finished if (n < 0) { sb.append(TABLE_END); return sb.toString(); } sb.append(DOC_ROW_START); sb.append(CELL_START).append(highlightKeyword(escapeForHTML(data.nthConstructorLine(type, n)))).append(CELL_END); sb.append(ROW_END); final List<String> paramLines = data.nthConstructorParamLines(type, n); if (paramLines != null && paramLines.size() > 0) { sb.append(DOC_ROW_START); sb.append(CELL_START); sb.append(HEADING_START).append("Parameters").append(HEADING_END); sb.append(PARAM_TABLE_START); for (final String line: paramLines) { final int pos = line.lastIndexOf(":"); if (pos > 0) { sb.append(ROW_START); sb.append(CELL_START).append(escapeForHTML(line.substring(0, pos).trim())).append(MIN_CELL_DISTANCE).append(CELL_END); sb.append(CELL_START).append(escapeForHTML(line.substring(pos+1).trim())).append(CELL_END); sb.append(ROW_END); } else { sb.append(ROW_START).append(CELL_START).append(escapeForHTML(line)).append(CELL_END).append(ROW_END); } } sb.append(TABLE_END); sb.append(CELL_END); sb.append(ROW_END); } final List<String> exampleLines = data.nthConstructorExampleLines(type, n); if (exampleLines != null && exampleLines.size() > 0) { sb.append(DOC_ROW_START); sb.append(CELL_START); sb.append(HEADING_START).append("Examples").append(HEADING_END); for (final String line: exampleLines) { sb.append(BR); sb.append(escapeForHTML(line)); } sb.append(CELL_END); sb.append(ROW_END); } sb.append(TABLE_END); return sb.toString(); } /** * @param text * @return the keyword embedded in this text */ public static final String extractKeyword (final String text) { if (text==null || text.length()==0) return ""; if (text.charAt(0) != '(' && text.charAt(0) != '<' && text.charAt(0) != '[' && text.charAt(0) != '{') return text; int pos = 1; while (pos < text.length() && Character.isLetterOrDigit(text.charAt(pos))) pos++; return text.substring(1,pos); } /** * @param text * @return same text with the keyword highlighted */ public static final String highlightKeyword (final String text) { if (text==null || text.length()==0) return ""; if (text.charAt(0) != '(') return text; int pos = 1; while (pos < text.length() && Character.isLetterOrDigit(text.charAt(pos))) pos++; return text.substring(0,1)+KEYWORD_START+text.substring(1,pos)+KEYWORD_END+text.substring(pos); } /** * @param text * @return text with various HTML entities escaped which might otherwise cause formatting problems */ public static final String escapeForHTML(final String text) { if (text==null|| text.isEmpty()) return ""; return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;"); } /** * @param data * @param rawCandidates * @param isPartial in partial mode, only the main javadoc is shown, and constructors are stripped * @return Suggestion lists matching these candidates. */ public static final List<SuggestionInstance> suggestionsForClasspaths ( final EditorHelpData data, final List<String> rawCandidates, final boolean isPartial ) { final List<SuggestionInstance> suggestions = new ArrayList<>(); final Set<String> allCandidates = expandHierarchy(data, rawCandidates); Set<String> uniqueEnums = new HashSet<>(); Set<String> uniqueConstructors = new HashSet<>(); for (final String classPath : allCandidates) { if (isDefine(classPath)) { final StringBuilder sb = new StringBuilder(); sb.append(escapeForHTML(data.defineDocString(classPath))); final List<String> exampleLines = data.defineExampleLines(classPath); if (exampleLines != null && exampleLines.size() > 0) { // FIXME - should use the same formatting as fullDocumentForConstructor, whatever that is! sb.append(BR); sb.append(BR); sb.append(HEADING_START).append("Examples").append(HEADING_END); for (final String line: exampleLines) { sb.append(BR); sb.append(escapeForHTML(line)); } } if (isPartial) { final String token = extractKeyword(classPath); if (uniqueConstructors.add(token)) suggestions.add(new SuggestionInstance(classPath, token, token, sb.toString())); } else { suggestions.add(new SuggestionInstance(classPath, classPath, classPath, sb.toString())); } } if (isEnum(classPath)) { String key = classPath.replace('$', '.'); Collection<String> enums = data.enumConstantLines(key); if (enums==null || enums.size()==0) { final String[] parts = classPath.split("\\$"); key = parts[0]; enums = data.enumConstantLines(key); } if (enums==null || enums.size()==0) { if (VERBOSE) System.out.println("Can't find enums for "+classPath); continue; } if (VERBOSE) System.out.println("Processing "+enums.size()+" enums for "+classPath+": "+enums); final String javadoc = data.typeDocString(key); for (final String label : enums) { final int pos = label.indexOf(":"); if (pos > 0) { final String substitution = label.substring(0,pos).trim(); final String embeddedDoc = label.substring(pos+1).trim(); if (uniqueEnums.add(substitution)) suggestions.add(new SuggestionInstance(classPath, label, substitution, javadoc+BR+BR+embeddedDoc)); } else { if (uniqueEnums.add(label)) suggestions.add(new SuggestionInstance(classPath, label, label, javadoc)); } } } else if (classPath.equalsIgnoreCase("true")) { // This would ideally be part of the grammar, but that would not // let us distinguish between primitive boolean and BooleanFunction suggestions.add(new SuggestionInstance("false", "false", "false", "Make condition false.")); } else if (classPath.equalsIgnoreCase("false")) { // This would ideally be part of the grammar, but that would not // let us distinguish between primitive boolean and BooleanFunction suggestions.add(new SuggestionInstance("true", "true", "true", "Make condition true.")); } else { final int count = data.numConstructors(classPath); if (count > 0) { if (VERBOSE) System.out.println("Found "+count+" constructors for "+classPath); if (isPartial) { final String label = data.nthConstructorLine(classPath, 0); final String token = extractKeyword(label); if (uniqueConstructors.add(token)) { final String javadoc = fullDocumentForConstructor(data, classPath, -1); suggestions.add(new SuggestionInstance(classPath, token, token, javadoc)); } } else { // Is class with constructors for (int n = 0; n < count; n++) { final String label = data.nthConstructorLine(classPath, n); if (VERBOSE) System.out.println( "#"+n+": "+label); final String javadoc = fullDocumentForConstructor(data, classPath, n); suggestions.add(new SuggestionInstance(classPath, label, label, javadoc)); } } } else { final String key = classPath; final String javadoc = data.typeDocString(key); final List<String> enums = data.enumConstantLines(key); if (enums != null && enums.size() > 0) { if (VERBOSE) System.out.println("Processing "+enums.size()+"enum constant lines for "+key+": "+enums); for (final String label : enums) { final int pos = label.indexOf(":"); if (pos > 0) { final String substitution = label.substring(0,pos).trim(); final String embeddedDoc = label.substring(pos+1).trim(); suggestions.add(new SuggestionInstance(classPath, label, substitution, javadoc+BR+BR+embeddedDoc)); } else { suggestions.add(new SuggestionInstance(classPath, label, label, javadoc)); } } } final List<String> subclasses = data.subclassDocLines(classPath); if (subclasses != null && subclasses.size() > 0) { for (final String label : subclasses) { final int pos = label.indexOf(":"); if (pos > 0) { final String substitution = label.substring(0,pos).trim(); final String embeddedDoc = label.substring(pos+1).trim(); suggestions.add(new SuggestionInstance(classPath, label, substitution, javadoc+BR+BR+embeddedDoc)); } else { suggestions.add(new SuggestionInstance(classPath, label, label, javadoc)); } } } } } } return suggestions; } private static Set<String> expandHierarchy(final EditorHelpData data, final List<String> rawCandidates) { final Set<String> results = new HashSet<>(); if (VERBOSE) System.out.println("Expanding: "+rawCandidates); for (int pos = 0; pos < rawCandidates.size(); pos++) { final String candidate = rawCandidates.get(pos); final String key = removeAngleBrackets(candidate); final List<String> subclasses = data.subclassDocLines(key); if (subclasses != null && subclasses.size() > 0) results.addAll(expandHierarchy(data, subclasses)); else if (data.numConstructors(key) > 0 || "true".equals(candidate) || "false".equals(candidate) || isEnum(key)) results.add(key); } return results; } private static String removeAngleBrackets(final String candidate) { if (candidate.startsWith("<")) return candidate.substring(1, candidate.indexOf(">")); return candidate; } /** * @param label * @return label with markup */ public static final String formatLabel (final String label) { // Split at whitespace, fix HTML markup... ampersand must be first! final String[] tokens = escapeForHTML(label).split(" "); // Add markup if (tokens[0].startsWith("(")) tokens[0] = "("+KEYWORD_START+tokens[0].substring(1)+KEYWORD_END; else tokens[0] = KEYWORD_START+tokens[0]+KEYWORD_END; final String result = "<html>"+String.join("&nbsp;", tokens)+"</html>"; return result; } private static boolean isEnum(final String classPath) { return classPath.contains("$"); } private static final boolean isDefine(final String classPath) { final String key = EditorHelpDataHelper.extractKeyword(classPath); return KnownDefines.getKnownDefines().knownDefines().get(key) != null; } }
12,758
29.893462
123
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/editor/EditorLookAndFeel.java
package app.display.dialogs.editor; import java.awt.Color; /** * All colour information in one place! * @author mrraow and cambolbro */ public class EditorLookAndFeel { static final String PARAM_TABLE_START = "<table class=\"params\" border=\"0\" cellspacing=0 cellpadding=0>"; static final String DOC_TABLE_START = "<table cellspacing=0 cellpadding=10 width='100%' >"; //"<table class=\"doc\" width=\"100%\" border=1 cellspacing=0 cellpadding=10>"; static final String TABLE_END = "</table>"; static final String ROW_START = "<tr>"; static final String ROW_END = "</tr>"; static final String DOC_ROW_START = "<tr style='border: 1px silver solid;'>"; static final String DOC_ROW_END = "</tr>"; static final String CELL_START = "<td>"; static final String CELL_END = "</td>"; static final String TABLE_HEADER_START = "<th>"; static final String TABLE_HEADER_END = "</th>"; static final String HEADING_START = "<b>"; static final String HEADING_END = "</b>"; static final String REMARK_START = ""; //"<i>"; static final String REMARK_END = ""; //"</i>"; static final String KEYWORD_START = "<b>"; static final String KEYWORD_END = "</b>"; static final String BR = "<br/>"; static final String PAD = "&nbsp;"; static final String MIN_CELL_DISTANCE = PAD+PAD+PAD+PAD+PAD+PAD; static final String HORIZONTAL_LINE3 = "<hr width=\"100%\"/>"; static final Color STRING_COLOUR = new Color( 79, 126, 97); static final Color FLOAT_COLOUR = new Color( 70, 95, 185); static final Color INT_COLOUR = new Color( 70, 95, 185); static final Color LABEL_COLOUR = new Color(160, 160, 160); static final Color CLASS_COLOUR = new Color(125, 35, 94); static final Color ENUM_COLOUR = new Color(100, 64, 63); static final Color RULE_COLOUR = new Color(220, 0, 0); static final Color DEFAULT_COLOUR = Color.BLACK; private static final Color[] BRACKET_COLOURS_BY_DEPTH = { new Color(0, 40, 150), new Color(50, 120, 240) }; private static final Color[] CURLY_BRACKET_COLOURS_BY_DEPTH = { new Color(50, 50, 50), new Color(140, 140, 140) }; private static final Color BAD_BRACKET_COLOUR = new Color(200, 0, 0); /** * @param type type of bracket * @param depth nesting depth * @return colour for this combination of type and depth */ public static Color bracketColourByDepthAndType(final EditorTokenType type, final int depth) { if (depth < 0) return BAD_BRACKET_COLOUR; final int index = Math.max(0, depth % CURLY_BRACKET_COLOURS_BY_DEPTH.length); switch (type) { case OPEN_ANGLE: case CLOSE_ANGLE: return RULE_COLOUR; case OPEN_CURLY: case CLOSE_CURLY: return CURLY_BRACKET_COLOURS_BY_DEPTH[index]; case OPEN_ROUND: case CLOSE_ROUND: case OPEN_SQUARE: case CLOSE_SQUARE: return BRACKET_COLOURS_BY_DEPTH[index]; default: System.out.println("Unexpected bracket type received!"); return DEFAULT_COLOUR; } } }
2,922
34.646341
172
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/editor/EditorTokenType.java
package app.display.dialogs.editor; import java.awt.Color; public enum EditorTokenType { STRING (EditorLookAndFeel.STRING_COLOUR, false), // OPEN_ROUND (EditorLookAndFeel.DEFAULT_COLOUR, true), // CLOSE_ROUND (EditorLookAndFeel.DEFAULT_COLOUR, true), // OPEN_SQUARE (EditorLookAndFeel.DEFAULT_COLOUR, true), // CLOSE_SQUARE (EditorLookAndFeel.DEFAULT_COLOUR, true), // OPEN_CURLY (EditorLookAndFeel.DEFAULT_COLOUR, true), // CLOSE_CURLY (EditorLookAndFeel.DEFAULT_COLOUR, true), // OPEN_ANGLE (EditorLookAndFeel.RULE_COLOUR, true), // CLOSE_ANGLE (EditorLookAndFeel.RULE_COLOUR, true), OPEN_ROUND (EditorLookAndFeel.DEFAULT_COLOUR, false), CLOSE_ROUND (EditorLookAndFeel.DEFAULT_COLOUR, false), OPEN_SQUARE (EditorLookAndFeel.DEFAULT_COLOUR, false), CLOSE_SQUARE (EditorLookAndFeel.DEFAULT_COLOUR, false), OPEN_CURLY (EditorLookAndFeel.DEFAULT_COLOUR, false), CLOSE_CURLY (EditorLookAndFeel.DEFAULT_COLOUR, false), OPEN_ANGLE (EditorLookAndFeel.RULE_COLOUR, false), CLOSE_ANGLE (EditorLookAndFeel.RULE_COLOUR, false), FLOAT (EditorLookAndFeel.FLOAT_COLOUR, false), INT (EditorLookAndFeel.INT_COLOUR, false), LABEL (EditorLookAndFeel.LABEL_COLOUR, false), WHITESPACE (EditorLookAndFeel.DEFAULT_COLOUR, false), CLASS (EditorLookAndFeel.CLASS_COLOUR, false), ENUM (EditorLookAndFeel.ENUM_COLOUR, false), RULE (EditorLookAndFeel.RULE_COLOUR, false), OTHER (EditorLookAndFeel.DEFAULT_COLOUR, false); private final Color fgColour; private final boolean isBold; private EditorTokenType (final Color fgColour, final boolean isBold) { this.fgColour = fgColour; this.isBold = isBold; } /** * @return the foreground colour */ public Color fgColour() { return fgColour; } /** * @return true if this should be rendered in bold text */ public boolean isBold() { return isBold; } }
1,810
35.22
71
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/editor/LudiiTokeniser.java
package app.display.dialogs.editor; import java.util.List; import java.util.ArrayList; public class LudiiTokeniser { private static final char OPEN_PARENTHESES = '('; private static final char CLOSE_PARENTHESES = ')'; private static final char OPEN_CURLY = '{'; private static final char CLOSE_CURLY = '}'; private static final char OPEN_SQUARE = '['; private static final char CLOSE_SQUARE = ']'; private static final char OPEN_ANGLE = '<'; private static final char CLOSE_ANGLE = '>'; private static final char STRING_DELIMITER = '"'; private static final char LABEL_DELIMITER = ':'; private final List<String> tokens = new ArrayList<>(); private final StringBuilder token = new StringBuilder(); public LudiiTokeniser (final String gameDescription) { boolean inString = false; boolean inNumber = false; boolean whitespaceLast = false; for (char ch: gameDescription.toCharArray()) { // Deal with any special cases... if (inString) { token.append(ch); if (ch == STRING_DELIMITER) { startNewToken(); inString=false; } continue; } if (inNumber) { if (isNumber(ch)) { token.append(ch); continue; } else { startNewToken(); inNumber=false; // Fall through } } // Keep whitespace separate from normal characters for easy identification of tokens final boolean isWhitespace = Character.isWhitespace(ch); if (whitespaceLast != isWhitespace) startNewToken(); whitespaceLast = isWhitespace; switch (ch) { case OPEN_PARENTHESES: case CLOSE_PARENTHESES: case OPEN_CURLY: case CLOSE_CURLY: case OPEN_SQUARE: case CLOSE_SQUARE: case OPEN_ANGLE: case CLOSE_ANGLE: startNewToken(); addCompleteToken(ch); break; case STRING_DELIMITER: startNewToken(); inString=true; token.append(ch); break; case LABEL_DELIMITER: token.append(ch); startNewToken(); break; default: if (isNumber(ch)) { startNewToken(); inNumber=true; } token.append(ch); break; } } startNewToken(); } private static boolean isNumber(char ch) { final boolean isDigit = (ch=='+'||ch=='-'||ch=='.'||Character.isDigit(ch)); return isDigit; } private boolean addCompleteToken(char ch) { return tokens.add(String.valueOf(ch)); } private void startNewToken() { if (token.length()!=0) { tokens.add(token.toString()); token.setLength(0); } } /** * @return all tokens in this file, as an array */ public String[] getTokens() { return tokens.toArray(new String[0]); } /** * @param token * @param inAngle * @param lastToken * @return true if this starts a new level of indentation */ public static EditorTokenType typeForToken (final String token, final boolean inAngle, final EditorTokenType lastToken) { if (token == null || token.length()==0) return EditorTokenType.OTHER; if (token.length()==1) { switch (token.charAt(0)) { case OPEN_PARENTHESES: return EditorTokenType.OPEN_ROUND; case OPEN_CURLY: return EditorTokenType.OPEN_CURLY; case OPEN_SQUARE: return EditorTokenType.OPEN_SQUARE; case OPEN_ANGLE: return EditorTokenType.OPEN_ANGLE; case CLOSE_PARENTHESES: return EditorTokenType.CLOSE_ROUND; case CLOSE_CURLY: return EditorTokenType.CLOSE_CURLY; case CLOSE_SQUARE: return EditorTokenType.CLOSE_SQUARE; case CLOSE_ANGLE: return EditorTokenType.CLOSE_ANGLE; } } if (token.charAt(0) == STRING_DELIMITER) return EditorTokenType.STRING; if (isFloat(token)) return EditorTokenType.FLOAT; if (isInteger(token)) return EditorTokenType.INT; if (token.endsWith(Character.toString(LABEL_DELIMITER))) return EditorTokenType.LABEL; if (token.trim().isEmpty()) return EditorTokenType.WHITESPACE; if (inAngle) return EditorTokenType.RULE; if (lastToken != null && lastToken==EditorTokenType.OPEN_ROUND && Character.isLowerCase(token.charAt(0))) return EditorTokenType.CLASS; if (Character.isUpperCase(token.charAt(0))) return EditorTokenType.ENUM; return EditorTokenType.OTHER; } /** * @param token * @return true if this should be formatted as an integer */ private static boolean isInteger (final String token) { try { Long.parseLong(token); return true; } catch (Exception e) { return false; } } /** * @param token * @return true if this should be formatted as a floating point number */ public static boolean isFloat (final String token) { if (!token.contains(".")) return false; try { Double.parseDouble(token); return true; } catch (Exception e) { return false; } } }
4,668
23.445026
138
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/editor/SuggestionDialog.java
package app.display.dialogs.editor; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.DefaultListModel; import javax.swing.JDialog; import javax.swing.JEditorPane; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.WindowConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.StyleSheet; import app.PlayerApp; import grammar.Grammar; /** * Create a suggestion list of alternative ludemes. * @author mrraow */ public class SuggestionDialog extends JDialog implements KeyListener, ListSelectionListener, MouseListener, MouseMotionListener { private static final long serialVersionUID = 4115195324471730562L; private static final Font FONT = UIManager.getFont("Label.font"); private static final int VIEW_WIDTH = 600; private static final int VIEW_HEIGHT = 400; final EditorDialog parent; private final boolean isPartial; private final JList<String> list; private final JEditorPane docs; private final List<SuggestionInstance> suggestionInstances = new ArrayList<>(); private PlayerApp app = null; //------------------------------------------------------------------------- /** * @param parent * @param point * @param isPartial */ public SuggestionDialog(final PlayerApp app, final EditorDialog parent, final Point point, final boolean isPartial) { super(parent); setUndecorated(true); this.parent = parent; this.isPartial = isPartial; this.app = app; final JPanel top = new JPanel(); top.setLayout(new BoxLayout(top, BoxLayout.PAGE_AXIS)); getContentPane().add(top); final JPanel fpanel = new JPanel(); fpanel.setLayout(new BoxLayout(fpanel, BoxLayout.LINE_AXIS)); top.add(fpanel); final DefaultListModel<String> listModel = new DefaultListModel<String>(); list = new JList<>(); list.setModel(listModel); list.getSelectionModel().addListSelectionListener(this); list.addMouseListener(this); list.addMouseMotionListener(this); list.setFont(FONT); list.addKeyListener(this); final JScrollPane scroll1 = new JScrollPane(list); scroll1.setPreferredSize(new Dimension(VIEW_WIDTH,VIEW_HEIGHT)); scroll1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); fpanel.add(scroll1); docs = new JEditorPane("text/html", ""); docs.setEditable(false); docs.addKeyListener(this); final StyleSheet styleSheet = ((HTMLDocument)(docs.getDocument())).getStyleSheet(); styleSheet.addRule("body { font-family: " + FONT.getFamily() + "; " + "font-size: " + FONT.getSize() + "pt; }"); styleSheet.addRule("p { font-family: " + FONT.getFamily() + "; " + "font-size: " + FONT.getSize() + "pt; }"); styleSheet.addRule("* { font-family: " + FONT.getFamily() + "; " + "font-size: " + FONT.getSize() + "pt; }"); final JScrollPane scroll2 = new JScrollPane(docs); scroll2.setPreferredSize(new Dimension(VIEW_WIDTH,VIEW_HEIGHT)); scroll2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); fpanel.add(scroll2); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setModalityType(ModalityType.MODELESS); addKeyListener(this); filterAndAdd(point); pack(); } private void filterAndAdd(final Point screenPos) { setVisible(false); filter(); if (isEmpty()) { parent.returnFocus(); return; } else { setLocation(screenPos.x, screenPos.y); setVisible(true); } } void filter() { final DefaultListModel<String> listModel = (DefaultListModel<String>)list.getModel(); listModel.clear(); list.removeAll(); suggestionInstances.clear(); final List<String> allCandidates = Grammar.grammar().classPaths(parent.getText(), parent.getCaretPosition(), isPartial); //System.out.println ("Returned classpaths: " + allCandidates); final List<SuggestionInstance> suggestionsFromClasspaths = EditorHelpDataHelper.suggestionsForClasspaths(parent.editorHelpData, allCandidates, isPartial); final String charsBefore = parent.charsBeforeCursor(); //System.out.println("### charsBefore:" + charsBefore); for (final SuggestionInstance si: suggestionsFromClasspaths) { if (!isPartial || matches(charsBefore, si.substitution)) suggestionInstances.add(si); } //suggestionInstances.addAll(suggestionsFromClasspaths); if (suggestionInstances.isEmpty()) { setVisible(false); parent.returnFocus(); return; } //System.out.println(suggestionInstances.size()+" suggestions found"); suggestionInstances.sort((a,b)->a.label.compareTo(b.label)); for (final SuggestionInstance si: suggestionInstances) listModel.addElement(EditorHelpDataHelper.formatLabel(si.substitution)); list.setSelectedIndex(0); list.invalidate(); } private static boolean matches(final String charsBefore, final String substitution) { final boolean result = substitution.startsWith(charsBefore) || substitution.startsWith("("+charsBefore); //System.out.println("testing: "+charsBefore+" vs "+substitution); return result; } public boolean isEmpty() { return suggestionInstances.isEmpty(); } @Override public void keyTyped(final KeyEvent e) { if (e.isActionKey()) return; System.out.println("Key typed: "+e.toString()); final char keyChar = e.getKeyChar(); if (keyChar == KeyEvent.CHAR_UNDEFINED) return; switch (keyChar) { case KeyEvent.VK_TAB: case KeyEvent.VK_CANCEL: case KeyEvent.VK_CLEAR: case KeyEvent.VK_SHIFT: case KeyEvent.VK_CONTROL: case KeyEvent.VK_ALT: case KeyEvent.VK_PAUSE: case KeyEvent.VK_CAPS_LOCK: case KeyEvent.VK_PAGE_UP: case KeyEvent.VK_PAGE_DOWN: case KeyEvent.VK_END: case KeyEvent.VK_HOME: break; case KeyEvent.VK_ENTER: { final int pos = list.getSelectedIndex(); insertListEntryAndClose(pos); } break; case KeyEvent.VK_ESCAPE: setVisible(false); break; case KeyEvent.VK_BACK_SPACE: if (isPartial) { parent.applyBackspace(app); updateList(); } break; case KeyEvent.VK_DELETE: if (isPartial) { parent.applyDelete(app); updateList(); } break; default: if (isPartial) { parent.insertCharacter(app, e.getKeyChar()); updateList(); } } } private void updateList() { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { filter(); } } ); } @Override public void keyPressed(final KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: { parent.cursorLeft(); updateList(); break; } case KeyEvent.VK_RIGHT: { parent.cursorRight(); updateList(); break; } } } @Override public void keyReleased(final KeyEvent e) { /* Don't care! Required for KeyListener interface */ } @Override public void valueChanged(final ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; final int pos = list.getSelectedIndex(); if (pos >= 0 && pos < suggestionInstances.size()) docs.setText("<html>"+suggestionInstances.get(pos).javadoc+"</html>"); } @Override public void mouseClicked(final MouseEvent evt) { final int pos = list.locationToIndex(evt.getPoint()); insertListEntryAndClose(pos); } private void insertListEntryAndClose(final int listSelection) { if (listSelection >= 0) { parent.replaceTokenScopeWith(app, suggestionInstances.get(listSelection).substitution, isPartial); setVisible(false); } } @Override public void mousePressed(final MouseEvent e) { /* Don't care! Required for MouseListener interface */ } @Override public void mouseReleased(final MouseEvent e) { /* Don't care! Required for MouseListener interface */ } @Override public void mouseEntered(final MouseEvent e) { /* Don't care! Required for MouseListener interface */ } @Override public void mouseExited(final MouseEvent e) { /* Don't care! Required for MouseListener interface */ } @Override public void mouseDragged(final MouseEvent e) { /* Don't care! Required for MouseMotionListener interface */ } @Override public void mouseMoved(final MouseEvent me) { final Point p = new Point(me.getX(),me.getY()); final int index = list.locationToIndex(p); if (index >= 0) list.setSelectedIndex(index); } }
8,881
26.669782
156
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/editor/SuggestionInstance.java
package app.display.dialogs.editor; public class SuggestionInstance { final String classPath; final String label; final String substitution; final String javadoc; /** * @param classPath * @param label * @param substitution * @param javadoc */ public SuggestionInstance (final String classPath, final String label, final String substitution, final String javadoc) { this.classPath = classPath; this.label = label; this.substitution = substitution; this.javadoc = javadoc; } public String getClassPath() { return classPath; } public String getLabel() { return label; } public String getSubstitution() { return substitution; } public String getJavadoc() { return javadoc; } }
722
16.634146
120
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/editor/TextPaneUtils.java
package app.display.dialogs.editor; import java.awt.Point; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.Caret; import javax.swing.text.JTextComponent; import javax.swing.text.Utilities; /** * Utilities for handling text panes * @author mrraow */ public class TextPaneUtils { private static final String HTML_BREAK = "<br/>"; private static final String HTML_END = "</html>"; private static final String HTML_START = "<html>"; /** * @param textArea * @return row number for the current caret position */ public static int getCaretRowNumber (final JTextPane textArea) { final int originalCarotPosition = textArea.getCaret().getDot(); int rn = (originalCarotPosition==0) ? 1 : 0; try { int offs=originalCarotPosition; while(offs>0) { offs=Utilities.getRowStart(textArea, offs)-1; rn++; } } catch (final BadLocationException e) { e.printStackTrace(); } return rn; } /** * @param textArea * @return the start of the current row as a caret position */ public static Point cursorCoords (final JTextPane textArea) { final Caret caret = textArea.getCaret(); final Point point = caret.getMagicCaretPosition(); return point; } /** * @param textArea * @return the start of the current row as a caret position */ public static int startOfCaretCurrentRow (final JTextPane textArea) { try { final int originalCarotPosition = textArea.getCaret().getDot(); return Utilities.getRowStart(textArea, originalCarotPosition); } catch (final BadLocationException e2) { e2.printStackTrace(); return 0; } } /** * @param tc * @param pt * @return partial word before specified point in text area */ public static String getLettersBeforePoint (final JTextComponent tc, final Point pt) { try { final int pos = tc.viewToModel(pt); final int start = Utilities.getWordStart(tc, pos); return tc.getText(start, pos - start); } catch (final BadLocationException e) { System.err.println(e); } return null; } /** * @param tc * @param pt * @return Word at specified point in text area */ public static String getWordAtPoint (final JTextComponent tc, final Point pt) { try { final int pos = tc.viewToModel(pt); final int start = Utilities.getWordStart(tc, pos); final int end = Utilities.getWordEnd(tc, pos); return tc.getText(start, end - start); } catch (final BadLocationException e) { System.err.println(e); } return null; } public static String replaceWordAtPoint (final JTextComponent tc, final Point pt, final String newWord) { try { final int pos = tc.viewToModel(pt); final int start = Utilities.getWordStart(tc, pos); final int end = Utilities.getWordEnd(tc, pos); return (tc.getText(0, start) + newWord + tc.getText(end, tc.getText().length() - end)); } catch (final BadLocationException e) { System.err.println(e); } return null; } /** * @param tc * @param newWord * @return new text after replacement */ public static String replaceWordAtCaret (final JTextComponent tc, final String newWord) { try { final int pos = tc.getCaretPosition(); final int start = Utilities.getWordStart(tc, pos); final int end = Utilities.getWordEnd(tc, pos); return (tc.getText(0, start) + newWord + tc.getText(end, tc.getText().length() - end)); } catch (final BadLocationException e) { System.err.println(e); } return null; } /** * Inserts the text at the caret * @param tc * @param text */ public static void insertAtCaret (final JTextComponent tc, final String text) { tc.replaceSelection(text); } /** * @param s1 * @param s2 * @return first difference between two strings with a little context, for debugging undo/redo */ public static String firstDiff (final String s1, final String s2) { for (int i = 0; i < s1.length() && i < s2.length(); i++) { if (s1.charAt(i) != s2.charAt(i)) { final String sub = i+20 < s1.length() ? s1.substring(i, i+20) : s1.substring(i); return sub.replace("\r", "\\r").replace("\n", "\\n"); } } return ""; } /** * Converts a string with newlines, etc. into something with html markup. * @return HTML version of input string. */ public static String convertToHTML (final String source) { if (source.toLowerCase().startsWith(HTML_START)) return source; return HTML_START+ source.replace("\r\n", HTML_BREAK) .replace("\r", HTML_BREAK) .replace("\n", HTML_BREAK)+ HTML_END; } }
4,663
24.210811
105
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/editor/UndoRecord.java
package app.display.dialogs.editor; import javax.swing.JTextPane; public class UndoRecord { public final String text; public final int caretPos; public final int selectionStart; public final int selectionEnd; public UndoRecord (final JTextPane textArea) { text = textArea.getText(); caretPos = textArea.getCaret().getDot(); selectionStart = textArea.getSelectionStart(); selectionEnd = textArea.getSelectionEnd(); } public void apply (final JTextPane textArea) { textArea.setText(text); textArea.setCaretPosition(caretPos); textArea.setSelectionStart(selectionStart); textArea.setSelectionEnd(selectionEnd); } public boolean ignoreChanges (final JTextPane textArea) { return text.equals(textArea.getText()); } }
751
21.787879
56
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/util/DialogUtil.java
package app.display.dialogs.util; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.font.FontRenderContext; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.AbstractButton; import javax.swing.JDialog; import javax.swing.WindowConstants; import app.DesktopApp; import app.util.SettingsDesktop; public class DialogUtil { /** * Initialise a Dialog. * @param dialog * @param title */ public static void initialiseDialog(final JDialog dialog, final String title, final Rectangle bounds) { sharedInitialisation(dialog, title, bounds); } //------------------------------------------------------------------------- /** * Initialise a Dialog on top of any existing ones, but with forced focus. * @param dialog * @param title */ public static void initialiseForcedDialog(final JDialog dialog, final String title, final Rectangle bounds) { dialog.setModal(true); sharedInitialisation(dialog, title, bounds); } //------------------------------------------------------------------------- /** * Initialise a Dialog and close any existing ones. * @param dialog * @param title */ public static void initialiseSingletonDialog(final JDialog dialog, final String title, final Rectangle bounds) { if (SettingsDesktop.openDialog != null) { SettingsDesktop.openDialog.setVisible(false); SettingsDesktop.openDialog.dispose(); } SettingsDesktop.openDialog = dialog; sharedInitialisation(dialog, title, bounds); } //------------------------------------------------------------------------- /** * Shared initialisation calls between both above cases. * @param dialog * @param title */ private static void sharedInitialisation(final JDialog dialog, final String title, final Rectangle bounds) { // Logo and title try { final URL resource = DesktopApp.frame().getClass().getResource("/ludii-logo-100x100.png"); final BufferedImage image = ImageIO.read(resource); dialog.setIconImage(image); dialog.setTitle(title); } catch (final IOException e) { e.printStackTrace(); } dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); if (bounds == null) dialog.setLocationRelativeTo(DesktopApp.frame()); else { dialog.setLocation(bounds.getLocation()); if (bounds.width > 0 && bounds.height > 0) { dialog.setSize(bounds.width, bounds.height); } } try { dialog.setVisible(true); } catch (final Exception e) { // Sometimes this just fails. Don't really know why but seems harmless. } } //------------------------------------------------------------------------- /** * Code used for nicely formatting and wrapping text (in HTML form) for JButtons. * Code obtained from https://stackoverflow.com/questions/32603544/wrap-dynamic-text-automatically-in-jbutton * @param graphics * @param button * @param str * @return Formatted text string (in HTML) */ public static String getWrappedText(final Graphics graphics, final AbstractButton button, final String str) { final String STR_NEWLINE = "<br />"; final FontRenderContext fontRenderContext = new FontRenderContext(new AffineTransform(), true, true); if( str != null ) { final String text = str.replaceAll("<html><center>", "").replaceAll("</center></html>", ""); final int width = button.getWidth(); final Rectangle2D stringBounds = button.getFont().getStringBounds(text, fontRenderContext); if ( !str.contains(STR_NEWLINE) && (width-5) < (Double.valueOf(stringBounds.getWidth())).intValue()) { String newStr; if( str.contains(" ") ) { final int lastIndex = str.lastIndexOf(" "); newStr = str.substring(0, lastIndex)+STR_NEWLINE+str.substring(lastIndex); } else { final int strLength = ((str.length()/3)*2); newStr = str.substring(0, strLength)+STR_NEWLINE+str.substring(strLength); } return newStr; } } return str; } }
4,253
28.136986
111
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/util/JComboCheckBox.java
package app.display.dialogs.util; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.ComboBoxModel; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; /** * Class for creating a JComboBox with check boxes on the options. * @author Matthew.Stephenson * */ @SuppressWarnings({ "rawtypes" }) public class JComboCheckBox extends JComboBox { private static final long serialVersionUID = 1L; public JComboCheckBox() { init(); } @SuppressWarnings("unchecked") public JComboCheckBox(final JCheckBox[] items) { super(items); init(); } @SuppressWarnings("unchecked") public JComboCheckBox(final Vector items) { super(items); init(); } @SuppressWarnings("unchecked") public JComboCheckBox(final ComboBoxModel aModel) { super(aModel); init(); } @SuppressWarnings("unchecked") private void init() { setRenderer(new ComboBoxRenderer()); addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent ae) { itemSelected(); } }); } void itemSelected() { if (getSelectedItem() instanceof JCheckBox) { final JCheckBox jcb = (JCheckBox)getSelectedItem(); jcb.setSelected(!jcb.isSelected()); } } class ComboBoxRenderer implements ListCellRenderer { private JLabel label; public ComboBoxRenderer() { setOpaque(true); } @Override public Component getListCellRendererComponent(final JList list, final Object value, final int index, final boolean isSelected, final boolean cellHasFocus) { if (value instanceof Component) { final Component c = (Component)value; if (isSelected) { c.setBackground(list.getSelectionBackground()); c.setForeground(list.getSelectionForeground()); } else { c.setBackground(list.getBackground()); c.setForeground(list.getForeground()); } return c; } else { if (label ==null) { label = new JLabel(value.toString()); } else { label.setText(value.toString()); } return label; } } } }
2,575
25.020202
107
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/util/MaxLengthTextDocument.java
package app.display.dialogs.util; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; /** * Document that can contain a maximum number of characters. * @author Matthew.Stephenson */ public class MaxLengthTextDocument extends PlainDocument { private static final long serialVersionUID = 1L; //Store maximum characters permitted private int maxChars; @Override public void insertString(final int offs, final String str, final AttributeSet a) throws BadLocationException { // the length of string that will be created is getLength() + str.length() if(str != null && (getLength() + str.length() < maxChars)) { super.insertString(offs, str, a); } } public void setMaxChars(final int i) { maxChars = i; } public int getMaxChars() { return maxChars; } }
943
22.6
84
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/StartVisualEditor.java
package app.display.dialogs.visual_editor; import app.PlayerApp; import app.display.dialogs.visual_editor.recs.codecompletion.controller.NGramController; import app.display.dialogs.visual_editor.view.VisualEditorFrame; import javax.swing.*; //----------------------------------------------------------------------------- /** * Visual editor view. * @author cambolbro */ public class StartVisualEditor { public static PlayerApp app; @SuppressWarnings("unused") //------------------------------------------------------------------------- public static void main(String[] args) { new StartVisualEditor(null); } public StartVisualEditor(final PlayerApp app) { StartVisualEditor.app = app; try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception ignored) { // Nothing to do } //controller = new NGramController(5); //MainFrame f = new MainFrame(editPanel); VisualEditorFrame f = new VisualEditorFrame(); f.requestFocus(); } private static NGramController controller; public static NGramController controller() { return controller; } }
1,147
19.872727
88
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/LayoutManagement/DFBoxDrawing.java
package app.display.dialogs.visual_editor.LayoutManagement; import app.display.dialogs.visual_editor.model.interfaces.iGNode; import app.display.dialogs.visual_editor.model.interfaces.iGraph; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; import static app.display.dialogs.visual_editor.LayoutManagement.NodePlacementRoutines.translateByRoot; /** * Layout drawing method * @author nic0gin */ public class DFBoxDrawing { private static boolean RECORD_TIME; private final iGraph graph; private int freeY; private double[] odsMetrics; private static final double DEFAULT_DISTANCE = 0.4; private static final double DEFAULT_OFFSET = 0.2; private static final double DEFAULT_SPREAD = 0.1; private double compactness = 0.9; private final int PADDING_X = 10; public static final int MIN_NODE_GAP = 20; private final HashMap<Integer, Integer> gupDistances = new HashMap<>(); /** * Constructor * @param graph graph */ public DFBoxDrawing(iGraph graph, boolean RECORD_TIME) { this.graph = graph; DFBoxDrawing.RECORD_TIME = RECORD_TIME; freeY = 0; odsMetrics = new double[3]; initWeights(); } /** * Initialize layout metrics with default values */ private void initWeights() { odsMetrics[0] = DEFAULT_OFFSET; odsMetrics[1] = DEFAULT_DISTANCE; odsMetrics[2] = DEFAULT_SPREAD; } /** * Main arrangement procedure. Based on the depth-search box layout algorithm by Miyadera et al., 1998. * Miyadera, Y., Anzai, K., Unno, H., and Yaku, T. (1998). Depth-first layout * algorithm for trees. Inf. Process. Lett., 66(4):187–194. * @param nodeId root node of tree/sub-tree to arrange * @param freeX initial x position */ private void initPlacement(int nodeId, int freeX) { if (graph.getNode(nodeId).children() == null || graph.getNode(nodeId).children().size() == 0 || (graph.getNode(nodeId).fixed() && graph.selectedRoot() != nodeId)) { Vector2D piInit = new Vector2D(freeX, freeY); if (graph.getNode(nodeId).fixed()) { freeY += (graph.getNode(nodeId).pos().y() - GraphRoutines.getSubtreeArea(graph, nodeId).y); piInit = new Vector2D(freeX, freeY); freeY += GraphRoutines.nodesMaxSpread() * (odsMetrics[2] * (1.0 - compactness)) + GraphRoutines.getSubtreeArea(graph, nodeId).height + PADDING_X; translateByRoot(graph, nodeId, piInit); } else { freeY += GraphRoutines.nodesMaxSpread() * (odsMetrics[2] * (1.0 - compactness)) + graph.getNode(nodeId).height() + PADDING_X; } // update node position graph.getNode(nodeId).setPos(piInit); } else { List<Integer> nodeCh = new ArrayList<>(graph.getNode(nodeId).children()); graph.getNode(nodeId).children().forEach(v -> { if (graph.getNode(v.intValue()).collapsed()) nodeCh.remove(v); }); if (nodeCh.size() == 0) return; iGNode nFirst = graph.getNode(nodeCh.get(0).intValue()); iGNode nLast = graph.getNode(nodeCh.get(nodeCh.size()-1).intValue()); nodeCh.forEach((s) -> { initPlacement(s.intValue(), (int) (freeX + GraphRoutines.nodesMaxDist() * odsMetrics[1]) + graph.getNode(s.intValue()).width() + PADDING_X); // freeX + getNodeDepth(graph, s)*graph.getNode(s).getWidth()*wX // H-V downward layout: nFirst.getPos().getY() + 0 // intermediate values: between 0.0 and 0.5 // Symmetry: nFirst.getPos().getY() + (nLast.getPos().getY() - nFirst.getPos().getY())/2 // intermediate values between 0.5 and 1.0 // H-V upward layout: nLast.getPos().getY() // Several options to set Y coordinate based positions of children nodes // (nLast.getPos().getY() - nFirst.getPos().getY())/2 // min(C3j, nLast.getPos().getY() - nFirst.getPos().getY()) // uncomment to see fun effect //freeY = Math.max(freeY, (int) (nV.getPos().getY() + nV.getHeight()*wY)); }); iGNode nV = graph.getNode(nodeId); double X0 = nFirst.pos().y(); double X1 = nLast.pos().y(); double wOffset = odsMetrics[0]; double yCoord; yCoord = (X1 - X0) * wOffset * (0.5 * (2.0 - compactness)) + X0; Vector2D piInit = new Vector2D(freeX, yCoord); // update node position nV.setPos(piInit); freeY = Math.max(freeY, (int)(yCoord+nV.height()+PADDING_X)); } } /** * Compaction procedure. Based on the paper by Hasan et al., 2003. * Hasan, M., Rahman, M. S., and Nishizeki, T. (2003). A linear algorithm for * compact box-drawings of trees. Networks, 42(3):160–164. * @param root root node of tree/sub-tree to arrange */ private void compactBox(int root) { // 1. Find all paths ArrayList<List<Integer>> paths = new ArrayList<>(); GraphRoutines.findAllPaths(paths, graph, root, new ArrayList<>()); // 2. Compute upward visibility graph HashMap<Integer, Integer> Gup = findUpwardVisibilityGraph(paths, graph); // 3. Move nodes upward according to G_up and specified metrics moveNodeUpward(paths, Gup, graph); } /** * Finds upward visibility graph * @param paths paths of graph * @param graph1 graph in operation * @return hashmap where keys correspond to node ids and value to their minimum distance from upper node */ private HashMap<Integer, Integer> findUpwardVisibilityGraph(List<List<Integer>> paths, iGraph graph1) { gupDistances.clear(); // Initialize HashMap<Integer, Integer> Gup = new HashMap<>(); List<Integer> LE = new ArrayList<>(paths.get(0)); // iterate each path for (int i = 1; i < paths.size(); i++) { List<Integer> leCandidates = new ArrayList<>(); List<Integer> P = new ArrayList<>(paths.get(i)); // cursor on Lower Envelop int j = LE.size()-1; // cursor on current path int k = P.size()-1; // iterating through LE and current path to add edges into Gup while (j != 0 && k != 0) { int currentPk = P.get(k).intValue(); iGNode upper = graph1.getNode(LE.get(j).intValue()); iGNode lower = graph1.getNode(P.get(k).intValue()); if (upper.equals(lower)) break; int upperWidth = upper.fixed() ? GraphRoutines.getSubtreeArea(graph1, upper.id()).width : upper.width(); int lowerWidth = lower.fixed() ? GraphRoutines.getSubtreeArea(graph1, lower.id()).width : lower.width(); // int nodeDist = (int)(lower.pos().y() - upper.pos().y() - upperHeight); // check all the cases for upper and lower nodes x coordinates intersecting // add edges for upward visibility graph // construct next LE // CASE#1: left corner coordinates match if ((int)(upper.pos().x()) == (int)(lower.pos().x())) { // check if right corner of upper exceeds right corner of lower to add to LE candidates if ((int)(upper.pos().x()+ upperWidth) > (int)(lower.pos().x()+lowerWidth)) { leCandidates.add(0, Integer.valueOf(upper.id())); } addMinDistToGup(Gup, upper, lower); j--; k--; } else if ((int)(upper.pos().x()) > (int)(lower.pos().x())) { // check if right corner of upper exceeds right corner of lower to add to LE candidates if ((int)(upper.pos().x()+ upperWidth) > (int)(lower.pos().x()+lowerWidth)) { leCandidates.add(0, Integer.valueOf(upper.id())); } // CASE#2: left corner of upper is within lower if ((int)(upper.pos().x()) <= (int)(lower.pos().x()+lowerWidth)) { addMinDistToGup(Gup, upper, lower); } j--; } else if ((int)(upper.pos().x()) < (int)(lower.pos().x())) { // CASE#2: right corner of upper is within lower if ((int)(upper.pos().x()+ upperWidth) > (int)(lower.pos().x())) { addMinDistToGup(Gup, upper, lower); } k--; } leCandidates.add(0, Integer.valueOf(currentPk)); } LE = new ArrayList<>(leCandidates); LE.addAll(0, paths.get(i).stream().limit(k+1).collect(Collectors.toList())); } return Gup; } /** * Helper method to add new min distance to upward visibility graph * @param gup upward visibility graph - hashmap where key is node id and value is minimum distance to upper node * @param upper upper node * @param lower lower node */ private void addMinDistToGup(HashMap<Integer, Integer> gup, iGNode upper, iGNode lower) { int newDist = GraphRoutines.computeNodeVerticalDistance(upper.id(), lower.id(), graph); if (gup.containsKey(Integer.valueOf(lower.id()))) { if (newDist < gupDistances.get(Integer.valueOf(lower.id())).intValue()) { gup.put(Integer.valueOf(lower.id()), Integer.valueOf(upper.id())); gupDistances.put(Integer.valueOf(lower.id()), Integer.valueOf(newDist)); } } else { gup.put(Integer.valueOf(lower.id()), Integer.valueOf(upper.id())); gupDistances.put(Integer.valueOf(lower.id()), Integer.valueOf(newDist)); } } /** * Move nodes upward according to upward visibility graph * @param paths paths of tree/subtree * @param gup upward visibility graph - hashmap where key is node id and value is minimum distance to upper node * @param graph1 graph in operation */ private void moveNodeUpward(List<List<Integer>> paths, HashMap<Integer, Integer> gup, iGraph graph1) { List<Integer> subTree = new ArrayList<>(); List<Integer> P; // keep track of T_i-1 nodes for (int i = 1; i < paths.size(); i++) { P = new ArrayList<>(paths.get(i)); int minDist = Integer.MAX_VALUE; for (int j = 1; j < P.size(); j++) { int nid = P.get(j).intValue(); if (!subTree.contains(P.get(j)) && gup.containsKey(Integer.valueOf(nid))) { minDist = Math.min(minDist, GraphRoutines.computeNodeVerticalDistance(gup.get(Integer.valueOf(nid)).intValue(), nid, graph1)); } } for (int j = 1; j < P.size(); j++) { iGNode n = graph1.getNode(P.get(j).intValue()); int dist = Math.abs(minDist - MIN_NODE_GAP); if (!subTree.contains(P.get(j))) { n.setPos(new Vector2D(n.pos().x(), n.pos().y() - Math.max(dist, 0)*compactness)); subTree.add(P.get(j)); } } } } /** * Update layout metrics. Values should be between 0.0 and 1.0 * @param offset relative offset of subtrees with respect to their root * @param distance relative distance between subtrees and their root * @param spread inner distance between nodes in a subtree */ public void updateWeights(Double offset, Double distance, Double spread) { odsMetrics[0] = offset.doubleValue(); odsMetrics[1] = distance.doubleValue(); odsMetrics[2] = spread.doubleValue(); } /** * Update layout metrics * @param weights array of O,D,S metrics */ public void updateWeights(double[] weights) { odsMetrics = weights.clone(); } /** * Update layout metric for graph compactness. * @param compactness value if between 0.0 and 1.0 */ public void setCompactness(double compactness) { this.compactness = compactness; } /** * Application of layout arrangement procedures. * @param root root node of tree/sub-tree to arrange */ public void applyLayout(int root) { freeY = 0; Vector2D oPos = graph.getNode(root).pos(); long startTime = System.nanoTime(); initPlacement(root,0); long endTime = System.nanoTime(); if (RECORD_TIME) System.out.println("Init placement: " + (endTime - startTime)/1E6); startTime = System.nanoTime(); compactBox(root); endTime = System.nanoTime(); if (RECORD_TIME) System.out.println("Compact box: " + (endTime - startTime)/1E6); startTime = System.nanoTime(); translateByRoot(graph, root, oPos); endTime = System.nanoTime(); if (RECORD_TIME) System.out.println("Translate by root: " + (endTime - startTime)/1E6); } /** * Default offset metric */ public static double defaultO() { return DEFAULT_OFFSET; } /** * Default distance metric */ public static double defaultD() { return DEFAULT_DISTANCE; } /** * Default spread metric */ public static double defaultS() { return DEFAULT_SPREAD; } }
14,020
37.308743
161
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/LayoutManagement/GraphAnimator.java
package app.display.dialogs.visual_editor.LayoutManagement; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.interfaces.iGNode; import app.display.dialogs.visual_editor.model.interfaces.iGraph; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Provides functionality for smooth animation between changes of graph layouts * @author nic0gin */ public class GraphAnimator { /** * Animation updates */ private final int ANIMATION_UPDATES = 25; /** * Animation update counter */ private int updateCounter = 0; private static GraphAnimator graphAnimator; private final HashMap<iGNode, Vector2D> nodeInitPositions; private final HashMap<iGNode, Vector2D> nodeFinalPosition; private final HashMap<iGNode, Vector2D> nodePosIncrements; private final List<iGNode> nodesToProcess; /** * Constructor */ private GraphAnimator() { nodeInitPositions = new HashMap<>(); nodeFinalPosition = new HashMap<>(); nodePosIncrements = new HashMap<>(); nodesToProcess = new ArrayList<>(); } /** * Returns single instance of GraphAnimator */ public static GraphAnimator getGraphAnimator() { if (graphAnimator == null) graphAnimator = new GraphAnimator(); return graphAnimator; } /** * Animates smooth transition between previous nodes positions and new positions * @return return true if finished animation */ public boolean animateGraphNodes() { if (updateCounter == 0) { updateToInitPositions(); } nodePosIncrements.forEach((k,v) -> k.setPos(new Vector2D(nodeInitPositions.get(k).x()+v.x()*updateCounter, nodeInitPositions.get(k).y()+v.y()*updateCounter))); updateCounter++; Handler.currentGraphPanel.syncNodePositions(); if (updateCounter == ANIMATION_UPDATES) { updateCounter = 0; return true; } return false; } public void clearPositionHistory() { nodeInitPositions.clear(); nodeFinalPosition.clear(); nodePosIncrements.clear(); } /** * Sets nodes to their previous positions and calculates increments for further animation */ public void updateToInitPositions() { nodeFinalPosition.forEach((k,v) -> { // compute node increments double incX = (v.x() - nodeInitPositions.get(k).x()) / (ANIMATION_UPDATES-1); double incY = (v.y() - nodeInitPositions.get(k).y()) / (ANIMATION_UPDATES-1); nodePosIncrements.put(k, new Vector2D(incX, incY)); // set node positions to initial k.setPos(nodeInitPositions.get(k)); }); Handler.currentGraphPanel.syncNodePositions(); } /** * Sets nodes to their new position */ public void updateToFinalPositions() { nodeFinalPosition.forEach(iGNode::setPos); Handler.currentGraphPanel.syncNodePositions(); } /** * Preserves initial/previous positions of nodes of a subtree that starts with provided root */ public void preserveInitPositions(iGraph graph, int root) { List<Integer> Q = new ArrayList<>(); Q.add(Integer.valueOf(root)); while (!Q.isEmpty()) { int nId = Q.remove(0).intValue(); iGNode n = graph.getNode(nId); nodesToProcess.add(n); nodeInitPositions.put(n, n.pos()); Q.addAll(n.children()); } } /** * Preserves initial/previous positions of a given list of nodes */ public void preserveInitPositions(List<iGNode> nodes) { nodes.forEach(n -> { nodesToProcess.add(n); nodeInitPositions.put(n, n.pos()); }); } /** * Preserving final positions of nodes whose initial positions were already preserved */ public void preserveFinalPositions() { nodesToProcess.forEach(n -> nodeFinalPosition.put(n, n.pos())); nodesToProcess.clear(); } public HashMap<iGNode, Vector2D> nodeFinalPosition() { return nodeFinalPosition; } public HashMap<iGNode, Vector2D> nodeInitPositions() { return nodeInitPositions; } public int updateCounter() { return updateCounter; } }
4,490
26.054217
114
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/LayoutManagement/GraphRoutines.java
package app.display.dialogs.visual_editor.LayoutManagement; import app.display.dialogs.visual_editor.model.interfaces.iGNode; import app.display.dialogs.visual_editor.model.interfaces.iGraph; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import static java.lang.Math.abs; /** * Graph manipulation procedures * @author nic0gin */ public final class GraphRoutines { /** * Tuning constants for metric evaluation */ private static final double NODES_MAX_DIST = 300; private static final double NODES_MAX_SPREAD = 400; private static final double[] ODS_TUNING = new double[] {1.0, 1.0, 1.0}; /** * Update of depth for graph nodes by BFS traversal * @param graph graph in operation * @param r root id */ public static void updateNodeDepth(iGraph graph, int r) { List<Integer> layer = new ArrayList<>(); List<Integer> nextLayer = new ArrayList<>(); int d = 1; layer.add(Integer.valueOf(r)); while (!layer.isEmpty()) { int finalD = d; nextLayer.clear(); layer.forEach((v) -> { graph.getNode(v.intValue()).setDepth(finalD); nextLayer.addAll(graph.getNode(v.intValue()).children()); }); layer = new ArrayList<>(nextLayer); d++; } } /** * Get depth of a node from the graph * @param graph graph in operation * @param v index of a node * @return depth of a node */ public static int getNodeDepth(iGraph graph, int v) { return graph.getNode(v).depth(); } /** * Get number of siblings of a node * @param graph graph in operation * @param v index of a node * @return number of siblings */ public static int getNumSiblings(iGraph graph, int v) { return graph.getNode(graph.getNode(v).parent()).children().size(); } /** * Evaluate subtree configurations of * @param graph graph * @param root starting from a root * @return layout metrics */ public static double[] computeLayoutMetrics(iGraph graph, int root) { double[] odsWeights = new double[3]; HashMap<Integer, List<Double>> layerOffset = new HashMap<>(); HashMap<Integer, List<Double>> layerDist = new HashMap<>(); HashMap<Integer, List<Double>> layerSpread = new HashMap<>(); List<Integer> Q = new ArrayList<>(); Q.add(Integer.valueOf(root)); while (!Q.isEmpty()) { int n = Q.remove(0).intValue(); iGNode node = graph.getNode(n); // if node is a parent: find its configurations if (!node.children().isEmpty()) { List<Integer> children = graph.getNode(n).children(); int depth = graph.getNode(children.get(0).intValue()).depth(); // compute D double xDiffMean = 0.0; for (Integer child: children) { xDiffMean += Math.abs(computeNodeHorizontalDistance(n, child.intValue(), graph)); } xDiffMean /= children.size(); double D = (Math.max(0, Math.min(xDiffMean, NODES_MAX_DIST))) / (NODES_MAX_DIST); // compute O double O; if (children.size() == 1) { O = DFBoxDrawing.defaultO(); } else { iGNode f = graph.getNode(children.get(0).intValue()); iGNode l = graph.getNode(children.get(children.size()-1).intValue()); O = ((node.pos().y()+node.height()/2.0) - f.pos().y()) / Math.abs(l.pos().y()+l.height() - f.pos().y()); O = Math.max(0.0, Math.min(1.0, O)); } // compute S double Smean = 0; double S; if (children.size() == 1) { S = DFBoxDrawing.defaultS(); } else { // order children by Y coordinate children.sort((o1, o2) -> (int) (graph.getNode(o1.intValue()).pos().y() - graph.getNode(o2.intValue()).pos().y())); for (int i = 0; i < children.size()-1; i++) Smean += abs(computeNodeVerticalDistance(children.get(i).intValue(), children.get(i+1).intValue(), graph)); Smean /= children.size()-1; S = Math.max(0, Math.min(Smean, NODES_MAX_SPREAD)) / (NODES_MAX_SPREAD); } addWeight(depth, D, layerDist); addWeight(depth, O, layerOffset); addWeight(depth, S, layerSpread); // Add children to the Q Q.addAll(children); } } if (graph.getNode(root).children().isEmpty()) { odsWeights[0] = DFBoxDrawing.defaultO(); odsWeights[1] = DFBoxDrawing.defaultD(); odsWeights[2] = DFBoxDrawing.defaultS(); } else { odsWeights[0] = getAvgWeight(layerOffset) * ODS_TUNING[0]; odsWeights[1] = getAvgWeight(layerDist) * ODS_TUNING[1]; odsWeights[2] = getAvgWeight(layerSpread) * ODS_TUNING[2]; } return odsWeights; } private static void addWeight(int d, double w, HashMap<Integer, List<Double>> weightMap) { if (!weightMap.containsKey(Integer.valueOf(d))) weightMap.put(Integer.valueOf(d), new ArrayList<>()); weightMap.get(Integer.valueOf(d)).add(Double.valueOf(w)); } private static double getAvgWeight(HashMap<Integer, List<Double>> weightMap) { List<Integer> keys = new ArrayList<>(weightMap.keySet()); double layerWeight = 1.0; double avg = 0.0; for (int i = 0; i < keys.size(); i++) { if(keys.size() - i > 1) layerWeight /= 2.0; double layerAvg = 0.0; int k = keys.get(i).intValue(); List<Double> list = weightMap.get(Integer.valueOf(k)); for (Double aDouble : list) layerAvg += aDouble.doubleValue(); layerAvg /= list.size(); avg += layerAvg*layerWeight; } return avg; } /** * A method for finding all paths in a tree graph starting from specified node * @param paths list of paths to be filled in * @param graph graph in operation * @param root starting node * @param pprime helper parameter for recursion; provide empty list at the beginning */ public static void findAllPaths(ArrayList<List<Integer>> paths, iGraph graph, int root, List<Integer> pprime) { // current node iGNode node = graph.getNode(root); List<Integer> p = new ArrayList<>(pprime); p.add(Integer.valueOf(root)); node.children().forEach(cid -> { iGNode c = graph.getNode(cid.intValue()); List<Integer> pTemp = new ArrayList<>(p); pTemp.add(cid); if (c.children().isEmpty() || c.fixed()) { paths.add(pTemp); } else { findAllPaths(paths, graph, cid.intValue(), p); } }); } /** * Method to compute the rectangular area around subtree of specified root * @param graph graph in operation * @param root starting root * @return Rectangle object */ public static Rectangle getSubtreeArea(iGraph graph, int root) { int ltX = (int) graph.getNode(root).pos().x(); int ltY = (int) graph.getNode(root).pos().y(); int rbX = (int) graph.getNode(root).pos().x(); int rbY = (int) graph.getNode(root).pos().y(); List<Integer> Q = new ArrayList<>(); Q.add(Integer.valueOf(root)); while (!Q.isEmpty()) { int nId = Q.remove(0).intValue(); iGNode node = graph.getNode(nId); if (node.pos().x() < ltX) ltX = (int) node.pos().x(); if (node.pos().x() + node.width() > rbX) rbX = (int) node.pos().x() + node.width(); if (node.pos().y() < ltY) ltY = (int) node.pos().y(); if (node.pos().y() + node.height() > rbY) rbY = (int) node.pos().y() + node.height(); Q.addAll(node.children()); } return new Rectangle(ltX, ltY, rbX-ltX, rbY-ltY); } /** * Compute vertical distance between two nodes * @param upper id of upper node * @param lower id of lower node * @param graph graph in operation * @return distance */ public static int computeNodeVerticalDistance(int upper, int lower, iGraph graph) { iGNode u = graph.getNode(upper); iGNode l = graph.getNode(lower); int upperHeight = u.fixed() ? GraphRoutines.getSubtreeArea(graph, u.id()).height : u.height(); return (int) (l.pos().y() - u.pos().y() - upperHeight); } /** * Compute horizontal distance between two nodes * @param left id of left node * @param right id of right node * @param graph graph in operation * @return distance */ public static int computeNodeHorizontalDistance(int left, int right, iGraph graph) { iGNode l = graph.getNode(left); iGNode r = graph.getNode(right); return (int) (r.pos().x()-(l.pos().x()+l.width())); } /** * Tuning constants for layout metrics * @return array of tuning constants in order o,d,s */ public static double[] odsTuning() {return ODS_TUNING;} public static double nodesMaxDist() { return NODES_MAX_DIST; } public static double nodesMaxSpread() { return NODES_MAX_SPREAD; } }
9,963
33.006826
135
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/LayoutManagement/LayoutHandler.java
package app.display.dialogs.visual_editor.LayoutManagement; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.interfaces.iGNode; import app.display.dialogs.visual_editor.model.interfaces.iGraph; import app.display.dialogs.visual_editor.view.panels.editor.tabPanels.LayoutSettingsPanel; import app.display.dialogs.visual_editor.view.panels.menus.TreeLayoutMenu; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import static app.display.dialogs.visual_editor.LayoutManagement.GraphRoutines.updateNodeDepth; /** * @author nic0gin */ public class LayoutHandler { private static final boolean RECORD_TIME = false; private final iGraph graph; private final DFBoxDrawing layout; private final EvaluateAndArrange evaluateAndArrange = new EvaluateAndArrange(); /** * Constructor * @param graph graph layout of which should be handled */ public LayoutHandler(iGraph graph) { this.graph = graph; layout = new DFBoxDrawing(graph, RECORD_TIME); } /** * Update compactness value of layout * @param sliderValue value between 0.0 and 1.0 */ public void updateCompactness(double sliderValue) { layout.setCompactness(sliderValue); } /** * Explicitly update layout metrics */ public void updateDFSWeights(double offset, double distance, double spread) { layout.updateWeights(Double.valueOf(offset), Double.valueOf(distance), Double.valueOf(spread)); } /** * Implicitly update layout metrics i.e. evaluate user's placement */ public void evaluateGraphWeights() { long startTime = System.nanoTime(); double[] weights = GraphRoutines.computeLayoutMetrics(graph, graph.getRoot().id()); long endTime = System.nanoTime(); if (RECORD_TIME) System.out.println("Metric computation: "+ (endTime - startTime)/1E6); layout.updateWeights(weights); LayoutSettingsPanel.getLayoutSettingsPanel().updateSliderValues(weights[0], weights[1], weights[2]); } /** * Executes layout management procedures of a graph */ public void executeLayout() { if (RECORD_TIME) System.out.println("Nodes: " + graph.getNodeList().size()); GraphAnimator.getGraphAnimator().clearPositionHistory(); if (Handler.evaluateLayoutMetrics) evaluateGraphWeights(); long startTime = System.nanoTime(); arrangeTreeComponents(); long endTime = System.nanoTime(); if (RECORD_TIME) System.out.println("Total drawing time: "+ (endTime - startTime)/1E6); TreeLayoutMenu.redoP.setEnabled(false); TreeLayoutMenu.undoP.setEnabled(true); Handler.currentGraphPanel.deselectEverything(); } /** * Arranges layout of all components of a graph */ public void arrangeTreeComponents() { if (GraphAnimator.getGraphAnimator().updateCounter() != 0) return; // determine graph components to be updated List<Integer> roots; if (graph.selectedRoot() == -1) { roots = new ArrayList<>(graph.connectedComponentRoots()); // move root node at the top of the list roots.remove(Integer.valueOf(graph.getRoot().id())); roots.add(0, Integer.valueOf(graph.getRoot().id())); } else { roots = new ArrayList<>(); roots.add(Integer.valueOf(graph.selectedRoot())); } // update graph components Vector2D transPos = null; for (int i = 0; i < roots.size(); i++) { int root = roots.get(i).intValue(); // translation position if (i > 0) { Rectangle rect = GraphRoutines.getSubtreeArea(graph, roots.get(i-1).intValue()); transPos = new Vector2D( Handler.gameGraphPanel.parentScrollPane().getViewport().getViewRect().x+NodePlacementRoutines.DEFAULT_X_POS, rect.y+rect.height+NodePlacementRoutines.DEFAULT_Y_POS); } // check if has children if (!graph.getNode(root).children().isEmpty()) { // preserve initial positions of subtree if (Handler.animation) GraphAnimator.getGraphAnimator().preserveInitPositions(graph, root); // update depth of subtree updateNodeDepth(graph, root); // rearrange subtree layout with standard procedure layout.applyLayout(root); if (i > 0) NodePlacementRoutines.translateByRoot(graph, root, transPos); // preserve final position if (Handler.animation) GraphAnimator.getGraphAnimator().preserveFinalPositions(); } else { iGNode rNode = graph.getNode(root); // preserve initial position of single node if (Handler.animation) GraphAnimator.getGraphAnimator().nodeInitPositions().put(rNode, rNode.pos()); if (i > 0) NodePlacementRoutines.translateByRoot(graph, root, transPos); // preserve final position of single node if (Handler.animation) GraphAnimator.getGraphAnimator().nodeFinalPosition().put(rNode, rNode.pos()); } } // display updated positions either through animation or single jump if (Handler.animation) { // animate change Timer animationTimer = new Timer(3, e -> { if (GraphAnimator.getGraphAnimator().animateGraphNodes()) { ((Timer)e.getSource()).stop(); } }); animationTimer.start(); } else { Handler.currentGraphPanel.syncNodePositions(); } } /** * An action listener for evaluation of user metrics and further execution of arrangement procedure */ private class EvaluateAndArrange implements ActionListener { public EvaluateAndArrange() { } @Override public void actionPerformed(ActionEvent e) { executeLayout(); } } public EvaluateAndArrange getEvaluateAndArrange() {return evaluateAndArrange;} }
6,479
32.926702
132
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/LayoutManagement/NodePlacementRoutines.java
package app.display.dialogs.visual_editor.LayoutManagement; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.interfaces.iGNode; import app.display.dialogs.visual_editor.model.interfaces.iGraph; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import javax.swing.*; import java.util.ArrayList; import java.util.List; /** * Provide methods for node placement * @author nic0gin */ public final class NodePlacementRoutines { public static final int X_AXIS = 0; public static final int Y_AXIS = 1; private static final int NODE_GAP = 25; public static final int DEFAULT_X_POS = 20; public static final int DEFAULT_Y_POS = 20; /** * Translate node placement by oPos vector with respect to root * @param r root node id * @param oPos original root position * @param graph graph in operation */ public static void translateByRoot(iGraph graph, int r, Vector2D oPos) { Vector2D t = graph.getNode(r).pos().sub(oPos); // iterate through descendants of a root node List<Integer> Q = new ArrayList<>(); Q.add(Integer.valueOf(r)); while (!Q.isEmpty()) { int nid = Q.remove(0).intValue(); iGNode n = graph.getNode(nid); if (!n.collapsed()) { n.setPos(n.pos().sub(t)); Q.addAll(n.children()); } } } public static void alignNodes(List<iGNode> nodes, int axis, IGraphPanel graphPanel) { if (nodes.isEmpty() || ( Handler.animation && GraphAnimator.getGraphAnimator().updateCounter() != 0)) return; // preserve initial node positions if (Handler.animation) GraphAnimator.getGraphAnimator().preserveInitPositions(nodes); // find min posX and posY in a list double posX = nodes.get(0).pos().x(); double posY = nodes.get(0).pos().y(); for (iGNode n: nodes) { if (n.pos().x() < posX) posX = n.pos().x(); if (n.pos().y() < posY) posY = n.pos().y(); } if (axis == X_AXIS) { for (int i = 1; i < nodes.size(); i++) { nodes.get(i).setPos(new Vector2D(nodes.get(i-1).pos().x()+nodes.get(i-1).width()+NODE_GAP, posY)); } } else if (axis == Y_AXIS) { for (int i = 1; i < nodes.size(); i++) { nodes.get(i).setPos(new Vector2D(posX, nodes.get(i-1).pos().y()+nodes.get(i-1).height()+NODE_GAP)); } } // preserve final if (Handler.animation) GraphAnimator.getGraphAnimator().preserveFinalPositions(); if (Handler.animation && GraphAnimator.getGraphAnimator().updateCounter() == 0) { Timer animationTimer = new Timer(3, e -> { if (GraphAnimator.getGraphAnimator().animateGraphNodes()) { ((Timer)e.getSource()).stop(); } }); animationTimer.start(); } else { graphPanel.syncNodePositions(); } } }
3,214
29.913462
115
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/LayoutManagement/Vector2D.java
package app.display.dialogs.visual_editor.LayoutManagement; /** * 2-dimensional real-valued vector with basic operations * @author nic0gin */ public class Vector2D { private double x,y; public Vector2D(double x, double y) { this.x = x; this.y = y; } public Vector2D normalize() { return div(euclideanNorm()); } public Vector2D mult(double c) { return new Vector2D(x*c, y*c); } public Vector2D mult(Vector2D u) { return new Vector2D(x*u.x, y*u.y); } public Vector2D div(double c) { return new Vector2D(x/c, y/c); } public Vector2D add(double c) { return new Vector2D(x+c, y+c); } public Vector2D sub(double c) { return new Vector2D(x-c, y-c); } public Vector2D add(Vector2D u) { return new Vector2D(x+u.x, y+u.y); } public Vector2D sub(Vector2D u) { return new Vector2D(x-u.x, y-u.y); } public double euclideanNorm() { return Math.sqrt(x*x + y*y); } public double x() { return x; } public double y() { return y; } public Vector2D copy() { return new Vector2D(this.x, this.y); } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } }
1,357
16.410256
59
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/documentation/DocumentationReader.java
package app.display.dialogs.visual_editor.documentation; import grammar.Grammar; import main.grammar.Clause; import main.grammar.ClauseArg; import main.grammar.Symbol; import main.grammar.ebnf.EBNFClause; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; /** * Reads EditorHelp.txt and stores help information for each symbol * @author Filipp Dokienko */ public class DocumentationReader { private static DocumentationReader instance = null; private static String helpFilePath = "/help/EditorHelp.txt"; private static InputStream helpFile = openHelpFile(); private static final HashMap<Symbol, HelpInformation> documentation = new HashMap<>(); private static final Grammar grammar = Grammar.grammar(); private static InputStream openHelpFile() { return DocumentationReader.class.getResourceAsStream(helpFilePath); } private static final HashMap<Clause, EBNFClause> clauseMap = new HashMap<>(); public static void main(String[] args) { try { //helpFilePath = DocumentationReader.class.getResource("/help/EditorHelp.txt").toURI().getPath(); readDoc(); } catch (Exception e) { throw new RuntimeException(e); } } public static void readDoc() throws IOException { // read helpFile by line //BufferedReader reader = new BufferedReader(new FileReader(new File(helpFilePath))); BufferedReader reader = new BufferedReader(new InputStreamReader(helpFile)); HelpInformation currentHelpInfo = null; Clause currentClause = null; String line; while ((line = reader.readLine()) != null) { if(line.startsWith("TYPE:")) { String symbolString = line.substring(6); Symbol symbol = findSymbol(symbolString); currentClause = null; currentHelpInfo = new HelpInformation(symbol); documentation.put(symbol, currentHelpInfo); } else if(line.startsWith("TYPE JAVADOC:")) { String descriptionString = line.substring(14); currentHelpInfo.setDescription(descriptionString); } else if(line.startsWith("NEW CTOR")) { // read next line line = reader.readLine(); currentClause = findClause(currentHelpInfo.symbol(), line); currentHelpInfo.addCtor(currentClause, line); } else if(line.startsWith("PARAM JAVADOC:")) { String fullLine = line.substring(15); String parameterStringName = fullLine.substring(0, fullLine.lastIndexOf(":")); String[] split = parameterStringName.split(" "); if(split.length > 1) parameterStringName = split[0].substring(0, split[0].length()-1); ClauseArg arg = findClauseArg(currentClause, parameterStringName); String parameterString = fullLine.substring(parameterStringName.length()+2); currentHelpInfo.addParameter(arg, parameterString); } else if(line.startsWith("EXAMPLE:")) { String exampleString = line.substring(10); currentHelpInfo.addExample(currentClause, exampleString); } else if(line.startsWith("REMARKS:")) { String remarkString = line.substring(9); currentHelpInfo.setRemark(remarkString); } } } private static Symbol findSymbol(String name) { for(Symbol symbol : grammar.symbols()) if(symbol.path().equals(name)) return symbol; return null; } private static Clause findClause(Symbol s, String string) { EBNFClause ec = null; try { ec = new EBNFClause(string.replaceAll("\\s+", " ")); } catch(Exception ignored) { // Nothing to do } String string2 = string; for(Clause clause : s.rule().rhs()) { if(clause.args() == null) continue; String clauseString = clause.toString(); for(ClauseArg arg : clause.args()) { string2 = string2.replace("<"+arg.symbol().token()+">", "<"+arg.symbol().grammarLabel()+">"); } clauseString = clauseString.replaceAll("<int>", "int"); clauseString = clauseString.replaceAll("<ints>", "ints"); string2 = string2.replaceAll("<int>", "int"); string2 = string2.replaceAll("<ints>", "ints"); string2 = string2.replaceAll("\\s+", " "); if(clauseString.equalsIgnoreCase(string2)) { clauseMap.put(clause, ec); return clause; } if(clauseToString(clause).equalsIgnoreCase(string2)) { clauseMap.put(clause, ec); return clause; } } for(Clause clause : s.rule().rhs()) { string2 = string2.replaceAll("<region>","<sites>"); string2 = string2.replaceAll("<rangefunction>","<range>"); string2 = string2.replaceAll("<intarrayfunction>","ints"); string2 = string2.replaceAll("<dimfunction>","<dim>"); if(clauseToString(clause).equalsIgnoreCase(string2)) { clauseMap.put(clause, ec); return clause; } } System.out.println("Could not find clause: "+string); return null; } private static String clauseToString(Clause c) { int currentGroup = 0; int lastGroup = 0; StringBuilder st = new StringBuilder(); st.append("(").append(c.symbol().token()).append(" "); if(c.args() != null) for(ClauseArg cArg : c.args()) { if(cArg.orGroup() > 0) { if(currentGroup != cArg.orGroup()) { if(currentGroup > 0) st.append(") "); st.append("("); currentGroup = cArg.orGroup(); } else st.append("|"); } if(cArg.orGroup() == 0 && currentGroup > 0) { st.append(")"); currentGroup = 0; } st.append(" ").append(cArg).append(" "); lastGroup = cArg.orGroup(); } if(lastGroup > 0) st.append(")"); st.append(")"); st = new StringBuilder(st.toString().replaceAll("\\s+", " ")); st = new StringBuilder(st.toString().replaceAll("\\( ", "(")); st = new StringBuilder(st.toString().replaceAll(" \\)", ")")); st = new StringBuilder(st.toString().replaceAll("<int>", "int")); st = new StringBuilder(st.toString().replaceAll("<ints>", "ints")); return st.toString(); } private static ClauseArg findClauseArg(Clause c, String string) { if(c==null) return null; List<String> strings = new ArrayList<>(); String string2 = string; List<ClauseArg> cas = c.args(); for(ClauseArg ca : cas) { String caString = ca.toString(); string2 = string2.replace( "<"+ca.symbol().token()+">", "<"+ca.symbol().grammarLabel()+">"); caString = caString.replaceAll("<int>", "int"); caString = caString.replaceAll("<ints>", "ints"); string2 = string2.replaceAll("<int>","int"); string2 = string2.replaceAll("<ints>","ints"); string2 = string2.toLowerCase(); caString = caString.toLowerCase(); strings.add(caString); if(caString.equals(string2)) return ca; } EBNFClause ec = clauseMap.get(c); String[] split = ec.toString().substring(1, ec.toString().length()-1).split(" "); if(ec.toString().contains("|")) { List<String> splitlist = new LinkedList<>(Arrays.asList(split)); while(splitlist.contains("|")) { int indexOfBar = splitlist.indexOf("|"); // element before char type = splitlist.get(indexOfBar-1).charAt(0); int fromIndex = indexOfBar-1; int untilIndex = indexOfBar; while(untilIndex+2 < splitlist.size() && splitlist.get(untilIndex+2).equals("|")) untilIndex+=2; untilIndex+=1; splitlist.set(fromIndex, splitlist.get(fromIndex).substring(1)); splitlist.set(untilIndex, splitlist.get(untilIndex).substring(0, splitlist.get(untilIndex).length()-1)); char closeType = ' '; if(type == '[') closeType = ']'; else if(type == '{') closeType = '}'; if(type == '[' || type == '{') { for(int i = fromIndex; i<=untilIndex; i++) { if(splitlist.get(i).equals("|")) continue; splitlist.set(i, type+splitlist.get(i)+closeType); } } for(int i = fromIndex; i<=untilIndex; i++) if(splitlist.get(i).equals("|")) splitlist.set(i, "[REMOVE]"); // remove all [REMOVE] from splitlist while(splitlist.contains("[REMOVE]")) splitlist.remove("[REMOVE]"); } split = splitlist.toArray(new String[0]); } int index = Arrays.asList(split).indexOf(string); if(index <= 0 || index > c.args().size()) return null; return c.args().get(index-1); } public static DocumentationReader instance() { if (instance == null) instance = new DocumentationReader(); return instance; } DocumentationReader() { try { //helpFilePath = DocumentationReader.class.getResource("/help/EditorHelp.txt").toURI().getPath(); readDoc(); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("static-method") public HashMap<Symbol, HelpInformation> documentation() { return documentation; } @SuppressWarnings("static-method") public HelpInformation help(Symbol symbol) { return documentation.get(symbol); } }
10,976
32.671779
120
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/documentation/HelpInformation.java
package app.display.dialogs.visual_editor.documentation; import main.grammar.Clause; import main.grammar.ClauseArg; import main.grammar.Symbol; import java.util.HashMap; public class HelpInformation { private final Symbol symbol; private String description; private final HashMap<Clause, String> ctor = new HashMap<>(); // syntax private final HashMap<Clause, String> examples = new HashMap<>(); // examples private final HashMap<ClauseArg, String> parameters = new HashMap<>(); // arguments private String remark = ""; public HelpInformation(Symbol symbol) { this.symbol = symbol; } public void setDescription(String description) { this.description = description; } public void addCtor(Clause clause, String syntax) { ctor.put(clause, syntax); } public void addExample(Clause clause, String example) { examples.put(clause, example); } public void addParameter(ClauseArg arg, String description1) { parameters.put(arg, description1); } public void setRemark(String remark) { this.remark = remark; } public Symbol symbol() { return symbol; } public String description() { return description; } public String remark() { return remark; } public String parameter(ClauseArg arg) { return parameters.get(arg); } public HashMap<ClauseArg, String> parameters() { return parameters; } }
1,538
19.52
87
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/handler/Handler.java
package app.display.dialogs.visual_editor.handler; import app.DesktopApp; import app.PlayerApp; import app.display.dialogs.visual_editor.StartVisualEditor; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.Edge; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.model.UserActions.*; import app.display.dialogs.visual_editor.view.VisualEditorFrame; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LudemeNodeComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LInputField; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import app.display.dialogs.visual_editor.view.panels.editor.backgrounds.CartesianGridBackground; import app.display.dialogs.visual_editor.view.panels.editor.backgrounds.DotGridBackground; import app.display.dialogs.visual_editor.view.panels.editor.backgrounds.EmptyBackground; import app.display.dialogs.visual_editor.view.panels.editor.backgrounds.IBackground; import app.display.dialogs.visual_editor.view.panels.editor.defineEditor.DefineEditor; import app.display.dialogs.visual_editor.view.panels.editor.defineEditor.DefineGraphPanel; import app.display.dialogs.visual_editor.view.panels.editor.gameEditor.GameGraphPanel; import app.display.dialogs.visual_editor.view.panels.editor.tabPanels.LayoutSettingsPanel; import app.display.dialogs.visual_editor.view.panels.header.ToolsPanel; import app.utils.GameUtil; import game.Game; import main.grammar.Clause; import main.grammar.Description; import main.grammar.Report; import main.grammar.Symbol; import main.options.UserSelections; import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Handler for the visual editor. * Handles all user actions and updates the view accordingly. * @author Filipp Dokienko */ public class Handler { // Graph Panels /** Main Game Editor Graph Panel */ public static GameGraphPanel gameGraphPanel; /** Define Graph Panels */ public static final List<DefineGraphPanel> defineGraphPanels = new ArrayList<>(); /** Currently selected Graph Panel */ public static IGraphPanel currentGraphPanel; /** Map of Graph Panels keyed by their DescriptionGraph */ private static final HashMap<DescriptionGraph, IGraphPanel> graphPanelMap = new HashMap<>(); // Defines /** The Input Symbol indicating the Parameter of a Define */ public static final Symbol PARAMETER_SYMBOL = new Symbol(Symbol.LudemeType.Ludeme, "PARAMETER", "PARAMETER", null); /** Map of a list of added define ludeme nodes keyed by their Define Graph */ private static final Map<DescriptionGraph, List<LudemeNode>> defineLudemeNodes = new HashMap<>(); /** Map of Graph Panels keyed by a define node which is part of the graph */ private static final Map<LudemeNode, DescriptionGraph> defineNodeToGraphMap = new HashMap<>(); // Undo and Redo functionality /** List of UserActions that were performed, keyed by the GraphPanel they were performed on */ private static final Map<IGraphPanel, Stack<IUserAction>> performedUserActionsMap = new HashMap<>(); /** List of UserActions that were undone, keyed by the GraphPanel they were undone on */ private static final Map<IGraphPanel, Stack<IUserAction>> undoneUserActionsMap = new HashMap<>(); /** List of UserActions on the current graph panel */ private static Stack<IUserAction> currentPerformedUserActions; /** List of undone UserActions on the current graph panel */ private static Stack<IUserAction> currentUndoneUserActions; /** The Action that is currently being undone */ private static IUserAction currentUndoAction; /** The Action that is currently being redone */ private static IUserAction currentRedoAction; /** Whether the Handler should record User Actions (store them) */ public static boolean recordUserActions = true; // Copied nodes /** List of currently copied nodes */ private static List<LudemeNode> clipboard = new ArrayList<>(); // Compiling /** The last compile */ public static Object[] lastCompile; /** Whether the game should be compiled after each change */ public static boolean liveCompile = false; // Sensitivity to changes /** Whether sensitive actions should be confirmed by the user */ public static boolean sensitivityToChanges = true; /** When X nodes are removed at once, ask the user for confirmation */ public static final int SENSITIVITY_REMOVAL = 6; /** When X collection elements are removed at once, ask the user for confirmation */ public static final int SENSITIVITY_COLLECTION_REMOVAL = 4; // Additional Panels of the Frame /** Main Frame */ public static VisualEditorFrame visualEditorFrame; /** Define Editor */ public static DefineEditor defineEditor; /** ToolsPanel, including undo, redo and play buttons */ public static ToolsPanel toolsPanel; /** Panel for layout settings */ public static LayoutSettingsPanel lsPanel; // Layout Settings /** Whether the layout-settings sidebar is visible */ public static final boolean sidebarVisible = true; /** Whether layout-arrangement animations are enabled */ public static boolean animation = false; /** Whether nodes should be placed arranged automatically */ public static boolean autoplacement = false; /** Whether layout configurations should be evaluated from user-placement when arranging graph */ public static boolean evaluateLayoutMetrics = false; // Appearance Settings /** Backgrounds: Dot Grid, Cartesian Grid, and no Grid */ public static final IBackground DotGridBackground = new DotGridBackground(); public static final IBackground EmptyBackground = new EmptyBackground(); public static final IBackground CartesianGridBackground = new CartesianGridBackground(); /** Currently active Background */ private static IBackground currentBackground = DotGridBackground; /** Instantiate the DesignPalette */ @SuppressWarnings("unused") private static final DesignPalette designPalette = DesignPalette.instance(); /** Whether there is any output to the console */ private static final boolean DEBUG = true; // ~~~~~~~ Graph Panels ~~~~~~~ /** * Assigns a IGraphPanel to a DescriptionGraph * @param graph graph to be assigned * @param graphPanel graph panel */ public static void addGraphPanel(DescriptionGraph graph, IGraphPanel graphPanel) { if(!graphPanelMap.containsKey(graph)) { graphPanelMap.put(graph, graphPanel); if(graphPanel.isDefineGraph() && !defineGraphPanels.contains(graphPanel)) defineGraphPanels.add((DefineGraphPanel) graphPanel); performedUserActionsMap.put(graphPanel, new Stack<>()); undoneUserActionsMap.put(graphPanel, new Stack<>()); } } /** * Removes a IGraphPanel from the map * @param graphPanel */ public static void removeGraphPanel(IGraphPanel graphPanel) { graphPanelMap.remove(graphPanel.graph()); if(graphPanel.isDefineGraph()) defineGraphPanels.remove(graphPanel); performedUserActionsMap.remove(graphPanel); undoneUserActionsMap.remove(graphPanel); System.out.println("Removed graph panel: " + graphPanel.graph()); System.out.println("Remaining graph panels: " + defineGraphPanels.size()); } /** * Updates the current active graph panel * @param graphPanel graph panel to be set as active */ public static void updateCurrentGraphPanel(IGraphPanel graphPanel) { currentGraphPanel = graphPanel; currentPerformedUserActions = performedUserActionsMap.get(graphPanel); currentUndoneUserActions = undoneUserActionsMap.get(graphPanel); if(toolsPanel != null) toolsPanel.updateUndoRedoBtns(currentPerformedUserActions, currentUndoneUserActions); } // ~~~~~~~ Changes to the graph ~~~~~~~ /** * Adds a node to the graph * @param graph graph in operation * @param node node to be added */ public static void addNode(DescriptionGraph graph, LudemeNode node ) { addNode(graph, node, false); } /** * Adds a node to the graph * @param graph graph in operation * @param node node to be added * @param connect Whether the node will be connected after insertion */ public static void addNode(DescriptionGraph graph, LudemeNode node, boolean connect) { if(DEBUG) System.out.println("[HANDLER] addNode(graph. node, connect) Adding node: " + node.title()); if(graph.getNodes().isEmpty()) graph.setRoot(node); graph.addNode(node); // if added node is a define node, store this node in the map if(node.isDefineNode()) { List<LudemeNode> defineNodes = defineLudemeNodes.computeIfAbsent(node.defineGraph(), k -> new ArrayList<>()); defineNodes.add(node); defineNodeToGraphMap.put(node, graph); } // notify graph panel IGraphPanel graphPanel = graphPanelMap.get(graph); addAction(new AddedNodeAction(graphPanel, node)); graphPanel.notifyNodeAdded(node, connect); if(recordUserActions && node.parentNode() != null && (node.parentNode().providedInputsMap().get(node.creatorArgument()) instanceof Object[])) { Object[] collectionInput = (Object[]) node.parentNode().providedInputsMap().get(node.creatorArgument()); int elementIndex = Arrays.asList(collectionInput).indexOf(node); ((AddedNodeAction) currentPerformedUserActions.peek()).setCollectionIndex(elementIndex); } } /** * Creates and adds a node to the graph * @param graph Graph to add the node to * @param symbol The symbol of the node to be created * @param nodeArgument The NodeArgument which created this node * @param x The x-position of the node * @param y The y-position of the node * @param connect Whether the node will be connected after insertion * @return The created node */ public static LudemeNode addNode(DescriptionGraph graph, Symbol symbol, NodeArgument nodeArgument, int x, int y, boolean connect) { LudemeNode node = new LudemeNode(symbol, nodeArgument, x, y); addNode(graph, node, connect); return node; } /** * Adds a 1D Collection Node to the graph, which is a node that can be connected to a 2D Collection Input * @param graph Graph to add the node to * @param nodeArgument2DCollection The NodeArgument which created this node (must be 2D collection) * @param x The x-position of the node * @param y The y-position of the node */ public static void addNode(DescriptionGraph graph, NodeArgument nodeArgument2DCollection, int x, int y) { LudemeNode node = new LudemeNode(nodeArgument2DCollection, x, y); addNode(graph, node, true); } /** * Removes a node from the graph. * @param graph The graph that contains the node. * @param node The node to remove. */ public static void removeNode(DescriptionGraph graph, LudemeNode node) { if(graph.getRoot() == node) return; if(DEBUG) System.out.println("[HANDLER] removeNode(graph, node) -> Removing node: " + node.title()); // remove node from map if a define node if(node.isDefineNode()) { defineLudemeNodes.get(node.defineGraph()).remove(node); defineNodeToGraphMap.remove(node); } IUserAction action = new RemovedNodeAction(graphPanelMap.get(graph), node); addAction(action); if(lastActionEquals(action)) Handler.recordUserActions = false; // if the action is added, and the node was part of a collection, notify the action about the collection element index if(recordUserActions && node.parentNode() != null && (node.parentNode().providedInputsMap().get(node.creatorArgument()) instanceof Object[])) { Object[] collectionInput = (Object[]) node.parentNode().providedInputsMap().get(node.creatorArgument()); int elementIndex = Arrays.asList(collectionInput).indexOf(node); ((RemovedNodeAction) currentPerformedUserActions.peek()).setCollectionIndex(elementIndex); } // Remove the node from the graph graph.removeNode(node); // notify its children that its parent is null node.childrenNodes().forEach(child -> child.setParent(null)); // notify its parent that its child is null if(node.parentNode() != null) node.parentNode().removeChildren(node); // reset the parent's inputs if(node.parentNode() != null) { List<NodeArgument> args = new ArrayList<>(node.parentNode().providedInputsMap().keySet()); List<Object> inputs = new ArrayList<>(node.parentNode().providedInputsMap().values()); int index2 = inputs.indexOf(node); if(index2>=0 && !(node.parentNode().providedInputsMap().get(args.get(index2)) instanceof Object[])) { Handler.updateInput(graph, node.parentNode(), args.get(index2), null); } } IGraphPanel graphPanel = graphPanelMap.get(graph); graphPanel.notifyNodeRemoved(graphPanel.nodeComponent(node)); if(lastActionEquals(action)) Handler.recordUserActions = true; if (Handler.autoplacement && currentGraphPanel.selectedLnc().size() == 1) { currentGraphPanel.graph().setSelectedRoot(-1); currentGraphPanel.getLayoutHandler().executeLayout(); } } /** * Removes a list of nodes from the graph * @param graph * @param nodes */ public static void removeNodes(DescriptionGraph graph, List<LudemeNode> nodes) { if(DEBUG) System.out.println("[HANDLER] removeNodes(graph, nodes) -> Removing nodes: " + nodes.size()); // display dialog to confirm removal of nodes if(nodes.size() >= SENSITIVITY_REMOVAL && Handler.sensitivityToChanges) { int userChoice = JOptionPane.showConfirmDialog(null, "Are you sure you want to remove " + nodes.size() + " nodes?", "Remove nodes", JOptionPane.YES_NO_OPTION); if(userChoice != JOptionPane.YES_OPTION) { return; } } // remove root node and already deleted nodes for(LudemeNode node : new ArrayList<>(nodes)) { if(graph.getRoot() == node) { nodes.remove(node); break; } } IUserAction action = new RemovedNodesAction(graphPanelMap.get(graph), nodes); addAction(action); if(lastActionEquals(action)) Handler.recordUserActions = false; for(LudemeNode n : nodes) removeNode(graph, n); if(lastActionEquals(action)) Handler.recordUserActions = true; if (Handler.autoplacement) { currentGraphPanel.graph().setSelectedRoot(-1); currentGraphPanel.getLayoutHandler().executeLayout(); } } /** * Removes currently selected nodes from the currently selected graph */ public static void remove() { remove(currentGraphPanel.graph()); } /** * Removes currently selected nodes from the given graph * @param graph Graph to remove nodes from */ public static void remove(DescriptionGraph graph) { List<LudemeNode> selectedNodes = selectedNodes(graph); if(selectedNodes.isEmpty()) return; if(selectedNodes.size() == 1) removeNode(graph, selectedNodes.get(0)); else removeNodes(graph, selectedNodes); } // ~~~~~~~ Changes to the nodes ~~~~~~~ /** * Updates the selected clause of a node * @param graph Graph to update the node in * @param node Node to update * @param c Clause to update to */ public static void updateCurrentClause(DescriptionGraph graph, LudemeNode node, Clause c) { Clause oldClause = node.selectedClause(); if(oldClause == c) return; IGraphPanel graphPanel = graphPanelMap.get(graph); IUserAction action = new ChangedClauseAction(graphPanel, node, oldClause, c); addAction(action); // remove all edges from the node for(Object input : node.providedInputsMap().values()) { if(input instanceof LudemeNode) { if(lastActionEquals(action)) { Handler.recordUserActions = false; removeEdge(graph, node, (LudemeNode) input); Handler.recordUserActions = true; } } } if(c.args() == null) node.setSelectedClause(c.symbol().rule().rhs().get(0)); else node.setSelectedClause(c); graphPanel.notifySelectedClauseChanged(graphPanel.nodeComponent(node)); } /** * Adds an empty collection input to collection of a node * @param graph The graph that contains the node. * @param node The node to update. * @param nodeArgument The argument of the node to update, which is a collection. */ public static void addCollectionElement(DescriptionGraph graph, LudemeNode node, NodeArgument nodeArgument) { if(DEBUG) System.out.println("[HANDLER] addCollectionElement(graph, node, nodeArgument) Adding collection element of " + node.title() + ", " + nodeArgument); IGraphPanel graphPanel = graphPanelMap.get(graph); Object[] oldCollection = (Object[]) node.providedInputsMap().get(nodeArgument); if(oldCollection == null) { IUserAction action = new AddedCollectionAction(graphPanel, node, nodeArgument, 1, null); addAction(action); if(lastActionEquals(action)) { Handler.recordUserActions = false; } updateInput(graph, node, nodeArgument, new Object[2]); if(lastActionEquals(action)) { Handler.recordUserActions = true; } graphPanel.notifyCollectionAdded(graphPanel.nodeComponent(node), nodeArgument, 1); return; } Object[] newCollection = new Object[oldCollection.length + 1]; System.arraycopy(oldCollection, 0, newCollection, 0, oldCollection.length); IUserAction action = new AddedCollectionAction(graphPanel, node, nodeArgument, oldCollection.length, null); addAction(action); if(lastActionEquals(action)) Handler.recordUserActions = false; updateInput(graph, node, nodeArgument, newCollection); if(lastActionEquals(action)) Handler.recordUserActions = true; graphPanel.notifyCollectionAdded(graphPanel.nodeComponent(node), nodeArgument, newCollection.length - 1); } /** * if a collection element was removed, update the provided input array * @param graph * @param node * @param nodeArgument * @param elementIndex Index of collection element */ public static void removeCollectionElement(DescriptionGraph graph, LudemeNode node, NodeArgument nodeArgument, int elementIndex) { if(DEBUG) System.out.println("[HANDLER] removeCollectionElement(graph, node, nodeArgument, elementIndex) Removing collection element of " + node.title() + ", " + nodeArgument + ", elementIndex: " + elementIndex); Object[] oldCollection = (Object[]) node.providedInputsMap().get(nodeArgument); if(oldCollection == null) return; // get input Object input = oldCollection[elementIndex]; IUserAction action = new RemovedCollectionAction(graphPanelMap.get(graph), node, nodeArgument, elementIndex, input); addAction(action); Object[] newCollection = new Object[oldCollection.length - 1]; if(currentUndoAction instanceof AddedCollectionAction) if(((AddedCollectionAction) currentUndoAction).isUpdated(node, nodeArgument, elementIndex)) ((AddedCollectionAction) currentUndoAction).setInput(input); System.arraycopy(oldCollection, 0, newCollection, 0, elementIndex); if (oldCollection.length - (elementIndex + 1) >= 0) System.arraycopy(oldCollection, elementIndex + 1, newCollection, elementIndex + 1 - 1, oldCollection.length - (elementIndex + 1)); if(lastActionEquals(action)) Handler.recordUserActions = false; updateInput(graph, node, nodeArgument, newCollection); if(input instanceof LudemeNode) removeEdge(graph, node, (LudemeNode) input, elementIndex); if(lastActionEquals(action)) Handler.recordUserActions = true; IGraphPanel graphPanel = graphPanelMap.get(graph); graphPanel.notifyCollectionRemoved(graphPanel.nodeComponent(node), nodeArgument, elementIndex); } /** * Adds and edge between two nodes. * @param graph The graph that contains the nodes. * @param from The node that the edge starts from. * @param to The node that the edge ends at. * @param nodeArgument The nodeArgument of the field */ public static void addEdge(DescriptionGraph graph, LudemeNode from, LudemeNode to, NodeArgument nodeArgument) { // check whether the edge already exists for(Edge e : graph.getEdgeList()) if(e.getNodeA() == from.id() && e.getNodeB() == to.id()) return; if(DEBUG) System.out.println("[HANDLER] addEdge(graph, form, to, nodeArgument) -> Adding edge: " + from.title() + " -> " + to.title()); graph.addEdge(from.id(), to.id()); // notify graph panel to draw edge IGraphPanel graphPanel = graphPanelMap.get(graph); graphPanel.notifyEdgeAdded(graphPanel.nodeComponent(from), graphPanel.nodeComponent(to), nodeArgument); // here from is the parent node from.addChild(to); to.setParent(from); } /** * Adds and edge between two nodes. * @param graph The graph that contains the nodes. * @param from The node that the edge starts from. * @param to The node that the edge ends at. * @param nodeArgument The nodeArgument of the field * @param elementIndex If the edge is part of a collection, the index of the element in the collection */ public static void addEdge(DescriptionGraph graph, LudemeNode from, LudemeNode to, NodeArgument nodeArgument, int elementIndex) { // check whether the edge already exists for(Edge e : graph.getEdgeList()) if(e.getNodeA() == from.id() && e.getNodeB() == to.id()) return; if(DEBUG) System.out.println("[HANDLER] addEdge(graph, form, to, nodeArgument, elementIndex) -> Adding edge: " + from.title() + " -> " + to.title() + ", elementIndex: " + elementIndex); graph.addEdge(from.id(), to.id()); // if the edge is part of a collection, adjust the collection size while(from.providedInputsMap().get(nodeArgument) == null || elementIndex+1>((Object[])from.providedInputsMap().get(nodeArgument)).length) addCollectionElement(graph, from, nodeArgument); // notify graph panel to draw edge IGraphPanel graphPanel = graphPanelMap.get(graph); graphPanel.notifyEdgeAdded(graphPanel.nodeComponent(from), graphPanel.nodeComponent(to), nodeArgument, elementIndex); // here from is the parent node from.addChild(to); to.setParent(from); } /** * Adds and edge between two nodes. * @param graph The graph that contains the nodes. * @param from The node that the edge starts from. * @param to The node that the edge ends at. */ public static void addEdge(DescriptionGraph graph, LudemeNode from, LudemeNode to, int inputFieldIndex) { addEdge(graph, from, to, inputFieldIndex, true); } /** * Adds and edge between two nodes. * @param graph The graph that contains the nodes. * @param from The node that the edge starts from. * @param to The node that the edge ends at. * @param inputFieldIndex The index of the inputfield where the connection stems from * @param notify Whether to notify the graph panel of the edge addition */ public static void addEdge(DescriptionGraph graph, LudemeNode from, LudemeNode to, int inputFieldIndex, boolean notify) { // check whether the edge already exists for(Edge e : graph.getEdgeList()) if(e.getNodeA() == from.id() && e.getNodeB() == to.id()) return; if(DEBUG) System.out.println("[HANDLER] nodeArgument(graph, form, to, inputFieldIndex) -> Adding edge: " + from.title() + " -> " + to.title() + ", inputFieldIndex: " + inputFieldIndex); graph.addEdge(from.id(), to.id()); if(notify) { // notify graph panel to draw edge IGraphPanel graphPanel = graphPanelMap.get(graph); graphPanel.notifyEdgeAdded(graphPanel.nodeComponent(from), graphPanel.nodeComponent(to), inputFieldIndex); } // here from is the parent node from.addChild(to); to.setParent(from); } /** * Removes an edge between two nodes. * @param graph The graph that contains the nodes. * @param from The node that the edge starts from. * @param to The node that the edge ends at. */ public static void removeEdge(DescriptionGraph graph, LudemeNode from, LudemeNode to) { removeEdge(graph, from, to, true); } /** * Removes an edge between two nodes. * @param graph The graph that contains the nodes. * @param from The node that the edge starts from. * @param to The node that the edge ends at. * @param notify Whether the graph panel should be notified about the removal of the edge */ public static void removeEdge(DescriptionGraph graph, LudemeNode from, LudemeNode to, boolean notify) { if(DEBUG) System.out.println("[HANDLER] removeEdge(graph, from, to) -> Removing edge: " + from.title() + " -> " + to.title()); graph.removeEdge(from.id(), to.id()); from.removeChildren(to); to.setParent(null); if(notify) { IGraphPanel graphPanel = graphPanelMap.get(graph); graphPanel.notifyEdgeRemoved(graphPanel.nodeComponent(from), graphPanel.nodeComponent(to)); } } /** * Removes an edge between two nodes of a given collection element index. * @param graph The graph that contains the nodes. * @param from The node that the edge starts from. * @param to The node that the edge ends at. * @param elementIndex The index of the element in the collection */ public static void removeEdge(DescriptionGraph graph, LudemeNode from, LudemeNode to, int elementIndex) { removeEdge(graph, from, to, elementIndex, true); } /** * Removes an edge between two nodes of a given collection element index. * @param graph The graph that contains the nodes. * @param from The node that the edge starts from. * @param to The node that the edge ends at. * @param elementIndex The index of the element in the collection * @param notify Whether the graph panel should be notified about the removal of the edge */ public static void removeEdge(DescriptionGraph graph, LudemeNode from, LudemeNode to, int elementIndex, boolean notify) { if(DEBUG) System.out.println("[HANDLER] removeEdge(graph, from, to, elementIndex) -> Removing edge: " + from.title() + " -> " + to.title() + " at index " + elementIndex); graph.removeEdge(from.id(), to.id()); from.removeChildren(to); to.setParent(null); if(notify) { IGraphPanel graphPanel = graphPanelMap.get(graph); graphPanel.notifyEdgeRemoved(graphPanel.nodeComponent(from), graphPanel.nodeComponent(to), elementIndex); } } /** * An optional terminal argument was activated/deactivated * @param graph * @param node * @param argument * @param activate */ public static void activateOptionalTerminalField(DescriptionGraph graph, LudemeNode node, NodeArgument argument, boolean activate) { IGraphPanel graphPanel = graphPanelMap.get(graph); IUserAction action = new ActivateOptionalTerminalAction(graphPanel, node, argument, activate); addAction(action); if(lastActionEquals(action)) Handler.recordUserActions = false; graphPanel.notifyTerminalActivated(graphPanel.nodeComponent(node), argument, activate); if(lastActionEquals(action)) Handler.recordUserActions = true; } // ~~~~~~~ Node Input Updates ~~~~~~~ /** * Updates the input of a node. * @param graph The graph that contains the node. * @param node The node to update. * @param nodeArgument The argument of the node to update. * @param input The new input. */ public static void updateInput(DescriptionGraph graph, LudemeNode node, NodeArgument nodeArgument, Object input) { if(DEBUG) System.out.println("[HANDLER] updateInput(graph, node, nodeArgument, input) -> Updating input: " + node.title() + ", " + nodeArgument + " -> " + input); IGraphPanel graphPanel = graphPanelMap.get(graph); if(input instanceof LudemeNode) { // if the input does not originate from a node creation, record the adding of the edge IUserAction lastAction = null; if(!currentPerformedUserActions.isEmpty()) { lastAction = currentPerformedUserActions.peek(); } if(lastAction instanceof AddedNodeAction) { if(!(((AddedNodeAction) lastAction).addedNode() == input && ((AddedNodeAction) lastAction).addedNode().creatorArgument() == nodeArgument)) { addAction(new AddedConnectionAction(graphPanel, node, (LudemeNode) input, nodeArgument)); } } else { addAction(new AddedConnectionAction(graphPanel, node, (LudemeNode) input, nodeArgument)); } } if(input == null) { Object oldInput = node.providedInputsMap().get(nodeArgument); if(oldInput instanceof LudemeNode) { addAction(new RemovedConnectionAction(graphPanelMap.get(graph), node, (LudemeNode) oldInput, nodeArgument)); //node.removeChildren((LudemeNode) oldInput); removeEdge(graph, node, (LudemeNode) oldInput, false); } } node.setProvidedInput(nodeArgument, input); if(node.isSatisfied() && graphPanel.nodeComponent(node) != null) { LudemeNodeComponent lnc = graphPanel.nodeComponent(node); if(lnc.isMarkedUncompilable()) { lnc.markUncompilable(false); } } // if it's a define graph, notify the graph about that if(graph.isDefine()) graph.notifyDefineChanged(nodeArgument, input); if(!graph.isDefine() && liveCompile && isConnectedToRoot(graph, node)) compile(); } /** * Updates the input of a collection field * @param graph * @param node * @param nodeArgument * @param input * @param elementIndex The index of the element within the collection */ public static void updateCollectionInput(DescriptionGraph graph, LudemeNode node, NodeArgument nodeArgument, Object input, int elementIndex) { if(DEBUG) System.out.println("[HANDLER] updateCollectionInput(graph, node, nodeArgument, input, elementIndex) Updating collection input of " + node.title() + ", " + nodeArgument + ", elementIndex: " + elementIndex + " to " + input); if(node.providedInputsMap().get(nodeArgument) == null) node.setProvidedInput(nodeArgument, new Object[1]); if(input == null && node.providedInputsMap().get(nodeArgument) instanceof Object[] && elementIndex >= ((Object[])(node.providedInputsMap().get(nodeArgument))).length) return; Object oldInput = node.providedInputsMap().get(nodeArgument); if(oldInput instanceof Object[] && input == null && ((Object[])(oldInput)).length > elementIndex && ((Object[])oldInput)[elementIndex] instanceof LudemeNode) { Handler.removeEdge(graph, node, (LudemeNode) ((Object[])(oldInput))[elementIndex], elementIndex, false); } if(node.providedInputsMap().get(nodeArgument) == null) return; while(elementIndex >= ((Object[])(node.providedInputsMap().get(nodeArgument))).length) addCollectionElement(graph, node, nodeArgument); Object[] in = (Object[]) oldInput; in[elementIndex] = input; Handler.updateInput(graph, node, nodeArgument, in); } // ~~~~~~~ Defines ~~~~~~~ /** * * @return A list of define ludeme nodes */ public static List<LudemeNode> defineNodes() { List<LudemeNode> list = new ArrayList<>(); for(DefineGraphPanel dgp : defineGraphPanels) { LudemeNode defineNode = dgp.graph().defineNode(); if(defineNode != null) { list.add(defineNode); } } return list; } /** * Updates all define nodes' symbol. Called when the title was changed. * The effect of this is that the title of the affected define nodes is changed. * @param graph The modified define graph * @param symbol The new symbol */ public static void updateDefineNodes(DescriptionGraph graph, Symbol symbol) { if(DEBUG) System.out.println("[HANDLER] Title of Define Node changed to " + symbol.name()); defineEditor.updateName(symbol.name()); // Get List of define nodes List<LudemeNode> defineNodes = defineLudemeNodes.get(graph); if(defineNodes == null) return; for(LudemeNode ln : defineNodes) { // Update symbol ln.updateDefineNode(symbol); // Update component // get graph panel IGraphPanel gp = graphPanelMap.get(defineNodeToGraphMap.get(ln)); // get component and update component gp.nodeComponent(ln).repaint(); } } /** * Updates all define nodes' list of required parameters. Called when the parameters were changed. * 1) currentNodeArguments field in LudemeNode updated * 2) Remove invalid collections * 3) Add/Remove input fields according to new list * @param graph * @param parameters */ public static void updateDefineNodes(DescriptionGraph graph, List<NodeArgument> parameters) { if(DEBUG) System.out.println("[HANDLER] Parameters of Define Node changed: " + parameters); // Get List of define nodes List<LudemeNode> defineNodes = defineLudemeNodes.get(graph); if(defineNodes == null) return; for(LudemeNode ln : defineNodes) { // Update parameters ln.updateDefineNode(parameters); // Update component // get graph panel IGraphPanel gp = graphPanelMap.get(defineNodeToGraphMap.get(ln)); // get component and update component gp.nodeComponent(ln).changedArguments(parameters); } } public static void updateDefineNodes(DescriptionGraph graph, LudemeNode macroNode) { if(DEBUG) System.out.println("[HANDLER] Macro Node changed"); // Get List of define nodes List<LudemeNode> defineNodes = defineLudemeNodes.get(graph); if(defineNodes == null) return; for(LudemeNode ln : defineNodes) { // Update macro node ln.updateDefineNode(macroNode); // remove ingoing connections if(ln.parentNode() != null) { removeEdge(defineNodeToGraphMap.get(ln), ln.parentNode(), ln); } } } /** * Removes a define * @param graph */ public static void removeDefine(DescriptionGraph graph) { defineEditor.removalGraph(graphPanelMap.get(graph)); } // ~~~~~~~ Compiling ~~~~~~~ /** * Attempts to compile the graph. * @return Array with 3 elements: Game (or null), List of Error Messages, List of unsatisfied nodes. */ public static Object[] compile() { return compile(false); } /** * Attempts to compile the graph. * @param openDialog Whether a dialog displaying the errors should be opened. * @return Array with 3 elements: Game (or null), List of Error Messages, List of unsatisfied nodes. */ public static Object[] compile(boolean openDialog) { if(!recordUserActions) return new Object[]{null, null, null}; Object[] output = new Object[3]; List<LudemeNode> unsatisfiedNodes = isComplete(gameGraphPanel.graph()); if(!unsatisfiedNodes.isEmpty()) { List<String> errors = new ArrayList<>(); StringBuilder errorMessage = new StringBuilder("Nodes are missing required arguments:\n"); for(LudemeNode node : unsatisfiedNodes) { errorMessage.append(node.title()).append(", \n"); } errors.add(errorMessage.toString()); output[1] = errors; output[2] = unsatisfiedNodes; if(liveCompile) { lastCompile = output; if(toolsPanel != null) { toolsPanel.play.updateCompilable(output); } } if(openDialog) { Handler.markUncompilable(); JOptionPane.showMessageDialog(null, errorMessage.toString(), "Couldn't compile", JOptionPane.ERROR_MESSAGE); } return output; } Description d = gameGraphPanel.graph().description(); Report r = new Report(); try { if (StartVisualEditor.app != null) { output[0] = compiler.Compiler.compile(d, StartVisualEditor.app.manager().settingsManager().userSelections(), r, false); } else { output[0] = compiler.Compiler.compile(d, new UserSelections(new ArrayList<>()), r, false); } } catch(Exception ignored) { // Nothing to do } output[1] = r.errors(); if(liveCompile) { lastCompile = output; if(toolsPanel != null) { toolsPanel.play.updateCompilable(output); } } if(output[0] == null && openDialog) { @SuppressWarnings("unchecked") java.util.List<String> errors = (List<String>) output[1]; String errorMessage; if (errors.isEmpty()) { errorMessage = "Could not create \"game\" ludeme from description."; } else { errorMessage = errors.toString(); errorMessage = errorMessage.substring(1, errorMessage.length() - 1); } JOptionPane.showMessageDialog(null, errorMessage, "Couldn't compile", JOptionPane.ERROR_MESSAGE); } return output; } /** * Marks uncompilable nodes in the graph. */ public static void markUncompilable() { List<LudemeNode> unsatisfiedNodes = isComplete(gameGraphPanel.graph()); List<LudemeNodeComponent> lncs = new ArrayList<>(); for(LudemeNode node : unsatisfiedNodes) lncs.add(gameGraphPanel.nodeComponent(node)); gameGraphPanel.notifyUncompilable(lncs); } /** * Executes the game */ public static void play() { Object[] output = lastCompile; // first compile if(lastCompile == null) output = compile(); if(output[0] == null) return; Game game = (Game) output[0]; // load game loadGame(game, StartVisualEditor.app); } /** * Executes a given game * @param game */ public static void play(Game game) { loadGame(game, StartVisualEditor.app); } /** * Loads the game into the game engine. * @param game * @param app */ public static void loadGame(Game game, PlayerApp app) { app.manager().ref().setGame(app.manager(), game); GameUtil.startGame(app); app.restartGame(); DesktopApp.frame().requestFocus(); } /** * * @return The .lud equivalent of the game graph */ public static String toLud() { return gameGraphPanel.graph().toLud(); } // ~~~~~~~ Selecting Nodes ~~~~~~~ /** * * @param graph * @return The selected nodes of a graph */ public static List<LudemeNode> selectedNodes(DescriptionGraph graph) { IGraphPanel graphPanel = graphPanelMap.get(graph); List<LudemeNode> nodes = new ArrayList<>(); for(LudemeNodeComponent lnc : graphPanel.selectedLnc()) nodes.add(lnc.node()); return nodes; } /** * Selects all nodes of the current graph. */ public static void selectAll() { selectAll(currentGraphPanel.graph()); } /** * Unselects all nodes of the current graph. */ public static void unselectAll() { currentGraphPanel.deselectEverything(); } /** * Selects all nodes of a graph. * @param graph */ public static void selectAll(DescriptionGraph graph) { IGraphPanel graphPanel = graphPanelMap.get(graph); graphPanel.selectAllNodes(); } /** * Selects a node * @param node */ public static void selectNode(LudemeNodeComponent node) { currentGraphPanel.addNodeToSelections(node); currentGraphPanel.repaint(); } /** * Activates the selection mode */ public static void activateSelectionMode() { currentGraphPanel.enterSelectionMode(); } /** * Deactivates the selection mode */ public static void deactivateSelectionMode() { currentGraphPanel.exitSelectionMode(); toolsPanel.deactivateSelection(); currentGraphPanel.repaint(); } /** * Turns off the selection button in the tools panel. */ public static void turnOffSelectionBtn() { toolsPanel.deactivateSelection(); toolsPanel.repaint(); toolsPanel.revalidate(); } // ~~~~~~~ Copying Nodes ~~~~~~~ /** * Copies the selected nodes of the currently active graph panel. */ public static void copy() { copy(currentGraphPanel.graph()); } /** * Copies the selected nodes of the given graph. * @param graph */ public static void copy(DescriptionGraph graph) { IGraphPanel graphPanel = graphPanelMap.get(graph); List<LudemeNode> toCopy = new ArrayList<>(); for(LudemeNodeComponent lnc : graphPanel.selectedLnc()) if(graph.getRoot() != lnc.node()) toCopy.add(lnc.node()); copy(toCopy); } /** * Copies the given nodes. * @param nodes */ public static void copy(List<LudemeNode> nodes) { if(nodes.isEmpty()) return; if(DEBUG) System.out.println("[HANDLER] copy(graph, nodes) Copying " + nodes.size() + " nodes"); clipboard.clear(); clipboard = copyTemporarily( nodes); } /** * Copies the given nodes and returns a list of the copied nodes. * @param nodes */ public static List<LudemeNode> copyTemporarily(List<LudemeNode> nodes) { if(nodes.isEmpty()) return new ArrayList<>(); if(DEBUG) System.out.println("[HANDLER] copy(graph, nodes) Copying " + nodes.size() + " nodes"); HashMap<LudemeNode, LudemeNode> copiedNodes = new HashMap<>(); // <original, copy> // create copies for(LudemeNode node : nodes) copiedNodes.put(node, node.copy()); // fill inputs (connections and collections) for(LudemeNode node : nodes) { LudemeNode copy = copiedNodes.get(node); // iterate each original node's provided inputs for (NodeArgument arg : node.providedInputsMap().keySet()) { Object input = node.providedInputsMap().get(arg); // input is a node if (input instanceof LudemeNode) { LudemeNode inputNode = (LudemeNode) input; // if input node is in the list of nodes to copy, copy it if (nodes.contains(inputNode)) { LudemeNode inputNodeCopy = copiedNodes.get(inputNode); copy.setProvidedInput(arg, inputNodeCopy); copy.addChild(inputNodeCopy); inputNodeCopy.setParent(copy); } } // input is a collection else if (input instanceof Object[]) { Object[] inputCollection = (Object[]) input; Object[] inputCollectionCopy = new Object[inputCollection.length]; for (int i = 0; i < inputCollection.length; i++) { // if input element is a node if (inputCollection[i] instanceof LudemeNode) { LudemeNode inputNode = (LudemeNode) inputCollection[i]; // if input node is in the list of nodes to copy, copy it if (nodes.contains(inputNode)) { LudemeNode inputNodeCopy = copiedNodes.get(inputNode); inputCollectionCopy[i] = inputNodeCopy; copy.addChild(inputNodeCopy); inputNodeCopy.setParent(copy); } } } copy.setProvidedInput(arg, inputCollectionCopy); } } } // store copied nodes return new ArrayList<>(copiedNodes.values()); } /** * * @return List of currently copied nodes */ public static List<LudemeNode> clipboard() { return clipboard; } // ~~~~~~~ Pasting Nodes ~~~~~~~ /** * Pastes nodes copied to the clipboard * @param x x-coordinate of the paste location * @param y y-coordinate of the paste location */ public static void paste(int x, int y) { paste(currentGraphPanel.graph(), x, y); } /** * Pastes nodes copied to the clipboard to the given graph * @param graph * @param x * @param y */ public static void paste(DescriptionGraph graph, int x, int y) { if(clipboard.isEmpty()) return; // old copy List<LudemeNode> oldCopy = new ArrayList<>(clipboard); clipboard.clear(); copy(oldCopy); paste(graph, oldCopy, x, y); } /** * Pastes a list of nodes * @param graph * @param nodes * @param x x-coordinate of the first node * @param y y-coordinate of the first node */ public static void paste(DescriptionGraph graph, List<LudemeNode> nodes, int x, int y) { if(DEBUG) System.out.println("[HANDLER] paste(graph, x, y) Pasting " + nodes.size() + " nodes"); recordUserActions = false; IGraphPanel graphPanel = graphPanelMap.get(graph); // find left-most node LudemeNode leftMostNode = nodes.get(0); for(LudemeNode node : nodes) if(node.x() < leftMostNode.x()) leftMostNode = node; int x_shift, y_shift; if(x == -1 && y == -1) { Rectangle v = graphPanel.parentScrollPane().getViewport().getViewRect(); x_shift = (int) (v.x - leftMostNode.x() + (v.getWidth()/2)); y_shift = (int) (v.y - leftMostNode.y() + (v.getHeight()/2)); } else { x_shift = x - leftMostNode.x(); y_shift = y - leftMostNode.y(); } // add nodes to graph for(LudemeNode node : nodes) { node.setX(node.x() + x_shift); node.setY(node.y() + y_shift); addNode(graph, node); } // update all edges for(LudemeNode parent : nodes) { for(NodeArgument argument : parent.providedInputsMap().keySet()) { Object input = parent.providedInputsMap().get(argument); if(input instanceof LudemeNode) { LudemeNode inputNode = (LudemeNode) input; if(nodes.contains(inputNode)) { addEdge(graph, parent, inputNode, argument); } } else if(input instanceof Object[]) { Object[] inputCollection = (Object[]) input; Object[] placeholder = new Object[1]; parent.setProvidedInput(argument, placeholder); for(int i = 0; i < inputCollection.length; i++) { if(inputCollection[i] instanceof LudemeNode) { LudemeNode inputNode = (LudemeNode) inputCollection[i]; if(nodes.contains(inputNode)) { addEdge(graph, parent, inputNode, argument, i); } } else if(i>0) { addCollectionElement(graph, parent, argument); } } if(parent.providedInputsMap().get(argument) == placeholder) { parent.setProvidedInput(argument, inputCollection); } } } } graphPanel.repaint(); recordUserActions = true; IUserAction action = new PasteAction(graphPanel, nodes); addAction(action); } // ~~~~~~~ Duplicating Nodes ~~~~~~~ /** * Duplicates the currently selected nodes of the currently active graph */ public static void duplicate() { duplicate(currentGraphPanel.graph()); } /** * Duplicates the currently selected nodes * @param graph */ public static void duplicate(DescriptionGraph graph) { List<LudemeNode> nodes = selectedNodes(graph); duplicate(graph, nodes); } /** * Duplicates a list of nodes * @param graph * @param nodes */ public static void duplicate(DescriptionGraph graph, List<LudemeNode> nodes) { // remove root node nodes.remove(graph.getRoot()); if(nodes.isEmpty()) return; // get left most node LudemeNode leftMostNode = nodes.get(0); for(LudemeNode node : nodes) if(node.x() < leftMostNode.x()) leftMostNode = node; int y = leftMostNode.y() + leftMostNode.height(); paste(graph, copyTemporarily(nodes), leftMostNode.x(), y); } // ~~~~~~~ Collapsing and Expanding Nodes ~~~~~~~ /** * Collapses the currently selected nodes of the currently active graph */ public static void collapse() { collapse(currentGraphPanel.graph()); } /** * Collapses the currently selected nodes of a given graph * @param graph */ public static void collapse(DescriptionGraph graph) { List<LudemeNode> selectedNodes = selectedNodes(graph); if(selectedNodes.isEmpty()) return; if(selectedNodes.size() == 1) { if(selectedNodes.get(0).parentNode() != null) { collapseNode(graph, selectedNodes.get(0), true); } return; } List<LudemeNode> roots = new ArrayList<>(); for(LudemeNode node : selectedNodes) if(node.parentNode() == null) roots.add(node); else if(!selectedNodes.contains(node.parentNode())) roots.add(node.parentNode()); // find all subtree root's children List<LudemeNode> toCollapse = new ArrayList<>(); for(LudemeNode node : selectedNodes) if(roots.contains(node.parentNode())) toCollapse.add(node); for(LudemeNode node : toCollapse) collapseNode(graph, node, true); graphPanelMap.get(graph).deselectEverything(); } /** * (Un-)Collapses a node * @param graph The graph that contains the node. * @param node The node to update. * @param collapse Whether the node should be collapsed or not. */ public static void collapseNode(DescriptionGraph graph, LudemeNode node, boolean collapse) { if(DEBUG) System.out.println("[HANDLER] collapse(graph, node) Collapsing " + node.title() + ": " + collapse); node.setCollapsed(collapse); IGraphPanel graphPanel = graphPanelMap.get(graph); addAction(new CollapsedAction(graphPanel, node, collapse)); graphPanel.notifyCollapsed(graphPanel.nodeComponent(node), collapse); } /** * Expands the currently selected nodes */ public static void expand() { expand(currentGraphPanel.graph()); } /* * Expands the currently selected nodes of a given graph */ public static void expand(DescriptionGraph graph) { List<LudemeNode> selectedNodes = selectedNodes(graph); // find all subtree root List<LudemeNode> toExpand = new ArrayList<>(); for(LudemeNode node : selectedNodes) toExpand.addAll(node.childrenNodes()); for (LudemeNode node : toExpand) collapseNode(graph, node, false); graphPanelMap.get(graph).deselectEverything(); } // ~~~~~~~ Undo and Redo ~~~~~~~ /** * Undoes the last action */ public static void undo() { if(currentPerformedUserActions.isEmpty()) return; currentUndoAction = currentPerformedUserActions.pop(); if(DEBUG) System.out.println("[HANDLER] undo() Undoing " + currentUndoAction.actionType()); currentUndoneUserActions.add(currentUndoAction); Handler.recordUserActions = false; currentUndoAction.undo(); currentUndoAction.graphPanel().repaint(); Handler.recordUserActions = true; if(DEBUG) System.out.println("[HANDLER] undo() Completed " + currentUndoAction.actionType()); toolsPanel.updateUndoRedoBtns(currentPerformedUserActions, currentUndoneUserActions); if(liveCompile) compile(); currentUndoAction = null; } /** * Redoes the last undone action */ public static void redo() { if(currentUndoneUserActions.isEmpty()) return; currentRedoAction = currentUndoneUserActions.pop(); if(DEBUG) System.out.println("[HANDLER] redo() Redoing " + currentRedoAction.actionType()); currentPerformedUserActions.add(currentRedoAction); Handler.recordUserActions = false; currentRedoAction.redo(); currentRedoAction.graphPanel().repaint(); Handler.recordUserActions = true; if(DEBUG) System.out.println("[HANDLER] redo() Completed " + currentRedoAction.actionType()); toolsPanel.updateUndoRedoBtns(currentPerformedUserActions, currentUndoneUserActions); if(liveCompile) compile(); currentRedoAction = null; } /** * Adds an action to the undo stack * @param action */ private static void addAction(IUserAction action) { if(!recordUserActions) return; if(DEBUG) System.out.println("Adding action: " + action.actionType()); currentPerformedUserActions.add(action); currentUndoneUserActions = new Stack<>(); toolsPanel.updateUndoRedoBtns(currentPerformedUserActions, currentUndoneUserActions); } /** * * @param action * @return Whether the last action equals a given user action */ private static boolean lastActionEquals(IUserAction action) { if(currentPerformedUserActions.isEmpty()) return false; return currentPerformedUserActions.peek() == action; } // ~~~~~~~ Appearance ~~~~~~~ /** * Sets the current active design palette */ public static void setPalette(String paletteName) { DesignPalette.loadPalette(paletteName); for(IGraphPanel graphPanel : graphPanelMap.values()) graphPanel.repaint(); } public static List<String> palettes() { return DesignPalette.palettes(); } /** * Sets the background * @param background */ public static void setBackground(IBackground background) { currentBackground = background; for(IGraphPanel graphPanel : graphPanelMap.values()) graphPanel.repaint(); } /** * * @return The current background */ public static IBackground currentBackground() { return currentBackground; } public static void setFont(String size) { switch(size) { case "Small": DesignPalette.makeSizeSmall(); break; case "Medium": DesignPalette.makeSizeMedium(); break; case "Large": DesignPalette.makeSizeLarge(); break; } for(IGraphPanel graphPanel : graphPanelMap.values()) graphPanel.repaint(); } // ~~~~~~~ Utility ~~~~~~~ /** * If the graph is complete (all required inputs filled) * @param graph */ public static List<LudemeNode> isComplete(DescriptionGraph graph) { List<LudemeNode> unsatisfiedNodes = new ArrayList<>(); for(LudemeNode ln : graph.getNodes()) if((graph.getRoot() == ln || ln.parentNode()!=null) && !ln.isSatisfied()) unsatisfiedNodes.add(ln); return unsatisfiedNodes; } /** * Whether a node has a path to the root * @param graph * @param node */ public static boolean isConnectedToRoot(DescriptionGraph graph, LudemeNode node) { LudemeNode last = node; while(last.parentNode() != null) last = last.parentNode(); return last == graph.getRoot(); } /** * Updates the position of a node * @param node node in operation * @param x x coordinate * @param y y coordinate */ public static void updatePosition(LudemeNode node, int x, int y) { node.setPos(x, y); } public static Dimension getViewPortSize() { return currentGraphPanel.parentScrollPane().getViewport().getSize(); } public static void reconstruct(IGraphPanel graph, LudemeNode node) { LudemeNodeComponent lnc = graph.nodeComponent(node); for(LInputField lif : lnc.inputArea().currentInputFields) { lif.reconstruct(); } lnc.inputArea().drawInputFields(); } public static void updateInputs(IGraphPanel graph, LudemeNode node) { LudemeNodeComponent lnc = graph.nodeComponent(node); lnc.inputArea().updateProvidedInputs(); } }
61,076
35.225979
240
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/DescriptionGraph.java
package app.display.dialogs.visual_editor.model; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.interfaces.iGNode; import app.display.dialogs.visual_editor.model.interfaces.iGraph; import main.grammar.Description; import main.grammar.Symbol; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Graph of LudemeNode objects * @author Filipp Dokienko */ public class DescriptionGraph implements iGraph { /** The Root node of this graph */ private LudemeNode ROOT; /** All nodes this graph contains keyed by their id */ private final HashMap<Integer, iGNode> nodeMap = new HashMap<>(); /** List of all LudemeNodes this graph contains */ private final List<LudemeNode> allLudemeNodes = new ArrayList<>(); /** List of all Edges this graph contains */ private final List<Edge> edgeList = new ArrayList<>(); private final List<Integer> connectedComponentRoots = new ArrayList<>(); private int selectedRoot = -1; /** Whether this graph is a define */ private boolean isDefine = false; /** The title of the define */ private String title; /** The symbol of the define */ private Symbol defineSymbol; /** The macro node of the define */ private LudemeNode defineMacroNode; /** The parameters of the define */ private List<NodeArgument> defineParameters = new ArrayList<>(); /** * Constructor. Used for non-define graphs without a predefined root node */ public DescriptionGraph() { } /** * Constructor for a define graph. * @param title Initial title of the define * @param isDefine Whether this graph is a define */ public DescriptionGraph(String title, boolean isDefine) { assert isDefine; this.title = title; this.isDefine = true; this.defineSymbol = new Symbol(Symbol.LudemeType.Ludeme, title, title, null); } /** * Constructor for a non-define graph with a predefined root node * @param root The root node */ public DescriptionGraph(LudemeNode root) { this.ROOT = root; } public Description description() { return new Description(ROOT.toLud()); } @Override public List<Edge> getEdgeList() { return edgeList; } @Override public HashMap<Integer, iGNode> getNodeList() { return nodeMap; } @Override public LudemeNode getNode(int id) { return (LudemeNode) nodeMap.get(Integer.valueOf(id)); } public List<LudemeNode> getNodes() { return allLudemeNodes; } @Override public int addNode(iGNode ludemeNode) { this.allLudemeNodes.add((LudemeNode) ludemeNode); int id = ludemeNode.id(); nodeMap.put(Integer.valueOf(id), ludemeNode); addConnectedComponentRoot(id); return id; } @Override public void removeNode(iGNode node) { this.allLudemeNodes.remove(node); nodeMap.remove(Integer.valueOf(node.id())); removeConnectedComponentRoot(node.id()); node.id(); } @Override public void addEdge(int from, int to) { Edge e = new Edge(from, to); for(Edge edge : edgeList) if(edge.equals(e)) return; edgeList.add(new Edge(from , to)); removeConnectedComponentRoot(to); } @Override public void removeEdge(int from, int to) { for(Edge e : edgeList) if(e.getNodeA() == from && e.getNodeB() == to) { edgeList.remove(e); addConnectedComponentRoot(to); return; } } @Override public List<Integer> connectedComponentRoots() { return connectedComponentRoots; } @Override public void addConnectedComponentRoot(int root) { if (!connectedComponentRoots.contains(Integer.valueOf(root)) && getNode(root) != null) connectedComponentRoots.add(Integer.valueOf(root)); } @Override public void removeConnectedComponentRoot(int root) { if (connectedComponentRoots.contains(Integer.valueOf(root))) connectedComponentRoots.remove(Integer.valueOf(root)); } @Override public int selectedRoot() { return selectedRoot; } @Override public void setSelectedRoot(int root) { this.selectedRoot = root; } @Override public void setRoot(iGNode root) { this.ROOT = (LudemeNode) root; } @Override public iGNode getRoot() { return ROOT; } public LudemeNode rootLudemeNode() { return ROOT; } public void remove(LudemeNode ludemeNode) { this.allLudemeNodes.remove(ludemeNode); } /** * Converts the graph to a .lud String * @return The .lud equivalent of the graph */ public String toLud() { if(!isDefine) return ROOT.toLud(); else return defineLud(); } // Methods for define graphs /** * Converts a define graph to a .lud String. * Replaces unprovided, but required arguments, indicated by " <PARAMETER> " with #[count] * @return The .lud equivalent of the define graph */ private String defineLud() { String lud = ((LudemeNode) getRoot()).toLud(true); int count = 1; while(lud.contains("<PARAMETER>")) { lud = lud.replaceFirst("<PARAMETER>","#"+count); count++; } return lud; } /** * * @return Whether this is a define graph */ public boolean isDefine() { return isDefine; } /** * * @return The title of the define */ public String title() { return title; } /** * Changes the title of the define * @param title The new title */ public void setTitle(String title) { if(!title.equals(this.title)) { this.title = title; // update the symbol this.defineSymbol = new Symbol(Symbol.LudemeType.Ludeme, title, title, null); // notify handler Handler.updateDefineNodes(this, defineSymbol); } } /** * * @return The symbol of the define */ public Symbol defineSymbol() { return defineSymbol; } /** * * @return The macro node (root of the define (excluding the define node itself)) of the define */ public LudemeNode defineMacroNode() { return defineMacroNode; } /** * * @return The current macro node of the define */ public LudemeNode computeDefineMacroNode() { return (LudemeNode) rootLudemeNode().providedInputsMap().get(rootLudemeNode().currentNodeArguments().get(1)); } /** * Updates the field of the define macro node */ public void updateMacroNode() { // if the macro node has changed, update it and notify about change if(defineMacroNode != computeDefineMacroNode()) { defineMacroNode = computeDefineMacroNode(); updateParameters(computeDefineParameters()); Handler.updateDefineNodes(this, defineMacroNode); } } public List<NodeArgument> parameters() { if(defineParameters == null) defineParameters = computeDefineParameters(); return defineParameters; } /** * Computes the required arguments of the define * @return List of NodeArguments that require an Input */ public List<NodeArgument> computeDefineParameters() { assert isDefine; List<NodeArgument> parameters = new ArrayList<>(); LudemeNode root = (LudemeNode) getRoot(); // The node must be satisfied (means all inputs filled) if(!root.isSatisfied()) return parameters; for(LudemeNode node : allLudemeNodes) if(Handler.isConnectedToRoot(this, node)) parameters.addAll(node.unfilledRequiredArguments()); return parameters; } /** * Updates the current parameters of the define. * computes which NodeArguments were added/removed from the parameters (of a define node) */ public void updateParameters(List<NodeArgument> parameters) { assert isDefine; this.defineParameters = parameters; Handler.updateDefineNodes(this, parameters); } private NodeArgument titleNodeArgument() { return rootLudemeNode().currentNodeArguments().get(0); } private NodeArgument macroNodeArgument() { return rootLudemeNode().currentNodeArguments().get(1); } public void notifyDefineChanged(NodeArgument nodeArgument, Object input) { // check what changed if(nodeArgument == titleNodeArgument() && !input.equals("")) setTitle((String) input); else if(nodeArgument == macroNodeArgument()) updateMacroNode(); else updateParameters(computeDefineParameters()); } /** * * @return The node of the define, used in other graphs */ public LudemeNode defineNode() { assert isDefine; if(defineMacroNode() == null || parameters() == null) return null; return new LudemeNode(defineSymbol, defineMacroNode(), this, parameters(), rootLudemeNode().x(), rootLudemeNode().y(), true); } }
9,606
24.482759
133
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/Edge.java
package app.display.dialogs.visual_editor.model; /** * Stores information about edge endpoints and its graphics * @author nic0gin */ public class Edge { private final int nodeA; private final int nodeB; public Edge(int nodeA, int nodeB) { this.nodeA = nodeA; this.nodeB = nodeB; } public int getNodeA() { return nodeA; } public int getNodeB() { return nodeB; } public boolean equals(Edge e) { return this.nodeA == e.getNodeA() && this.nodeB == e.getNodeB(); } }
568
15.735294
72
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/GameParser.java
package app.display.dialogs.visual_editor.model; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.recs.display.ProgressBar; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import compiler.Arg; import compiler.ArgClass; import grammar.Grammar; import main.grammar.*; import main.options.UserSelections; import other.GameLoader; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; /** * Class handles parsing of compilable *.lud game description into visual format * @author nic0gin */ public class GameParser { /** * Creates call tree from partial fully expanded game description * @param description valid partial game description (brackets match) * @return call tree with dummy root */ @SuppressWarnings("unused") private static Call createPartialCallTree(String description) { Token tokenTree_test = new Token(description, new Report()); Grammar gm = grammar.Grammar.grammar(); final ArgClass rootClass = (ArgClass) Arg.createFromToken(grammar.Grammar.grammar(), tokenTree_test); assert rootClass != null; rootClass.matchSymbols(gm, new Report()); Class<?> clsRoot = null; try { clsRoot = Class.forName(rootClass.instances().get(0).symbol().path()); } catch (final ClassNotFoundException e) { e.printStackTrace(); } // Create call tree with dummy root Call callTree = new Call(Call.CallType.Null); final Map<String, Boolean> hasCompiled = new HashMap<>(); rootClass.compile(clsRoot, (-1), new Report(), callTree, hasCompiled); return callTree; } public static void ParseFileToGraph(File file, IGraphPanel graphPanel, ProgressBar progressBar) { // #1 file to string StringBuilder sb = descriptionToString(file.getPath()); progressBar.updateProgress(1); // creating a call tree from game description // #2 file to description Description test_desc = new Description(sb.toString()); progressBar.updateProgress(2); // #3 expand and parse the description parser.Parser.expandAndParse(test_desc, new UserSelections(new ArrayList<>()),new Report(),false); progressBar.updateProgress(3); // #4 create token tree Token tokenTree_test = new Token(test_desc.expanded(), new Report()); Grammar gm = grammar.Grammar.grammar(); progressBar.updateProgress(4); // #5 create from token final ArgClass rootClass = (ArgClass) Arg.createFromToken(grammar.Grammar.grammar(), tokenTree_test); assert rootClass != null; progressBar.updateProgress(5); // #6 match symbols progressBar.updateProgress(6); rootClass.matchSymbols(gm, new Report()); // #7 compile a call tree progressBar.updateProgress(7); // Attempt to compile the game Class<?> clsRoot = null; try { clsRoot = Class.forName("game.Game"); } catch (final ClassNotFoundException e) { e.printStackTrace(); } // Create call tree with dummy root Call callTree = new Call(Call.CallType.Null); final Map<String, Boolean> hasCompiled = new HashMap<>(); rootClass.compile(clsRoot, (-1), new Report(), callTree, hasCompiled); // #8 constructing a graph from call tree constructGraph(callTree.args().get(0), 0, null, -1, null, graphPanel.graph()); Handler.gameGraphPanel.updateGraph(); progressBar.updateProgress(8); graphPanel.graph().getNodeList().forEach((k,v) -> { Handler.reconstruct(graphPanel, (LudemeNode) v); Handler.updateInputs(graphPanel, (LudemeNode) v); }); } /** * Prints out all the necessary information to construct ludeme graph * @param c parent call * @param d depth * @param graph graph in operation */ private static Object constructGraph(Call c, int d, LudemeNode parent, int collectionIndex, NodeArgument creatorArgument, DescriptionGraph graph) { List<Call> cArgs = c.args(); int matched = 0; int counter = 0; switch (c.type()) { case Array: // Apply method for the arguments of c // TODO: update collection input Object[] objects = new Object[cArgs.size()]; for (int i = 0; i < cArgs.size(); i++) { objects[i] = constructGraph(cArgs.get(i), d+1, parent, i, creatorArgument, graph); } return objects; case Terminal: return c.object(); case Class: // TODO: debug this! Symbol ludemeSymbol = c.symbol(); List<Clause> rhsList = c.symbol().rule().rhs(); Clause currentClause = null; for (Clause clause : rhsList) { if (clause.args() != null && c.args().size() == clause.args().size()) { List<ClauseArg> iRhs = clause.args(); for (int j = 0; j < cArgs.size(); j++) { Symbol s = cArgs.get(j).symbol(); if (s != null) { if (s.returnType().token().equals( iRhs.get(j).symbol().returnType().token())) { counter++; } } } if (counter > matched || rhsList.size() == 1) { matched = counter; counter = 0; currentClause = clause; } } } // creating ludeme node from call class LudemeNode ln = new LudemeNode(ludemeSymbol, Handler.gameGraphPanel.parentScrollPane().getViewport().getViewRect().x, Handler.gameGraphPanel.parentScrollPane().getViewport().getViewRect().y); ln.setCreatorArgument(creatorArgument); // setting up current clause constructor ln.setSelectedClause(currentClause); // Handler.updateCurrentClause(graph, ln, currentClause); // providing argument to the ludeme node int orGroup = 0; int orGroupFinished = -1; // node argument cursor int i = 0; // clause argument cursor assert currentClause != null; // check for the constructor name extension int j = currentClause.args().get(0).symbol().ludemeType().equals(Symbol.LudemeType.Constant) ? 1 : 0; Object input; // temp storage of ludeme inputs HashMap<NodeArgument, Object> ludemeInputs = new HashMap<>(); while (i < ln.providedInputsMap().size()) { // check if input for orGroup was produced if (currentClause.args().get(j).orGroup() == orGroupFinished) { j++; } else { // adding inputs Call call = cArgs.get(j); input = constructGraph(call, d+1, ln, -1, ln.currentNodeArguments().get(i), graph); // update terminal input if (!(input instanceof LudemeNode || input instanceof Object[])) //Handler.updateInput(graph, ln, ln.currentNodeArguments().get(i), input); ln.setProvidedInput(ln.currentNodeArguments().get(i), input); ludemeInputs.put(ln.currentNodeArguments().get(i), input); if (currentClause.args().get(j).orGroup() > orGroup) { orGroup = currentClause.args().get(j).orGroup(); // check if orGroup is fully iterated if (j - 1 >= 0 && currentClause.args().get(j).orGroup() != currentClause.args().get(j-1).orGroup()) { i++; } // check if one of inputs of orGroup was given already else if (input != null) { i++; orGroupFinished = orGroup; } } else { i++; } j++; } } Handler.addNode(graph, ln); for (int k = 0; k < ludemeInputs.size(); k++) { input = ludemeInputs.get(ln.currentNodeArguments().get(k)); if (input instanceof LudemeNode) { Handler.addEdge(graph, ln, (LudemeNode) input, ((LudemeNode) input).creatorArgument()); } else if (input instanceof Object[]) { for (int l = 0; l < ((Object[]) input).length; l++) { LudemeNode lnInput = (LudemeNode) ((Object[]) input)[l]; Handler.addEdge(graph, ln, lnInput, lnInput.creatorArgument(), l); } } } /* // add edge to graph model if (parent != null) { if (collectionIndex == -1) Handler.addEdge(graph, parent, ln, ln.creatorArgument()); else Handler.addEdge(graph, parent, ln, ln.creatorArgument(), collectionIndex); } */ return ln; case Null: default: return null; } } private static StringBuilder descriptionToString(String gamePath) { final StringBuilder sb = new StringBuilder(); String path = gamePath.replaceAll(Pattern.quote("\\"), "/"); path = path.substring(path.indexOf("/lud/")); InputStream in = GameLoader.class.getResourceAsStream(path); try { assert in != null; try (final BufferedReader rdr = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { String line; while ((line = rdr.readLine()) != null) sb.append(line).append("\n"); } } catch (final IOException e) { e.printStackTrace(); } return sb; } }
11,475
38.986063
149
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/LudemeNode.java
package app.display.dialogs.visual_editor.model; import app.display.dialogs.visual_editor.LayoutManagement.Vector2D; import app.display.dialogs.visual_editor.documentation.DocumentationReader; import app.display.dialogs.visual_editor.documentation.HelpInformation; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.interfaces.iGNode; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Preprocessing; import grammar.Grammar; import main.grammar.Clause; import main.grammar.ClauseArg; import main.grammar.Symbol; import java.util.*; /** * Node representation of a ludeme in the current description * @author Filipp Dokienko */ public class LudemeNode implements iGNode { /** ID of last node */ private static int LAST_ID = 0; /** ID of this node */ private final int ID; /** Symbol/Ludeme this node represents */ private Symbol symbol; /** The Node Argument which created this node */ private NodeArgument NODE_ARGUMENT_CREATOR; /** List of clauses this symbol encompasses */ private List<Clause> clauses; /** Currently selected Clause by the user */ private final LinkedHashMap<Symbol, List<Clause>> SYMBOL_CLAUSE_MAP = new LinkedHashMap<>(); // for each clause the symbols it contains private Clause selectedClause = null; /** Map of NodeArgument and its corresponding input */ private LinkedHashMap<NodeArgument, Object> providedInputsMap; /** Depth in the graph/tree */ private int depth = 0; /** Width and height of the node in its graphical representation */ private int width,height; /** This node's parent */ private LudemeNode parent; /** List of children of this node */ private final List<LudemeNode> children = new ArrayList<>(); /** x and y coordinates of this node in the graph */ private int x,y; /** whether this node (and thus its children) are visible (collapsed) or not. */ private boolean collapsed = false; /** whether this node is visible */ private boolean visible = true; /** whether this node is a root of fixed node group */ private boolean fixed = false; /** HelpInformation */ private final HelpInformation helpInformation; /** Which package this node belongs to. * game, game.equipment, game.functions, game.rules */ private final String PACKAGE_NAME; /** HashMap of NodeArguments keyed by the clause they correspond to */ private final HashMap<Clause, List<NodeArgument>> nodeArguments; /** List of NodeArguments for the current Clause of the associated LudemeNodeComponent */ private List<NodeArgument> currentNodeArguments; /** Whether this node is a 1D Collection-supply for a 2D-Collection */ private boolean is1DCollectionNode = false; private boolean isDefineRoot = false; private DescriptionGraph defineGraph; private boolean isDefineNode = false; private LudemeNode macroNode = null; /** * Constructor for a new LudemeNode * @param symbol Symbol/Ludeme this node represents * @param x x coordinate of this node in the graph * @param y y coordinate of this node in the graph */ public LudemeNode(Symbol symbol, int x, int y) { this(symbol, null, x, y); } /** * Constructor for a new LudemeNode * @param symbol Symbol/Ludeme this node represents * @param argument The Node Argument which created this node * @param x x coordinate of this node in the graph * @param y y coordinate of this node in the graph */ public LudemeNode(Symbol symbol, NodeArgument argument, int x, int y) { this(symbol, argument, null, x, y); } /** * Constructor for a new LudemeNode * @param symbol Symbol/Ludeme this node represents * @param argument The Node Argument which created this node * @param nodeArguments HashMap of NodeArguments keyed by the clause they correspond to (null if not available) * @param x x coordinate of this node in the graph * @param y y coordinate of this node in the graph */ public LudemeNode(Symbol symbol, NodeArgument argument, HashMap<Clause, List<NodeArgument>> nodeArguments, int x, int y) { this.ID = LAST_ID++; this.symbol = symbol; this.NODE_ARGUMENT_CREATOR = argument; if(symbol.rule() == null) this.clauses = new ArrayList<>(); else this.clauses = symbol.rule().rhs(); this.x = x; this.y = y; this.width = 100; // width and height are hard-coded for now, are updated later this.height = 100; // Expand clauses if possible if(clauses != null) { expandClauses(); if(clauses.size() > 0) this.selectedClause = clauses.get(0); } // Create a NodeArgument for each ClauseArg, if not provided as parameter HashMap<Clause, List<NodeArgument>> nodeArguments2 = nodeArguments; if(nodeArguments2 == null) nodeArguments2 = generateNodeArguments(); this.nodeArguments = nodeArguments2; // get the NodeArguments of the currently selected clause currentNodeArguments = nodeArguments2.get(selectedClause()); if(currentNodeArguments == null) currentNodeArguments = new ArrayList<>(); // initialize the provided inputs map providedInputsMap = new LinkedHashMap<>(); for(NodeArgument na : currentNodeArguments) providedInputsMap.put(na, null); // package name this.PACKAGE_NAME = initPackageName(); clauses.sort(Comparator.comparing(Clause::toString)); // Create a map of symbols and their corresponding clauses, used in the pick-a-constructor menu to group clauses by symbols for(Clause c : clauses) if(SYMBOL_CLAUSE_MAP.containsKey(c.symbol())) SYMBOL_CLAUSE_MAP.get(c.symbol()).add(c); else { List<Clause> l = new ArrayList<>(); l.add(c); SYMBOL_CLAUSE_MAP.put(c.symbol(), l); } this.helpInformation = DocumentationReader.instance().help(this.symbol); } /** * Creates a LudemeNode which represents a 1D collection * @param na2DCollection NodeArgument which represents the 2D collection, and this 1D collection is part of * @param x x coordinate of this node in the graph * @param y y coordinate of this node in the graph */ public LudemeNode(NodeArgument na2DCollection, int x, int y) { this.ID = LAST_ID++; this.is1DCollectionNode = true; this.x = x; this.y = y; this.width = 100; // width and height are hard-coded for now, are updated later this.height = 100; NodeArgument na1DCollection = na2DCollection.collection1DEquivalent(na2DCollection.args().get(0)); this.symbol = na1DCollection.arg().symbol(); this.clauses = new ArrayList<>(); List<ClauseArg> clauseArgs = new ArrayList<>(); clauseArgs.add(na1DCollection.arg()); this.clauses.add(new Clause(this.symbol, clauseArgs, false)); // Expand clauses if possible if(clauses != null) { expandClauses(); if(clauses.size() > 0) this.selectedClause = clauses.get(0); } this.NODE_ARGUMENT_CREATOR = na2DCollection; this.nodeArguments = generateNodeArguments(); currentNodeArguments = nodeArguments.get(selectedClause()); // initialize the provided inputs map providedInputsMap = new LinkedHashMap<>(); for(NodeArgument na : currentNodeArguments) providedInputsMap.put(na, null); clauses.sort(Comparator.comparing(Clause::toString)); // package name this.PACKAGE_NAME = initPackageName(); this.helpInformation = DocumentationReader.instance().help(symbol); } /** * Creates a Define-Graph Root LudemeNode * @param x * @param y * @param viableDefineRoots * @param isDefine */ public LudemeNode(int x, int y, List<Symbol> viableDefineRoots, boolean isDefine) { assert isDefine; Symbol s = new Symbol(Symbol.LudemeType.Ludeme, "Define","define",null); List<ClauseArg> args = new ArrayList<>(); args.add(new ClauseArg(Grammar.grammar().symbolsWithPartialKeyword("string").get(0), "Name", null, false, 0, 0)); Clause c = new Clause(s, args, true); System.out.println(); this.ID = LAST_ID++; this.x = x; this.y = y; this.symbol = s; this.clauses = new ArrayList<>(); clauses.add(c); selectedClause = c; helpInformation = null; PACKAGE_NAME = "game"; nodeArguments = new HashMap<>(); List<NodeArgument> nas = new ArrayList<>(); nas.add(new NodeArgument(c, args.get(0))); nas.add(new NodeArgument(s, c, viableDefineRoots)); nodeArguments.put(c, nas); currentNodeArguments = nas; providedInputsMap = new LinkedHashMap<>(); for(NodeArgument na : currentNodeArguments) providedInputsMap.put(na, null); isDefineRoot = true; } public LudemeNode(Symbol symbol, LudemeNode macroNode, DescriptionGraph defineGraph, List<NodeArgument> requiredParameters, int x, int y, boolean isDefine) { assert isDefine; this.ID = LAST_ID++; this.symbol = symbol; this.x = x; this.y = y; this.clauses = new ArrayList<>(); this.defineGraph = defineGraph; Clause c = new Clause(symbol, new ArrayList<>(), true); clauses.add(c); selectedClause = c; this.helpInformation = null; PACKAGE_NAME = "define"; this.nodeArguments = new LinkedHashMap<>(); this.nodeArguments.put(clauses.get(0), requiredParameters); this.currentNodeArguments = requiredParameters; providedInputsMap = new LinkedHashMap<>(); for(NodeArgument na : currentNodeArguments) providedInputsMap.put(na, null); isDefineNode = true; this.macroNode = macroNode; } /** * Updates the symbol of a define node. * Called when the define name was modified. * @param symbol1 */ public void updateDefineNode(Symbol symbol1) { assert isDefineNode(); List<NodeArgument> oldArgs = nodeArguments.get(selectedClause()); this.symbol = symbol1; this.clauses.remove(0); Clause c = new Clause(symbol1, new ArrayList<>(), true); this.clauses.add(c); this.selectedClause = c; nodeArguments.clear(); nodeArguments.put(c, oldArgs); } /** * Updates the required parameters of a define node. * @param parameters */ public void updateDefineNode(List<NodeArgument> parameters) { assert isDefineNode(); this.nodeArguments.put(clauses.get(0), parameters); this.currentNodeArguments = parameters; LinkedHashMap<NodeArgument, Object> newInputMap = new LinkedHashMap<>(); for(NodeArgument na : parameters) newInputMap.put(na, providedInputsMap.get(na)); this.providedInputsMap = newInputMap; for(NodeArgument na : currentNodeArguments) providedInputsMap.put(na, null); } public void updateDefineNode(LudemeNode macroNode1) { this.macroNode = macroNode1; } /** * * @return The package name this symbol/node belongs to */ private String initPackageName() { String packageName = "game"; if(symbol.cls().getPackage() != null) { String[] splitPackage = symbol.cls().getPackage().getName().split("\\."); if(splitPackage.length == 1) packageName = splitPackage[0]; else packageName = splitPackage[0] + "." + splitPackage[1]; } return packageName; } /** * * @return the symbol this node represents */ public Symbol symbol() { return symbol; } /** * * @return The Node Argument which created this node */ public NodeArgument creatorArgument() { return NODE_ARGUMENT_CREATOR; } /** * Called if another NodeArgument is provided with this node * @param argument */ public void setCreatorArgument(NodeArgument argument) { this.NODE_ARGUMENT_CREATOR = argument; } /** * Clauses without a constructor (e.g. <match> in the "game" symbol) are expanded to the clauses of "match" */ private void expandClauses() { List<Clause> newClauses = new ArrayList<>(); for(Clause clause : clauses) if(clause.symbol() != symbol()) newClauses.addAll(expandClauses(clause.symbol())); else newClauses.add(clause); clauses = newClauses; } private List<Clause> expandClauses(Symbol s) { List<Clause> clauses1 = new ArrayList<>(); for(Clause clause : s.rule().rhs()) if(clauses1.contains(clause) || this.clauses().contains(clause)) { // Nothing to do } else if(clause.symbol() == s) clauses1.add(clause); else clauses1.addAll(expandClauses(clause.symbol())); return clauses1; } /** * * @return the list of clauses this symbol encompasses */ public List<Clause> clauses() { return clauses; } /** * Changes the selected clause of this node * @param selectedClause the selected clause to set */ public void setSelectedClause(Clause selectedClause) { this.selectedClause = selectedClause; this.currentNodeArguments = nodeArguments.get(selectedClause()); providedInputsMap = new LinkedHashMap<>(); for(NodeArgument na : currentNodeArguments) providedInputsMap.put(na, null); } /** * * @return the currently selected clause */ public Clause selectedClause() { return selectedClause; } /** * * @return the map of NodeArguments keyed by the input provided by the user */ public LinkedHashMap<NodeArgument, Object> providedInputsMap() { return providedInputsMap; } public void setProvidedInput(NodeArgument arg, Object input) { if(providedInputsMap.containsKey(arg)) providedInputsMap.put(arg, input); } /** * Sets this node to be visible or not * @param visible the visible to set */ public void setVisible(boolean visible) { this.visible = visible; } /** * * @return whether this node is visible in the GUI */ public boolean visible(){ return visible; } /** * Sets this node to be collapsed or not * @param collapsed the collapsed to set */ public void setCollapsed(boolean collapsed) { if(parentNode() == null) { this.collapsed = collapsed; return; } this.visible = !collapsed; if(!collapsed) this.collapsed = false; // the complete subtree of this node becomes invisible if collapsed or visible if not collapsed setSubtreeVisible(!collapsed); if(collapsed) this.collapsed = true; } /** * Sets the visibility of this node's subtree * @param visible the visibility to set */ private void setSubtreeVisible(boolean visible) { List<LudemeNode> currentChildren = new ArrayList<>(children); while(!currentChildren.isEmpty()) for(LudemeNode child : new ArrayList<>(currentChildren)) { currentChildren.remove(child); if(child.parent.collapsed() || (child != this && child.collapsed)) { continue; } child.setVisible(visible); currentChildren.addAll(child.children); } } /** * * @return whether this node is collapsed */ @Override public boolean collapsed(){ return collapsed; } public boolean isSatisfied() { for(NodeArgument na : providedInputsMap.keySet()) if(!na.optional() && providedInputsMap.get(na) == null) return false; else if(!na.optional() && providedInputsMap.get(na) instanceof Object[]) for(Object o : (Object[])providedInputsMap.get(na)) if(o == null) return false; return true; } public List<NodeArgument> unfilledRequiredArguments() { List<NodeArgument> arguments = new ArrayList<>(); for(NodeArgument na : providedInputsMap.keySet()) if(providedInputsMap.get(na) == Handler.PARAMETER_SYMBOL) arguments.add(na); else if(!na.optional() && providedInputsMap.get(na) == null) // ! If optional inputs should be included as parameter, remove "!na.optional() &&" arguments.add(na); else if(providedInputsMap.get(na) != null && (providedInputsMap.get(na).equals("") || providedInputsMap.get(na).equals("<PARAMETER>"))) arguments.add(na); return arguments; } public LinkedHashMap<Symbol, List<Clause>> symbolClauseMap() { return SYMBOL_CLAUSE_MAP; } public boolean is1DCollectionNode() { return is1DCollectionNode; } /** * * @return a HashMap of NodeArguments keyed by the clause they correspond to */ private HashMap<Clause, List<NodeArgument>> generateNodeArguments() { HashMap<Clause, List<NodeArgument>> nodeArguments1 = new HashMap<>(); if(clauses() == null) return nodeArguments1; for (Clause clause : clauses()) nodeArguments1.put(clause, generateNodeArguments(clause)); return nodeArguments1; } /** * Generates a list of lists of NodeArguments for a given Clause * @param clause Clause to generate the list of lists of NodeArguments for * @return List of lists of NodeArguments for the given Clause */ private static List<NodeArgument> generateNodeArguments(Clause clause) { List<NodeArgument> nodeArguments1 = new ArrayList<>(); if(clause.symbol().ludemeType().equals(Symbol.LudemeType.Predefined)) { NodeArgument nodeArgument = new NodeArgument(clause); nodeArguments1.add(nodeArgument); return nodeArguments1; } List<ClauseArg> clauseArgs = clause.args(); for(int i = 0; i < clauseArgs.size(); i++) { ClauseArg clauseArg = clauseArgs.get(i); // Some clauses have Constant clauseArgs followed by the constructor keyword. They should not be included in the InputArea if(nodeArguments1.isEmpty() && clauseArg.symbol().ludemeType().equals(Symbol.LudemeType.Constant)) continue; NodeArgument nodeArgument = new NodeArgument(clause, clauseArg); nodeArguments1.add(nodeArgument); // if the clauseArg is part of a OR-Group, they all are added to the NodeArgument automatically, and hence can be skipped in the next iteration i = i + nodeArgument.originalArgs.size() - 1; } return nodeArguments1; } /** * * @return the List of NodeArguments for the current Clause of the associated LudemeNodeComponent */ public List<NodeArgument> currentNodeArguments() { currentNodeArguments = nodeArguments.get(selectedClause()); if(currentNodeArguments == null) currentNodeArguments = new ArrayList<>(); return currentNodeArguments; } /** * * @return the id of this node */ @Override public int id() { return ID; } /** * * @return the id of this node's parent */ @Override public int parent() { return parent.id(); } /** * * @return the parent node */ public LudemeNode parentNode() { return parent; } /** * * @return the list of children of this node */ @Override public List<Integer> children() { List<Integer> children_ids = new ArrayList<>(); for(LudemeNode c : children) children_ids.add(Integer.valueOf(c.id())); return children_ids; } /** * * @return the position of this node in the graph */ @Override public Vector2D pos() { return new Vector2D(x, y); } /** * Set the position of this node in the graph * @param pos the position to set */ @Override public void setPos(Vector2D pos) { x = (int) Math.round(pos.x()); y = (int) Math.round(pos.y()); } /** * Set the width of this node in the graph * @param width the width to set */ public void setWidth(int width) { this.width = width; } /** * * @return the width of this node in the graph */ @Override public int width() { return width; } /** * Set the height of this node in the graph * @param height the height to set */ public void setHeight(int height) { this.height = height; } /** * * @return the height of this node in the graph */ @Override public int height() { return height; } /** * Set the depth of this node * @param depth the depth to set */ @Override public void setDepth(int depth) { this.depth = depth; } /** * * @return the depth of this node */ @Override public int depth() { return depth; } @Override public boolean fixed() { return fixed; } public void setFixed(boolean fixed) { System.out.println("Fixed: " + fixed); this.fixed = fixed; } /** * Set the position of this node * @param x the x coordinate to set * @param y the y coordinate to set */ public void setPos(int x, int y) { this.x = x; this.y = y; } /** * Sets the parent of this node * @param ludemeNode the parent to set */ public void setParent(LudemeNode ludemeNode) { this.parent = ludemeNode; } /** * Adds a child to this node * @param child the child to add */ public void addChild(LudemeNode child) { // Checks if child nodes was already added if (!this.children.contains(child)) { children.clear(); providedInputsMap.forEach((k,v) -> { if (v instanceof LudemeNode) { children.add((LudemeNode) v); } else if (v instanceof Object[]) { for (Object obj: (Object[]) v) { if (obj instanceof LudemeNode) children.add((LudemeNode) obj); } } }); } } /** * Removes a child from this node * @param children1 the child to remove */ public void removeChildren(LudemeNode children1) { this.children.remove(children1); } /** * * @return List of children of this node */ public List<LudemeNode> childrenNodes() { return children; } public String toLud() { return toLud(false); } public String toLud(boolean isDefinePanel) { if(isDefineNode) return toLudDefineNode(); StringBuilder sb = new StringBuilder(); if(parentNode() != null) sb.append("\n"); int depth1 = 0; LudemeNode n = this; while(n.parentNode() != null) { n = n.parentNode(); depth1++; } for(int i = 0 ; i < depth1; i++) sb.append("\t"); if(is1DCollectionNode()) { // get collection Object[] collection = (Object[]) providedInputsMap().get(providedInputsMap().keySet().iterator().next()); if(collection == null) return "{ } "; sb.append("{"); for (Object in : collection) { if (in == null) continue; if (in instanceof String) sb.append("\"").append(in).append("\""); else if (in instanceof LudemeNode) sb.append(((LudemeNode) in).toLud()); else sb.append(in); sb.append(" "); } sb.append("} "); return sb.toString(); } sb.append("("); sb.append(tokenTitle()); // append all inputs for (NodeArgument arg : providedInputsMap().keySet()) { Object input = providedInputsMap().get(arg); if(input == null) { if(!arg.optional() && isDefinePanel) { if(arg.arg().label() != null) sb.append(" ").append(arg.arg().label()).append(":<PARAMETER>"); else sb.append(" <PARAMETER> "); } continue; } sb.append(" "); if(arg.arg().label() != null) sb.append(arg.arg().label()).append(":"); if(input instanceof LudemeNode) sb.append(((LudemeNode) input).toLud(isDefinePanel)); else if(input instanceof Object[]) { sb.append(collectionToLud((Object[]) input, arg, isDefinePanel)); } else if(input instanceof String) sb.append("\"").append(input).append("\""); else sb.append(input); } if(numberOfMandatoryLudemeInputs() > 1) { for(int i = 0 ; i < depth1; i++) { sb.append("\t"); } sb.append("\n"); } sb.append(")"); return sb.toString(); } public String toLudDefineNode() { String rawLud = defineGraph.toLud(); // fill parameters int currentI = 1; while(rawLud.contains("#"+currentI)) { Object input; if(currentI-1 >= currentNodeArguments.size()) input = null; else input = providedInputsMap().get(currentNodeArguments.get(currentI-1)); String replacement = ""; if(input instanceof LudemeNode) replacement = ((LudemeNode)input).toLud(); else if(input instanceof Object[]) replacement = collectionToLud((Object[])input,currentNodeArguments.get(currentI-1), false); else if(input instanceof String) replacement = "\"" + input + "\""; else if(input!=null) replacement = input.toString(); // remove label if any input = null int indexOfCross = rawLud.indexOf("#"); if(input == null & rawLud.charAt(indexOfCross-1) == ':') { // find last space before : int indexSpace = indexOfCross-2; while(rawLud.charAt(indexSpace) != ' ') indexSpace--; String label = rawLud.substring(indexSpace, indexOfCross-1); rawLud = rawLud.replace(label+":#"+currentI, "#"+currentI); } rawLud = rawLud.replaceFirst("#"+currentI, replacement); currentI++; } // cut define fragments rawLud = rawLud.substring(1, rawLud.length()-1); rawLud = rawLud.substring(rawLud.indexOf("(")); rawLud = rawLud.replaceAll("\\s+"," "); return rawLud; } public static String collectionToLud(Object[] collection, NodeArgument arg, boolean isDefinePanel) { if(collection.length == 0 && arg.optional()) return ""; StringBuilder sb = new StringBuilder(); sb.append("{ "); for(Object obj : collection) { if(obj == null) continue; if(obj instanceof LudemeNode) sb.append(((LudemeNode)obj).toLud(isDefinePanel)).append(" "); else if(obj instanceof String) sb.append("\"").append(obj).append("\""); else sb.append(obj).append(" "); } sb.append("}"); return sb.toString(); } public String toLudCodeCompletion(List<NodeArgument> argsOfInputField) { LudemeNode root = this; while(root.parentNode() != null) root = root.parentNode(); String rootLud = root.toLud(); String thisLud = toLud(); // compute code completion lud for this node StringBuilder sb = new StringBuilder(); sb.append("("); sb.append(tokenTitle()); // append all inputs for (NodeArgument arg : providedInputsMap().keySet()) { Object input = providedInputsMap().get(arg); if(argsOfInputField.contains(arg)) { if(input instanceof Object[]) { if(arg.arg().label() != null) sb.append(arg.arg().label()).append(":"); sb.append("{ "); for(Object obj : (Object[]) input) { if(obj == null) continue; if(obj instanceof LudemeNode) sb.append(((LudemeNode)obj).toLud()); else sb.append(obj).append(" "); } } sb.append(" ").append(Preprocessing.COMPLETION_WILDCARD); // replace thisLud with sb return rootLud.replace(thisLud, sb.toString()); } if(input == null) continue; sb.append(" "); if(arg.arg().label() != null) sb.append(arg.arg().label()).append(":"); if(input instanceof LudemeNode) sb.append(((LudemeNode) input).toLud()); else if(input instanceof Object[]) { sb.append("{ "); for(Object obj : (Object[]) input) { if(obj == null) continue; if(obj instanceof LudemeNode) sb.append(((LudemeNode)obj).toLud()); else sb.append(obj).append(" "); } sb.append("}"); } else if(input instanceof String) sb.append("\"").append(input).append("\""); else sb.append(input); } sb.append(")"); return rootLud.replace(thisLud, sb.toString()); } private int numberOfMandatoryLudemeInputs() { int n = 0; for(NodeArgument arg : providedInputsMap().keySet()) { if(!arg.optional() && !arg.isTerminal()) n++; } return n; } /** * The title consists of the symbol and any Constants followed by the constructor * @return The title of this node */ public String title() { if(selectedClause == null) return symbol().name(); if(selectedClause.args() != null && selectedClause.args().isEmpty()) return selectedClause.symbol().name(); StringBuilder title = new StringBuilder(selectedClause().symbol().name()); if(selectedClause().args() == null) return title.toString(); // if selected clause starts with constants, add these to the title int index = 0; while(selectedClause().args().get(index).symbol().ludemeType().equals(Symbol.LudemeType.Constant)) { title.append(" ").append(selectedClause().args().get(index).symbol().name()); index++; } return title.toString(); } private String tokenTitle() { if(selectedClause == null) return symbol().token(); StringBuilder title = new StringBuilder(selectedClause().symbol().token()); if(selectedClause().args() == null) return title.toString(); if(selectedClause.args().size() == 0) return title.toString(); // if selected clause starts with constants, add these to the title int index = 0; while(selectedClause().args().get(index).symbol().ludemeType().equals(Symbol.LudemeType.Constant)) { title.append(" ").append(selectedClause().args().get(index).symbol().name()); index++; } return title.toString(); } /** * Copies a node * @return a copy of the node */ public LudemeNode copy() { return copy(0, 0); } /** * Copies a node * @param x_shift The x-shift of the new copied node * @param y_shift The y-shift of the new copied node * @return a copy of the node */ public LudemeNode copy(int x_shift, int y_shift) { LudemeNode copy = new LudemeNode(symbol(), creatorArgument(),nodeArguments,x+x_shift, y+y_shift); copy.setCollapsed(collapsed()); copy.setVisible(visible()); copy.setSelectedClause(selectedClause()); copy.setHeight(height()); for(NodeArgument na : providedInputsMap.keySet()) { Object input = providedInputsMap.get(na); if(input == null || input instanceof LudemeNode) continue; // if no input provided or it is LudemeNode, skip it boolean isLudemeCollection = false; if(input instanceof Object[]) for (Object o : (Object[]) input) if (o instanceof LudemeNode) { isLudemeCollection = true; break; } if(!isLudemeCollection) copy.setProvidedInput(na, input); } return copy; } /** * * @return The package name of the symbol */ public String packageName() { return PACKAGE_NAME; } /** * * @return The HelpInformation */ public HelpInformation helpInformation() { return helpInformation; } public String description() { if(helpInformation == null) return ""; if(selectedClause == null) return ""; if(selectedClause.symbol() == symbol()) return helpInformation.description(); else return DocumentationReader.instance().documentation().get(selectedClause.symbol()).description(); } public String remark() { if(helpInformation == null) return ""; if(selectedClause == null) return ""; if(selectedClause.symbol() == symbol()) return helpInformation.remark(); else return DocumentationReader.instance().documentation().get(selectedClause.symbol()).remark(); } public int x() { return x; } public int y() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public DescriptionGraph defineGraph() { assert isDefineNode() || isDefineRoot(); return defineGraph; } public boolean isDefineRoot() { return isDefineRoot; } public boolean isDefineNode() { return isDefineNode; } public LudemeNode macroNode() { return macroNode; } @Override public String toString(){ return toLud(); } // // UNUSED DYNAMIC-CONSTRUCTOR VARIABLES & METHODS // /* // whether this node is dynamic or not. // a dynamic node has no pre-selected clause. by providing any arguments to the node, the list of // possible clauses is narrowed down to the ones that match the provided arguments. // private boolean dynamic = false; // Clauses that satisfy currently provided inputs private List<Clause> activeClauses = new ArrayList<>(); // Clauses that do not satisfy currently provided inputs private List<Clause> inactiveClauses = new ArrayList<>(); // NodeArguments that are currently provided private List<NodeArgument> providedNodeArguments = new ArrayList<>(); // NodeArguments that can be provided to satisfy active clauses private List<NodeArgument> activeNodeArguments = new ArrayList<>(); // NodeArguments that cannot be provided to satisfy active clauses private List<NodeArgument> inactiveNodeArguments = new ArrayList<>(); //@return whether this node is dynamic public boolean dynamic() { return dynamic; } // @return The list of active clauses public List<Clause> activeClauses() { return activeClauses; } // @return The list of inactive clauses public List<Clause> inactiveClauses() { return inactiveClauses; } // @return The list of active Node Arguments public List<NodeArgument> activeNodeArguments() { return activeNodeArguments; } // @return The list of inactive Node Arguments public List<NodeArgument> inactiveNodeArguments() { return inactiveNodeArguments; } // @return The list of provided node arguments public List<NodeArgument> providedNodeArguments() { return providedNodeArguments; } //Sets this node to be dynamic or not //@param dynamic the dynamic to set public void setDynamic(boolean dynamic) { if(dynamic && !dynamicPossible()) { this.dynamic=false; return; } this.dynamic = dynamic; if(dynamic) { // set current clause to biggest for(Clause c : CLAUSES) { if(c.args() == null) continue; if(c.args().size() > selectedClause.args().size()) { selectedClause = c; //providedInputs = new Object[selectedClause.args().size()]; } } } } IN CONSTRUCTOR: if(dynamic()) { activeClauses = new ArrayList<>(clauses()); inactiveClauses = new ArrayList<>(); providedNodeArguments = new ArrayList<>(); activeNodeArguments = new ArrayList<>(); for(List<NodeArgument> nas: nodeArguments.values()) activeNodeArguments.addAll(nas); inactiveNodeArguments = new ArrayList<>(); currentNodeArguments = activeNodeArguments; } //@return whether it is possible to make this node dynamic public boolean dynamicPossible() { if(CLAUSES.size() == 1) return false; for(Clause clause : CLAUSES){ if(clause.args() == null) continue; if(clause.args().size() > 1) return true; } return false; } */ }
39,881
29.259484
159
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/NodeArgument.java
package app.display.dialogs.visual_editor.model; import app.display.dialogs.visual_editor.documentation.DocumentationReader; import app.display.dialogs.visual_editor.documentation.HelpInformation; import grammar.Grammar; import main.grammar.Clause; import main.grammar.ClauseArg; import main.grammar.Symbol; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * Represents the required Argument (ClauseArg) of a "row" in the node * If ClauseArg is part of a OR-Group, then this is a list, otherwise it just contains the ClauseArg. * LInputField is used to graphically represent NodeArgument * @author Filipp Dokienko */ public class NodeArgument { /** The clause this NodeArgument is part of */ private final Clause CLAUSE; /** The list of ClauseArgs this NodeArgument encompasses */ private final List<ClauseArg> args; /** Arguments prior to expanding */ public final List<ClauseArg> originalArgs = new ArrayList<>(); /** The index of the ClauseArg in the Clause */ private final int INDEX; /** List of possible Arguments as Input */ private final List<PossibleArgument> possibleArguments; /** The list of Symbols that may be provided as input for this NodeArgument * Structural Symbols are not included in this list, but rather expanded to their rules. */ private final List<Symbol> possibleSymbolInputs; private String parameterDescription = null; /** * Constructor for NodeInput * @param clause the clause this NodeArgument is part of * @param arg the ClauseArg this NodeArgument represents */ public NodeArgument(Clause clause, ClauseArg arg) { this.CLAUSE = clause; this.INDEX = clause.args().indexOf(arg); // add argument to list this.args = new ArrayList<>(); this.args.add(arg); // if arg is part of OR-Group, add other components of OR-Group to it. if(arg.orGroup() != 0) { int group = arg.orGroup(); int index = clause.args().indexOf(arg)+1; while(index < clause.args().size() && clause.args().get(index).orGroup() == group) { this.args.add(clause.args().get(index)); index++; } } for(ClauseArg c : new ArrayList<>(this.args)) if(c.symbol().returnType() != c.symbol()) for(String[] f : Grammar.grammar().getFunctions()) if(f[0].equals(c.symbol().name())) { // find the symbol that matches f[1] List<Symbol> candidates = new ArrayList<>(); if(Grammar.grammar().symbolsWithPartialKeyword(f[1]) != null) candidates.addAll(Grammar.grammar().symbolsWithPartialKeyword(f[1])); if(Grammar.grammar().symbolsWithPartialKeyword(f[1].substring(0, f[1].length()-1)) != null) candidates.addAll(Grammar.grammar().symbolsWithPartialKeyword(f[1].substring(0, f[1].length()-1))); Symbol match = null; for(Symbol s : candidates) if(s.grammarLabel().equals(f[1]) && s.rule().rhs().size() > 0) { match = s; break; } if(match == null) match = c.symbol().returnType(); int nesting = c.nesting(); ClauseArg newArg = new ClauseArg(match, c.actualParameterName(), c.label(), c.optional(), c.orGroup(), c.andGroup()); newArg.setNesting(nesting); args.remove(c); args.add(newArg); break; } originalArgs.addAll(this.args); // if contains a choice between a 1d collection or not, keep the 1d collection and remove the other if(this.args.size() == 2) if(args.get(0).symbol().equals(args.get(1).symbol())) { if(args.get(0).nesting() == 0 && args.get(1).nesting() == 1) this.args.remove(0); else if(args.get(0).nesting() == 1 && args.get(1).nesting() == 0) this.args.remove(1); } else if(this.args.size() == 3) { ClauseArg arg1 = args.get(0); ClauseArg arg2 = args.get(1); ClauseArg arg3 = args.get(2); if(arg1.symbol().equals(arg2.symbol()) && arg1.symbol().equals(arg3.symbol())) { if(arg1.nesting() == 0 && arg2.nesting() == 1 && arg3.nesting() == 2) this.args.remove(arg1); else if(arg1.nesting() == 1 && arg2.nesting() == 2 && arg3.nesting() == 0) this.args.remove(arg3); else if(arg1.nesting() == 2 && arg2.nesting() == 0 && arg3.nesting() == 1) this.args.remove(arg2); } } this.possibleArguments = new ArrayList<>(); for(ClauseArg ca : args) computePossibleArguments(ca); Set<Symbol> possibleArguments1 = new HashSet<>(); for(PossibleArgument pa : this.possibleArguments) possibleArguments1.addAll(expandPossibleArgument(pa)); for(ClauseArg a : args()) if(terminalDropdown(a)) possibleArguments1.add(a.symbol()); Set<Symbol> possibleSymbols = new HashSet<>(); for(Symbol s : possibleArguments1) if(!s.ludemeType().equals(Symbol.LudemeType.Constant)) possibleSymbols.add(s); possibleSymbolInputs = new ArrayList<>(possibleSymbols); parameterDescription = readHelp(); } /** * Constructor for PreDefined Arguments * @param clause the clause this NodeArgument is part of */ public NodeArgument(Clause clause) { CLAUSE = clause; // add argument to list args = new ArrayList<>(); args.add(new ClauseArg(clause.symbol(), null, null, false, 0, 0)); args.get(0).setNesting(clause.args().get(0).nesting()); INDEX = 0; this.possibleArguments = new ArrayList<>(); possibleSymbolInputs = new ArrayList<>(); } /** * Creates a NodeArgument with a given list of possible symbol inputs * Used for Define nodes */ public NodeArgument(Symbol symbol, Clause clause, List<Symbol> viableInputs) { CLAUSE = clause; args = new ArrayList<>(); INDEX = 1; ClauseArg ca = new ClauseArg(symbol, "Macro", null, false, 0, 0); args.add(ca); this.possibleArguments = new ArrayList<>(); for(Symbol s : viableInputs) computePossibleArguments(s); Set<Symbol> possibleArguments1 = new HashSet<>(); for(PossibleArgument pa : this.possibleArguments) possibleArguments1.addAll(expandPossibleArgument(pa)); for(ClauseArg a : args()) if(terminalDropdown(a)) possibleArguments1.add(a.symbol()); Set<Symbol> possibleSymbols = new HashSet<>(); for(Symbol s : possibleArguments1) { if(s.ludemeType().equals(Symbol.LudemeType.Constant)) continue; possibleSymbols.add(s); } this.possibleSymbolInputs = new ArrayList<>(possibleSymbols); } private NodeArgument create1DEquivalent(ClauseArg ca) { ClauseArg ca1d = new ClauseArg(ca.symbol(), ca.actualParameterName(), ca.label(), false, 0, 0); ca1d.setNesting(1); return new NodeArgument(this.CLAUSE, ca1d); } public NodeArgument collection1DEquivalent(ClauseArg arg) { return create1DEquivalent(arg); } private Set<Symbol> expandPossibleArgument(PossibleArgument pa) { Set<Symbol> symbols = new HashSet<>(); if(pa.possibleArguments().size() == 0) symbols.add(pa.clause().symbol()); else for(PossibleArgument p : pa.possibleArguments()) symbols.addAll(expandPossibleArgument(p)); return symbols; } private void computePossibleArguments(ClauseArg arg) { if(arg.symbol() == null) System.out.println(); if(arg.symbol().rule() == null) return; for(Clause c : arg.symbol().rule().rhs()) possibleArguments.add(new PossibleArgument(c)); } private void computePossibleArguments(Symbol s) { if(s.rule() == null) return; for(Clause c : s.rule().rhs()) possibleArguments.add(new PossibleArgument(c)); } /** * * @return list of Symbols that may be provided as input for this NodeArgument */ public List<Symbol> possibleSymbolInputsExpanded() { return possibleSymbolInputs; } private static boolean terminalDropdown(ClauseArg arg) { if(arg.symbol().rule() == null) return false; if(arg.symbol().rule().rhs().size() == 0) return false; for(Clause clause : arg.symbol().rule().rhs()) if(!clause.symbol().ludemeType().equals(Symbol.LudemeType.Constant)) return false; return true; } public boolean isTerminal() { if(arg().symbol().ludemeType().equals(Symbol.LudemeType.Predefined)) return true; else return terminalDropdown(); } public boolean terminalDropdown() { return terminalDropdown(arg()); } public boolean canBePredefined() { Symbol s = arg().symbol(); if(s.rule() == null || s.rule().rhs().size() == 0) return false; for(Clause clause : s.rule().rhs()) { if(clause.args() != null && clause.args().size() > 0) continue; if(clause.args() == null && clause.symbol().ludemeType().equals(Symbol.LudemeType.Primitive)) return true; } return false; } public List<Symbol> constantInputs() { List<Symbol> constantInputs = new ArrayList<>(); for(Clause clause : arg().symbol().rule().rhs()) if(clause.symbol().ludemeType().equals(Symbol.LudemeType.Constant)) constantInputs.add(clause.symbol()); return constantInputs; } /** * * @return The clause of this NodeArgument */ public Clause clause() { return CLAUSE; } /** * @return the list of ClauseArgs this NodeInput encompasses */ public List<ClauseArg> args() { return args; } /** * @return the first ClauseArg this NodeInput encompasses */ public ClauseArg arg() { if(args.size() == 0) return null; return args.get(0); } /** * @return Size of the list of ClauseArgs this NodeInput encompasses */ public int size() { return args.size(); } /** * * @return the index of the ClauseArg in the clause */ public int index() { return INDEX; } /** * * @return whether this NodeArgument is optional */ public boolean optional() { if(arg() == null) return false; return arg().optional(); } /** * * @return whether this NodeArgument is a collection */ public boolean collection() { if(arg() == null) return false; return arg().nesting() > 0; } /** * * @return whether this NodeArgument is a 2D-Collection */ public boolean collection2D() { if(arg() == null) return false; return arg().nesting() == 2; } /** * * @return whether this NodeArgument includes multiple ClauseArgs among which the user can choose */ public boolean choice() { return size() > 1; } public void setActiveChoiceArg(ClauseArg activeArg) { ClauseArg temp = args.get(0); int index = args.indexOf(activeArg); args.set(0, activeArg); args.set(index, temp); parameterDescription = readHelp(); } public String parameterDescription() { return parameterDescription; } private String readHelp() { DocumentationReader dr = DocumentationReader.instance(); HelpInformation hi = dr.documentation().get(CLAUSE.symbol()); if(hi == null || hi.parameter(arg()) == null) return null; return hi.parameter(arg()); } @Override public String toString() { return "[ " + INDEX + ", " + args.stream().map(ClauseArg::toString).collect(Collectors.joining(", ")) + " ]"; } }
12,865
30.846535
215
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/PossibleArgument.java
package app.display.dialogs.visual_editor.model; import main.grammar.Clause; import main.grammar.Symbol; import java.util.ArrayList; import java.util.List; public class PossibleArgument { private final Clause clause; private final List<PossibleArgument> possibleArguments = new ArrayList<>(); public PossibleArgument(Clause clause) { this.clause = clause; computePossibleArguments(); } private void computePossibleArguments() { if(clause.args() != null) return; Symbol symbol = clause.symbol(); if(symbol.rule() == null) return; for(Clause c : symbol.rule().rhs()) { if(c == clause) continue; possibleArguments.add(new PossibleArgument(c)); } } public Clause clause() { return clause; } public List<PossibleArgument> possibleArguments() { return possibleArguments; } @Override public String toString() { return clause.toString(); } }
1,060
17.946429
79
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/ActivateOptionalTerminalAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; /** * Created when an optional terminal inputfield gets activated/deactivated */ public class ActivateOptionalTerminalAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final LudemeNode node; private final NodeArgument argument; private final boolean wasActivated; public ActivateOptionalTerminalAction(IGraphPanel graphPanel, LudemeNode node, NodeArgument argument, boolean wasActivated) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.node = node; this.argument = argument; this.wasActivated = wasActivated; } /** * @return The type of the action */ @Override public ActionType actionType() { return ActionType.ACTIVATE_OPTIONAL_TERMINAL; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } /** * Undoes the action */ @Override public void undo() { graphPanel.notifyTerminalActivated(graphPanel.nodeComponent(node), argument, !wasActivated); } /** * Redoes the action */ @Override public void redo() { graphPanel.notifyTerminalActivated(graphPanel.nodeComponent(node), argument, wasActivated); } }
1,863
26.014493
127
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/AddedCollectionAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; /** * Created when a collection is added to the graph. * @author Filipp Dokienko */ public class AddedCollectionAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final LudemeNode affectedNode; private final NodeArgument nodeArgument; private final int elementIndex; private Object collectionInput; /** * Constructor. * * @param graphPanel * @param affectedNode * @param nodeArgument The argument that is provided by the collection. * @param elementIndex The index of the added element to the collection * @param input The input that was added to the collection (null for non-terminal) */ public AddedCollectionAction(IGraphPanel graphPanel, LudemeNode affectedNode, NodeArgument nodeArgument, int elementIndex, Object input) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.affectedNode = affectedNode; this.nodeArgument = nodeArgument; this.elementIndex = elementIndex; this.collectionInput = input; } public boolean isUpdated(LudemeNode node, NodeArgument nodeArgument1, int elementIndex1) { return node==affectedNode && nodeArgument1==this.nodeArgument && elementIndex1==this.elementIndex; } public void setInput(Object input) { this.collectionInput = input; } /** * @return The type of the action */ @Override public ActionType actionType() { return ActionType.ADDED_COLLECTION; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } /** * Undoes the action */ @Override public void undo() { Handler.removeCollectionElement(graph, affectedNode,nodeArgument, elementIndex); } /** * Redoes the action */ @Override public void redo() { Handler.addCollectionElement(graph, affectedNode, nodeArgument); if(collectionInput != null) { System.out.println("INPUT:: " + collectionInput + ", " + elementIndex); Handler.updateCollectionInput(graph, affectedNode, nodeArgument, collectionInput, elementIndex); } } }
2,880
28.397959
140
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/AddedConnectionAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; /** * Created when a connection between two nodes is established. * @author Filipp Dokienko */ public class AddedConnectionAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final LudemeNode from; private final LudemeNode to; private final NodeArgument nodeArgument; public AddedConnectionAction(IGraphPanel graphPanel, LudemeNode from, LudemeNode to, NodeArgument nodeArgument) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.from = from; this.to = to; this.nodeArgument = nodeArgument; //this.index = index; } /** * @return The type of the action */ @Override public ActionType actionType() { return ActionType.ADDED_INPUT; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } /** * Undoes the action */ @Override public void undo() { //Handler.updateInput(graph, from, index, null); Handler.removeEdge(graph, from, to); Handler.updateInput(graph, from, nodeArgument, null); } /** * Redoes the action */ @Override public void redo() { //Handler.updateInput(graph, from, index, to); Handler.addEdge(graph, from, to, nodeArgument); Handler.updateInput(graph, from, nodeArgument, to); } }
2,050
25.636364
115
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/AddedNodeAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import java.util.Arrays; import java.util.LinkedHashMap; /** * Created when a node is added to the graph. * @author Filipp Dokienko */ public class AddedNodeAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final LudemeNode addedNode; private LudemeNode parent; // remembers the parent of the node private LinkedHashMap<NodeArgument, Object> removedData; // Inputs that were removed when the node was removed private int collectionIndex = -1; // If the node was removed from a collection, this is the index of the node in the collection /** * Constructor. * @param graphPanel The graph panel that was affected by the action. * @param addedNode The node that was added. */ public AddedNodeAction(IGraphPanel graphPanel, LudemeNode addedNode) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.addedNode = addedNode; } public LudemeNode addedNode() { return addedNode; } /** * @return The type of the action */ @Override public ActionType actionType() { return ActionType.ADDED_NODE; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } /** * Undoes the action */ @Override public void undo() { parent = addedNode.parentNode(); removedData = new LinkedHashMap<>(addedNode.providedInputsMap()); for(NodeArgument arg : addedNode.providedInputsMap().keySet()) { if(removedData.get(arg) instanceof Object[]) { Object[] copy = Arrays.copyOf((Object[])removedData.get(arg), ((Object[])removedData.get(arg)).length); removedData.put(arg, null); removedData.put(arg, copy); } } // find the index of the removed node in its parent Handler.removeNode(graph, addedNode); graphPanel().repaint(); } public void setCollectionIndex(int index) { System.out.println("AddedNodeAction.setCollectionIndex: " + index); collectionIndex = index; } /** * Redoes the action */ @Override public void redo() { Handler.addNode(graph, addedNode); for (NodeArgument arg : removedData.keySet()) { Object input = removedData.get(arg); if (input == null) continue; if (input instanceof LudemeNode) Handler.addEdge(graph, addedNode, (LudemeNode) input, arg); else if (input instanceof Object[]) { Object[] collection = (Object[]) input; Handler.updateInput(graph, addedNode, arg, input); for (int i = 0; i < collection.length; i++) { if (!(collection[i] instanceof LudemeNode)) continue; Handler.addEdge(graph, addedNode, (LudemeNode) collection[i], arg, i); } } else Handler.updateInput(graph, addedNode, arg, input); addedNode.setProvidedInput(arg, removedData.get(arg)); } if (parent != null) { if (collectionIndex == -1) Handler.addEdge(graph, parent, addedNode, addedNode.creatorArgument()); else Handler.addEdge(graph, parent, addedNode, addedNode.creatorArgument(), collectionIndex); } graphPanel().repaint(); } @Override public String toString() { return "User Action: " + actionType() + " " + addedNode.toString(); } }
4,234
29.25
131
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/ChangedClauseAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import main.grammar.Clause; import java.util.Arrays; import java.util.LinkedHashMap; /** * Created when the active clause of a node is changed. * @author Filipp Dokienko */ public class ChangedClauseAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final LudemeNode node; private final Clause previousClause; private final Clause currentClause; private final LinkedHashMap<NodeArgument, Object> removedData; // Inputs that were removed when the node was modified /** * Constructor. * @param graphPanel * @param node * @param previousClause * @param currentClause */ public ChangedClauseAction(IGraphPanel graphPanel, LudemeNode node, Clause previousClause, Clause currentClause) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.node = node; this.previousClause = previousClause; this.currentClause = currentClause; // copy previous inputs removedData = new LinkedHashMap<>(node.providedInputsMap()); for(NodeArgument arg : node.providedInputsMap().keySet()) { if(removedData.get(arg) instanceof Object[]) { Object[] copy = Arrays.copyOf((Object[])removedData.get(arg), ((Object[])removedData.get(arg)).length); removedData.put(arg, null); removedData.put(arg, copy); } } } /** * @return The type of the action */ @Override public ActionType actionType() { return ActionType.CHANGED_CLAUSE; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } /** * Undoes the action */ @Override public void undo() { Handler.updateCurrentClause(graph, node, previousClause); // insert old inputs again for(NodeArgument arg : removedData.keySet()) { Object input = removedData.get(arg); if(input == null) continue; if(input instanceof LudemeNode) Handler.addEdge(graph, node, (LudemeNode) input, arg); else if(input instanceof Object[]) { //Handler.updateInput(graph, removedNode, arg, input); for(int i = 0; i < ((Object[]) input).length; i++) { if(!(((Object[]) input)[i] instanceof LudemeNode)) continue; Handler.addEdge(graph, node, (LudemeNode) ((Object[]) input)[i], arg, i); } } else Handler.updateInput(graph, node, arg, input); node.setProvidedInput(arg, removedData.get(arg)); } graphPanel.notifyInputsUpdated(graphPanel.nodeComponent(node)); } /** * Redoes the action */ @Override public void redo() { Handler.updateCurrentClause(graph, node, currentClause); } }
3,600
29.777778
121
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/CollapsedAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; /** * Created when a node is collapsed * @author Filipp Dokienko */ public class CollapsedAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final LudemeNode collapsedNode; private final boolean collapsed; /** * Constructor. * @param graphPanel The graph panel that was affected by the action. * @param collapsedNode The node that was collapsed. */ public CollapsedAction(IGraphPanel graphPanel, LudemeNode collapsedNode, boolean collapsed) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.collapsedNode = collapsedNode; this.collapsed = collapsed; } /** * @return The type of the action */ @Override public ActionType actionType() { return ActionType.COLLAPSED; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } /** * Undoes the action */ @Override public void undo() { Handler.collapseNode(graph, collapsedNode, !collapsed); } /** * Redoes the action */ @Override public void redo() { Handler.collapseNode(graph, collapsedNode, collapsed); } }
1,820
23.945205
95
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/IUserAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; /** * Describes an undoable action that was performed by the user * @author Filipp Dokienko */ public interface IUserAction { /** * Describes the action that was performed */ enum ActionType { ADDED_NODE, // User added a new Ludeme REMOVED_NODE, // User removed a Ludeme CHANGED_CLAUSE, // User changed a clause COLLAPSED, // User collapsed a node ADDED_INPUT, // User added a new input to a node REMOVED_INPUT, // User removed an input from a node ADDED_COLLECTION, // User added a new collection to a node REMOVED_COLLECTION, // User removed a collection from a node ACTIVATE_OPTIONAL_TERMINAL, // User activated an optional terminal PASTED // User pasted one or more nodes } /** * * @return The type of the action */ ActionType actionType(); /** * * @return The graph panel that was affected by the action */ IGraphPanel graphPanel(); /** * * @return The description graph that was affected by the action */ DescriptionGraph graph(); /** * Undoes the action */ void undo(); /** * Redoes the action */ void redo(); }
1,434
23.322034
74
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/PasteAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import java.util.List; /** * Created when the user pastes node(s). */ public class PasteAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final List<LudemeNode> pastedNodes; private RemovedNodesAction removedNodesAction; public PasteAction(IGraphPanel graphPanel, List<LudemeNode> pastedNodes) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.pastedNodes = pastedNodes; } /** * @return The type of the action */ @Override public ActionType actionType() { return ActionType.PASTED; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } /** * Undoes the action */ @Override public void undo() { removedNodesAction = new RemovedNodesAction(graphPanel, pastedNodes); Handler.removeNodes(graph, pastedNodes); } /** * Redoes the action */ @Override public void redo() { removedNodesAction.undo(); } }
1,644
22.5
77
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/RemovedCollectionAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; public class RemovedCollectionAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final LudemeNode affectedNode; private final NodeArgument nodeArgument; private final int elementIndex; private final Object collectionInput; public RemovedCollectionAction(IGraphPanel graphPanel, LudemeNode affectedNode, NodeArgument nodeArgument, int elementIndex, Object input) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.affectedNode = affectedNode; this.nodeArgument = nodeArgument; this.elementIndex = elementIndex; this.collectionInput = input; } /** * @return The type of the action */ @Override public ActionType actionType() { return ActionType.REMOVED_COLLECTION; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } /** * Undoes the action */ @Override public void undo() { Handler.addCollectionElement(graph, affectedNode, nodeArgument); if(collectionInput != null) { System.out.println("INPUT:: " + collectionInput + ", " + elementIndex); if(collectionInput instanceof LudemeNode) Handler.addEdge(graph, affectedNode, (LudemeNode) collectionInput, nodeArgument, elementIndex); Handler.updateCollectionInput(graph, affectedNode, nodeArgument, collectionInput, elementIndex); } } /** * Redoes the action */ @Override public void redo() { Handler.removeCollectionElement(graph, affectedNode,nodeArgument, elementIndex); if(collectionInput != null) { System.out.println("INPUT:: " + collectionInput + ", " + elementIndex); if(collectionInput instanceof LudemeNode) Handler.removeEdge(graph, affectedNode, (LudemeNode) collectionInput, elementIndex);} } }
2,580
31.670886
149
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/RemovedConnectionAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; /** * Created when a connection between two nodes is removed. * @author Filipp Dokienko */ public class RemovedConnectionAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final LudemeNode from; private final LudemeNode to; private final NodeArgument nodeArgument; public RemovedConnectionAction(IGraphPanel graphPanel, LudemeNode from, LudemeNode to, NodeArgument nodeArgument) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.from = from; this.to = to; this.nodeArgument = nodeArgument; //this.index = index; } /** * @return The type of the action */ @Override public ActionType actionType() { return ActionType.REMOVED_INPUT; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } /** * Undoes the action */ @Override public void undo() { Handler.addEdge(graph, from, to, nodeArgument); Handler.updateInput(graph, from, nodeArgument, to); } /** * Redoes the action */ @Override public void redo() { Handler.removeEdge(graph, from, to); Handler.updateInput(graph, from, nodeArgument, null); } }
1,940
24.88
117
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/RemovedNodeAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LudemeNodeComponent; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; /** * Created when a node is removed from the graph. * @author Filipp Dokienko */ public class RemovedNodeAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final LudemeNode removedNode; private final LudemeNode parent; // remembers the parent of the node private final LinkedHashMap<NodeArgument, Object> removedData; // Inputs that were removed when the node was removed private int collectionIndex = -1; // If the node was removed from a collection, this is the index of the node in the collection /** * Constructor. * @param graphPanel The graph panel that was affected by the action. * @param removedNode The node that was added. */ public RemovedNodeAction(IGraphPanel graphPanel, LudemeNode removedNode) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.removedNode = removedNode; parent = removedNode.parentNode(); removedData = new LinkedHashMap<>(removedNode.providedInputsMap()); for(NodeArgument arg : removedNode.providedInputsMap().keySet()) { if(removedData.get(arg) instanceof Object[]) { Object[] copy = Arrays.copyOf((Object[])removedData.get(arg), ((Object[])removedData.get(arg)).length); removedData.put(arg, null); removedData.put(arg, copy); } } // find collection index if(parent==null) return; LinkedHashMap<NodeArgument, Object> parentInputs = parent.providedInputsMap(); if(parentInputs.containsValue(removedNode)) { collectionIndex = -1; } else { for(NodeArgument arg : parentInputs.keySet()) { if(parentInputs.get(arg) instanceof Object[]) { Object[] collection = (Object[])parentInputs.get(arg); for(int i = 0; i < collection.length; i++) { if(collection[i] == removedNode) { collectionIndex = i; break; } } } } } } public void setCollectionIndex(int index) { System.out.println("RemovedNodeAction.setCollectionIndex: " + index); collectionIndex = index; } /** * @return The type of the action */ @Override public IUserAction.ActionType actionType() { return ActionType.REMOVED_NODE; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } /** * Undoes the action */ @Override public void undo() { Handler.addNode(graph, removedNode); for (NodeArgument arg : removedData.keySet()) { Object input = removedData.get(arg); if (input == null) { continue; } if (input instanceof LudemeNode) { Handler.addEdge(graph, removedNode, (LudemeNode) input, arg); } else if (input instanceof Object[]) { Object[] collection = (Object[]) input; Handler.updateInput(graph, removedNode, arg, input); for(int i = 0; i < collection.length-1; i++) { Handler.addCollectionElement(graph, removedNode, arg); } for (int i = 0; i < collection.length; i++) { if (!(collection[i] instanceof LudemeNode)) { continue; } Handler.addEdge(graph, removedNode, (LudemeNode) collection[i], arg, i); } } else { Handler.updateInput(graph, removedNode, arg, input); } removedNode.setProvidedInput(arg, removedData.get(arg)); } if(parent != null) { if(collectionIndex == -1) Handler.addEdge(graph, parent, removedNode, removedNode.creatorArgument()); else Handler.addEdge(graph, parent, removedNode, removedNode.creatorArgument(), collectionIndex); } graphPanel().repaint(); List<LudemeNodeComponent> lncs = new ArrayList<>(); lncs.add(graphPanel.nodeComponent(removedNode)); graphPanel.updateCollapsed(lncs); } /** * Redoes the action */ @Override public void redo() { Handler.removeNode(graph, removedNode); graphPanel().repaint(); } @Override public String toString() { return "User Action: " + actionType() + " " + removedNode.toString(); } }
5,774
29.882353
131
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/UserActions/RemovedNodesAction.java
package app.display.dialogs.visual_editor.model.UserActions; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.DescriptionGraph; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LudemeNodeComponent; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import java.util.*; public class RemovedNodesAction implements IUserAction { private final IGraphPanel graphPanel; private final DescriptionGraph graph; private final List<LudemeNode> removedNodes; private final List<LudemeNode> removedNodesSorted; private final HashMap<LudemeNode, LinkedHashMap<NodeArgument, Object>> copiedInputs = new HashMap<>(); private final HashMap<LudemeNode, LinkedHashMap<NodeArgument, Integer>> copiedNodeInputIds = new HashMap<>(); private final HashMap<LudemeNode, LinkedHashMap<NodeArgument, Object[]>> copiedCollectionNodeIds = new HashMap<>(); private final HashMap<Integer, LudemeNode> nodeId = new HashMap<>(); public RemovedNodesAction(IGraphPanel graphPanel, List<LudemeNode> removedNodes) { this.graphPanel = graphPanel; this.graph = graphPanel.graph(); this.removedNodes = new ArrayList<>(removedNodes); this.removedNodesSorted = new ArrayList<>(removedNodes); // sort removed nodes such that their depth descends removedNodesSorted.sort((n1, n2) -> n2.depth() - n1.depth()); for(LudemeNode node : removedNodesSorted) { copiedInputs.put(node, copyInputs(node)); copiedNodeInputIds.put(node, copyIds(node)); copiedCollectionNodeIds.put(node, copyCollectionIds(node)); } } private static LinkedHashMap<NodeArgument, Object> copyInputs(LudemeNode node) { LinkedHashMap<NodeArgument, Object> copiedInputs1 = new LinkedHashMap<>(node.providedInputsMap()); for(NodeArgument arg : node.providedInputsMap().keySet()) { if(copiedInputs1.get(arg) instanceof Object[]) { Object[] copy = Arrays.copyOf((Object[])copiedInputs1.get(arg), ((Object[])copiedInputs1.get(arg)).length); copiedInputs1.put(arg, copy); } } return copiedInputs1; } private LinkedHashMap<NodeArgument, Integer> copyIds(LudemeNode node) { LinkedHashMap<NodeArgument, Integer> copiedIds = new LinkedHashMap<>(); LinkedHashMap<NodeArgument, Object> inputs = copiedInputs.get(node); for(NodeArgument arg : inputs.keySet()) { if(inputs.get(arg) instanceof LudemeNode) { LudemeNode inputNode = (LudemeNode)inputs.get(arg); copiedIds.put(arg, Integer.valueOf(inputNode.id())); nodeId.put(Integer.valueOf(inputNode.id()), inputNode); } } return copiedIds; } private LinkedHashMap<NodeArgument, Object[]> copyCollectionIds(LudemeNode node) { LinkedHashMap<NodeArgument, Object[]> copiedIds = new LinkedHashMap<>(); LinkedHashMap<NodeArgument, Object> inputs = copiedInputs.get(node); for(NodeArgument arg : inputs.keySet()) { if(inputs.get(arg) instanceof Object[]) { Object[] copy = Arrays.copyOf((Object[])inputs.get(arg), ((Object[])inputs.get(arg)).length); for(int i = 0; i < copy.length; i++) { if(copy[i] instanceof LudemeNode) { LudemeNode inputNode = (LudemeNode)copy[i]; copy[i] = Integer.valueOf(inputNode.id()); nodeId.put(Integer.valueOf(inputNode.id()), inputNode); } } copiedIds.put(arg, copy); } } return copiedIds; } /** * @return The type of the action */ @Override public ActionType actionType() { return ActionType.REMOVED_NODE; } /** * @return The graph panel that was affected by the action */ @Override public IGraphPanel graphPanel() { return graphPanel; } /** * @return The description graph that was affected by the action */ @Override public DescriptionGraph graph() { return graph; } private void addAllNodes(List<LudemeNode> nodes) { for(LudemeNode node : nodes) Handler.addNode(graph, node); } private void assignParent(LudemeNode node) { if(node.parentNode() != null) return; for(LudemeNode n : removedNodesSorted) { LinkedHashMap<NodeArgument, Integer> ids = copiedNodeInputIds.get(n); if(ids.containsValue(Integer.valueOf(node.id()))) { node.setParent(n); Handler.addEdge(graph, n, node, node.creatorArgument()); return; } } for(LudemeNode ln : copiedCollectionNodeIds.keySet()) { LinkedHashMap<NodeArgument, Object[]> ids = copiedCollectionNodeIds.get(ln); for(NodeArgument arg : ids.keySet()) { if(Arrays.asList(ids.get(arg)).contains(Integer.valueOf(node.id()))) { node.setParent(ln); return; } } } } private void assignInputs(LudemeNode node) { LinkedHashMap<NodeArgument, Object> inputs = copiedInputs.get(node); for(NodeArgument arg : inputs.keySet()) { Object input = inputs.get(arg); if(input == null || input instanceof LudemeNode) { continue; } else if(input instanceof Object[]) { //Handler.updateInput(graph, removedNode, arg, input); for(int i = 1; i < ((Object[])input).length; i++) { Handler.addCollectionElement(graph, node, arg); } boolean isLudemeCollection = false; for(Object o : (Object[])input) { if(o instanceof LudemeNode) { isLudemeCollection = true; break; } } LinkedHashMap<NodeArgument, Object[]> collectionIds = copiedCollectionNodeIds.get(node); Object[] cid = collectionIds.get(arg); for(int i = 0; i < cid.length; i++) { if(isLudemeCollection) { if(cid[i] == null) { continue; } Handler.updateCollectionInput(graph, node, arg, nodeId.get(cid[i]), i); Handler.addEdge(graph, node, nodeId.get(cid[i]), arg, i); } else { Handler.updateCollectionInput(graph, node, arg, ((Object[]) input)[i], i); } } } else Handler.updateInput(graph, node, arg, input); node.setProvidedInput(arg, inputs.get(arg)); } } @Override public void undo() { addAllNodes(removedNodesSorted); for(LudemeNode n : removedNodesSorted) assignParent(n); for(LudemeNode n : removedNodesSorted) assignInputs(n); // add last edges to non-removed components //if(removedNodes.get(0).parentNode() != null) Handler.addEdge(graph, removedNodes.get(0).parentNode(),removedNodes.get(0), removedNodes.get(0).creatorArgument()); for(LudemeNode n : removedNodesSorted) if(n.parentNode() != null && !removedNodesSorted.contains(n.parentNode())) Handler.addEdge(graph, n.parentNode(),n, n.creatorArgument()); List<LudemeNodeComponent> lncs = new ArrayList<>(); for(LudemeNode n : removedNodesSorted) lncs.add(graphPanel.nodeComponent(n)); graphPanel.updateCollapsed(lncs); } /** * Redoes the action */ @Override public void redo() { Handler.removeNodes(graph, removedNodes); } }
8,513
35.384615
171
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/interfaces/iGNode.java
package app.display.dialogs.visual_editor.model.interfaces; import app.display.dialogs.visual_editor.LayoutManagement.Vector2D; import java.util.List; /** * An interface of a node used for layout graph * @author nic0gin */ public interface iGNode { /** * Returns node id * @return node id */ int id(); /** * Returns id of a parent node * @return id of a parent node */ int parent(); /** * Returns list of children id's order by connection components * @return list of children id's */ List<Integer> children(); /** * Returns position of a node * @return position vector of a node */ Vector2D pos(); /** * Set position vector of a node * @param pos position vector */ void setPos(Vector2D pos); /** * Get width of a node box * @return width */ int width(); /** * Get height of a node box * @return height */ int height(); /** * Set depth of a node * @param depth depth */ void setDepth(int depth); /** * Get depth of a node * @return depth */ int depth(); /** * Get boolean flag to check if node is fixed * @return boolean flag */ boolean fixed(); /** * Get boolean flag to check if node is collapsed * @return boolean flag */ boolean collapsed(); }
1,421
16.555556
67
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/model/interfaces/iGraph.java
package app.display.dialogs.visual_editor.model.interfaces; import app.display.dialogs.visual_editor.model.Edge; import java.util.HashMap; import java.util.List; /** * An interface to be adopted by displayable graph * @author nic0gin */ public interface iGraph { /** * Returns a list of edges in graph * @return list of edges */ List<Edge> getEdgeList(); /** * Returns a list on nodes in graph * @return hashmap where key stands for a node id and value is a node object */ HashMap<Integer, iGNode> getNodeList(); /** * get node by id * @param id node id * @return node instance */ iGNode getNode(int id); /** * Adds instance of a node to the graph * @param node valid instance of a node * @return node id */ int addNode(iGNode node); /** * Removes instance of a node from the graph * @param node valid instance of a node */ void removeNode(iGNode node); /** * add edge * @param from parent node * @param to child node */ void addEdge(int from, int to); /** * remove edge * @param from starting node of an edge * @param to end node of an */ void removeEdge(int from, int to); /** * * @return list of roots id of all connected components in the graph */ List<Integer> connectedComponentRoots(); /** * Add root id to the connected components list * Add node to the list on creation, on removal and on the deletion of parent connection * @param root id */ void addConnectedComponentRoot(int root); /** * Remove root id from the connected components list * Call on adding a parent node * @param root id */ void removeConnectedComponentRoot(int root); /** * returns id of a selected root * @return selected root/sub-root */ int selectedRoot(); /** * sets selected root * @param root selected root/sub-root */ void setSelectedRoot(int root); /** * sets main root of graph * @param root node instance (typically 'game' node) */ void setRoot(iGNode root); /** * returns instance of main graph root * @return node instance */ iGNode getRoot(); }
2,310
20.598131
92
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/CodeCompletionValidationMain.java
package app.display.dialogs.visual_editor.recs; import java.util.List; import app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling.DocHandler; import app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling.ModelLibrary; import app.display.dialogs.visual_editor.recs.validation.controller.ValidationController; public class CodeCompletionValidationMain { public static void main(String[] args) { ValidationController.validate(0.66,5,1000,2); /*int maxN = 20; int[] NValues = new int[maxN]; long[] creationDurations = new long[maxN]; String storageLocation = "PlayerDesktop/src/app/display/dialogs/visual_editor/resources/recs/validation/modelcreation/creation_duration.csv"; for(int i = 9; i <= maxN; i++) { long start = System.nanoTime(); ModelLibrary.getInstance().getModel(i); long finish = System.nanoTime(); long duration = finish - start; creationDurations[i - 2] = duration; NValues[i - 2] = i; System.out.println("N:"+i+",creation_duration:"+duration+"\n"); FileWriter fw = FileUtils.writeFile(storageLocation); try { fw.write("N,creation_duration"); for(int j = 2; j <= maxN; j++) { fw.write(NValues[j - 2]+","+creationDurations[j - 2]+"\n"); } fw.close(); } catch (IOException e) { e.printStackTrace(); } }*/ //ValidationController controller = new ValidationController(); //controller.validate(2,15); } public static void getMultipleModels(int maxN) { for(int N = 2; N <= maxN; N++) { ModelLibrary.getInstance().getModel(N); DocHandler.getInstance().writeDocumentsFile(); } } public static void testModelCreation() { // ModelLibrary lib = ModelLibrary.getInstance(); //NGram model = lib.getModel(5); DocHandler.getInstance().close(); } public static void print(Object o) { System.out.println(o); } public static void print(int i) { System.out.println(i); } public static void print(String s) { System.out.println(s); } public static <T> void print(List<T> list) { System.out.println(list); } }
2,415
30.789474
149
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/Ludeme.java
package app.display.dialogs.visual_editor.recs.codecompletion; public class Ludeme { private final String keyword; public Ludeme(String keyword) { this.keyword = keyword; } public String getKeyword() { return keyword; } @Override public String toString() { return keyword; } }
334
16.631579
62
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/controller/NGramController.java
package app.display.dialogs.visual_editor.recs.codecompletion.controller; import app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling.DocHandler; import app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling.ModelLibrary; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Context; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.NGram; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Preprocessing; import app.display.dialogs.visual_editor.recs.interfaces.codecompletion.controller.iController; import app.display.dialogs.visual_editor.recs.utils.*; import java.io.File; import java.util.List; import static app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Preprocessing.COMPLETION_WILDCARD; /** * @author filreh */ public class NGramController implements iController { private static final int MAX_PICKLIST_LENGTH = 50; private int N; private ModelLibrary lib; private NGram model; private DocHandler docHandler; /** * Standard constructor * @param N */ public NGramController(int N) { this.N = N; initModel(); } /** * This constructor is only for validation * @param model */ public NGramController(NGram model) { this.N = model.getN(); docHandler = DocHandler.getInstance(); this.model = model; } /** * This method should * - request a model with the specified N from the ModelLibrary * - load in the grammar */ private void initModel() { docHandler = DocHandler.getInstance(); lib = ModelLibrary.getInstance(); model = lib.getModel(N); } /** * Code Completion method for Visual Editor * * 1. Convert the context string into a Context object * 2. Get the matching Instance objects from the model * 3. Filter out the invalid Instances using the Grammar * 4. Use the BucketSort for the correct ordering * * @param contextString * @return list of candidate predictions sort after matching words with context, multiplicity */ @SuppressWarnings("all") @Override public List<Instance> getPicklist(String contextString) { // 0. if there is the wildcard COMPLETION_WILDCARD in there and cut it and everything after it off if(contextString.contains(COMPLETION_WILDCARD)) { int pos = contextString.lastIndexOf(COMPLETION_WILDCARD); contextString = contextString.substring(0,pos); } // 1. acquire context and preprocess it String cleanContextString = Preprocessing.preprocess(contextString); Context context = NGramUtils.createContext(cleanContextString); // 2. context sensitivity List<Instance> match = model.getMatch(context.getKey()); // 4. Calculate Number of Matching words & Remove duplicate predictions List<Pair<Instance, Integer>> uniquePredictions = NGramUtils.uniteDuplicatePredictions(match, context); // 5. Sorting after matching words and multiplicity List<Instance> picklist = BucketSort.sort(uniquePredictions, MAX_PICKLIST_LENGTH); return picklist; } /** * Code Completion method for Visual Editor * * 1. Convert the context string into a Context object * 2. Get the matching Instance objects from the model * 3. Filter out the invalid Instances using the Grammar * 4. Use the BucketSort for the correct ordering * 5. Optional: Shorten list to maxLength * * @param context * @param maxLength * @return list of candidate predictions sort after matching words with context, multiplicity */ @Override public List<Instance> getPicklist(String context, int maxLength) { List<Instance> picklist = getPicklist(context); if(picklist.size() >= maxLength) { picklist = picklist.subList(0,maxLength); } return picklist; } /** * Code Completion method for Text Editor * * 1. Convert the context string into a Context object * 2. Get the matching Instance objects from the model * 3. Filter out the invalid Instances using the Grammar * 4. Use the BucketSort for the correct ordering * 5. a. Preprocess begunWord * b. Filter out choices based on begunWord * * @param context * @param begunWord */ @Override public List<Instance> getPicklist(String context, String begunWord) { //String cleanBegunWord = Preprocessing.preprocessBegunWord(begunWord); System.out.println("CONTROLLER: context -> "+context); //List<Instance> preliminaryPicklist = getPicklist(context); //List<Symbol> picklist = NGramUtils.filterByBegunWord(cleanBegunWord,preliminaryPicklist);//TODO return null; } /** * Code Completion method for Text Editor * * 1. Convert the context string into a Context object * 2. Get the matching Instance objects from the model * 3. Filter out the invalid Instances using the Grammar * 4. Use the BucketSort for the correct ordering * 5. Filter out choices based on begunWord * 6. Optional: Shorten list to maxLength * * @param context * @param begunWord * @param maxLength */ @Override public List<Instance> getPicklist(String context, String begunWord, int maxLength) { List<Instance> picklist; if(StringUtils.equals(begunWord,"")) { picklist = getPicklist(context,maxLength); } else { picklist = getPicklist(context, begunWord); } if(picklist.size() >= maxLength) { picklist = picklist.subList(0,maxLength); } return picklist; } /** * This method switches out the current model, remember to update the N parameter * * @param ngramModel */ @Override public void changeModel(NGram ngramModel) { this.model = ngramModel; this.N = ngramModel.getN(); } /** * End all necessary connections and open links to storage. Discard the model */ @Override public void close() { DocHandler docHandlerInstance = DocHandler.getInstance(); //find all files in res/models that end in .csv and delete them //because models are stored compressed as .gz String modelsLocation = docHandlerInstance.getModelsLocation(); List<File> allFilesModels = FileUtils.listFilesForFolder(modelsLocation); for(File f : allFilesModels) { String fPath = f.getPath(); if(FileUtils.isFileCSV(fPath)) { FileUtils.deleteFile(fPath); } } docHandlerInstance.close(); } /** * Get the value of N for the current model */ @Override public int getN() { return N; } /** * @return a docHandler. */ public DocHandler getDocHandler() { return docHandler; } }
7,193
33.421053
115
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/filehandling/DocHandler.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling; import app.display.dialogs.visual_editor.recs.utils.FileUtils; import app.display.dialogs.visual_editor.recs.utils.StringUtils; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * Class is a singleton */ public class DocHandler { // TODO: refactor paths in similar way public static final String DOC_LOCATION = "../Common/res/recs/documents.txt"; public static final String GRAMMAR = "grammar_location"; public static final String GAMES = "games_location"; public static final String MODELS = "models_location"; public static final String MODEL = "location_model_"; public static final String LOGO = "logo_location"; public static final String GAMES_NAMES = "games_names_location"; public static final String SEPARATOR = ":"; public static final String MODEL_DOES_NOT_EXIST = "MODELDOESNOTEXIST"; private static final boolean DEBUG = false; private String grammarLocation; private String gamesLocation; private String logoLocation; private String modelsLocation; private Map<Integer,String> modelLocations; //singleton private static DocHandler docHandler; private String gamesNamesLocation; public static DocHandler getInstance() { // create object if it's not already created if(docHandler == null) { docHandler = new DocHandler(); } // returns the singleton object return docHandler; } /** * The constructor reads in alla available information from the file on startup */ private DocHandler() { modelLocations = new HashMap<>(); try(Scanner sc = FileUtils.readFile(DOC_LOCATION);) { while (sc.hasNext()) { String nextLine = sc.nextLine(); if(DEBUG)System.out.println(nextLine); parseDocumentsLine(nextLine); } sc.close(); } } /** * This method parses the different lines of the documents.txt: * -grammar location * -games location * -model location * @param line */ private void parseDocumentsLine(String line) { String[] split = line.split(SEPARATOR); if(StringUtils.equals(split[0], GRAMMAR)) { grammarLocation = split[1]; if(DEBUG)System.out.println(grammarLocation); } if(StringUtils.equals(split[0], GAMES)) { gamesLocation = split[1]; if(DEBUG)System.out.println(gamesLocation); } if(StringUtils.equals(split[0], LOGO)) { logoLocation = split[1]; if(DEBUG)System.out.println(logoLocation); } if(StringUtils.equals(split[0], MODELS)) { modelsLocation = split[1]; if(DEBUG)System.out.println(modelsLocation); } if(StringUtils.equals(split[0], GAMES_NAMES)) { gamesNamesLocation = split[1]; if(DEBUG)System.out.println(gamesNamesLocation); } if(split[0].startsWith(MODEL)) { int N = Integer.parseInt(split[0].charAt(MODEL.length())+""); modelLocations.put(Integer.valueOf(N), split[1]); if(DEBUG)System.out.println(modelLocations.get(Integer.valueOf(N))); } } /** * This method writes the stored data about documents to the documents.txt */ public void writeDocumentsFile() { try (FileWriter fw = FileUtils.writeFile(DOC_LOCATION);) { if(grammarLocation != null) { fw.write(GRAMMAR +SEPARATOR+grammarLocation+"\n"); } if(gamesLocation != null) { fw.write(GAMES +SEPARATOR+gamesLocation+"\n"); } if(logoLocation != null) { fw.write(LOGO +SEPARATOR+logoLocation+"\n"); } if(modelsLocation != null) { fw.write(MODELS +SEPARATOR+modelsLocation+"\n"); } if(gamesNamesLocation != null) { fw.write(GAMES_NAMES +SEPARATOR+gamesNamesLocation+"\n"); } for(Map.Entry<Integer, String> entry : modelLocations.entrySet()) { int N = entry.getKey().intValue(); String modelLocation = entry.getValue(); fw.write(MODEL +N+SEPARATOR+modelLocation+"\n"); } fw.close(); } catch (IOException e) { e.printStackTrace(); } } public void addModelLocation(int N, String location) { modelLocations.put(Integer.valueOf(N), location); } public String getGrammarLocation() { return grammarLocation; } public String getGamesLocation() { return gamesLocation; } public String getLogoLocation() { return logoLocation; } public String getModelsLocation() { return modelsLocation; } public String getGamesNamesLocation() { return gamesNamesLocation; } public String getModelLocation(int N) { return modelLocations.getOrDefault(Integer.valueOf(N), MODEL_DOES_NOT_EXIST); } /** * Write the documents file on closing */ public void close() { writeDocumentsFile(); } }
5,405
30.248555
85
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/filehandling/GameFileHandler.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling; import app.display.dialogs.visual_editor.recs.utils.FileUtils; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class GameFileHandler { public static void writeGame(String gameDescription, String location) { try (FileWriter fw = FileUtils.writeFile(location);) { fw.write(gameDescription); fw.close(); } catch (IOException e) { e.printStackTrace(); } } public static String readGame(String location) { String gameDescription = ""; //reads line by line try ( Scanner sc = FileUtils.readFile(location);) { while (sc.hasNext()) { String nextLine = sc.nextLine(); gameDescription += "\n"+nextLine; } sc.close(); return gameDescription; } } }
960
26.457143
82
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/filehandling/LudiiGameDatabase.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.filehandling.iLudiiGameDatabase; import app.display.dialogs.visual_editor.recs.utils.FileUtils; import app.display.dialogs.visual_editor.recs.utils.StringUtils; /** * @author filreh */ public class LudiiGameDatabase implements iLudiiGameDatabase { private static final boolean DEBUG = false; private final DocHandler docHandler; private ArrayList<String> locations; private Map<Integer, String> descriptions; private Map<String, Integer> names; //Singleton private static LudiiGameDatabase db; public static LudiiGameDatabase getInstance() { // create object if it's not already created if(db == null) { db = new LudiiGameDatabase(); } // returns the singleton object return db; } private LudiiGameDatabase() { this.docHandler = DocHandler.getInstance(); init(); } private void init() { fetchGameLocations(); names = new HashMap<>(); descriptions = new HashMap<>(); fetchGameNames(); } private void fetchGameLocations() { File folder = new File(docHandler.getGamesLocation()); ArrayList<File> files = FileUtils.listFilesForFolder(folder); locations = new ArrayList<>(); for(File f : files) { String location = f.getAbsolutePath(); locations.add(location); if(DEBUG)System.out.println(location); } } /** * This method reads in a file that contains all game names. */ private void fetchGameNames() { String location = DocHandler.getInstance().getGamesNamesLocation(); try(Scanner sc = FileUtils.readFile(location);) { int id = 0; while (sc.hasNext()) { String curGameName = sc.nextLine(); names.put(curGameName, Integer.valueOf(id++)); } sc.close(); } } // /** // * This method analyses each game description one by one and writes the name of each game to a file. // */ // private void fetchGameNamesFromDescriptions() { // String location = DocHandler.getInstance().getGamesNamesLocation(); // try(FileWriter fw = FileUtils.writeFile(location);) // { // for(int i = 0; i < getAmountGames(); i++) { // String gameDescription = getDescription(i); // String gameName = NGramUtils.getGameName(gameDescription); // names.put(gameName, i); // // try { // fw.write(gameName); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // catch (IOException e1) // { // e1.printStackTrace(); // } // } /** * Returns a list of all the locations of game descriptions in the database. */ @Override public List<String> getLocations() { return locations; } /** * Returns the amount of games in the database */ @Override public int getAmountGames() { return locations.size(); } /** * Returns the description of the game with the id in the locations list * * @param id */ @Override public String getDescription(int id) { //fetches description if it was already read in String description = descriptions.getOrDefault(Integer.valueOf(id), "null"); // else, reads it in if(StringUtils.equals(description,"null")) { String location = locations.get(id); description = GameFileHandler.readGame(location); } return description; } /** * Returns the description of the game with the name specified. Create a map that links names to * ids and use the other method. * * @param name */ @Override public String getDescription(String name) { int id = names.get(name).intValue(); return getDescription(id); } public List<String> getNames() { String[] namesArr = new String[getAmountGames()+1]; for(Map.Entry<String, Integer> entry : names.entrySet()) { int id = entry.getValue().intValue(); String name = entry.getKey(); namesArr[id] = name; } List<String> namesList = Arrays.asList(namesArr); return namesList; } }
4,713
27.227545
111
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/filehandling/ModelFilehandler.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.NGram; import app.display.dialogs.visual_editor.recs.utils.FileUtils; import app.display.dialogs.visual_editor.recs.utils.GZIPController; import app.display.dialogs.visual_editor.recs.utils.Model2CSV; import app.display.dialogs.visual_editor.recs.utils.StringUtils; public class ModelFilehandler { public static final String MODEL_LOCATION = DocHandler.getInstance().getModelsLocation()+"/ngram_model_"; /** * This method performs the operation of extracting a model from its file. * @param N */ public static NGram readModel(int N) { DocHandler docHandler = DocHandler.getInstance(); String location = docHandler.getModelLocation(N); if(location == null) { throw new NullPointerException("Model does not exist yet"); } //removes file extension location = StringUtils.removeSuffix(location,".gz"); //decompress GZIPController.decompress(location+".gz",location+".csv"); //model2csv NGram model = Model2CSV.csv2model(location+".csv"); return model; } public static void writeModel(NGram model) { int N = model.getN(); String location = MODEL_LOCATION+N; //write to csv file Model2CSV.model2csv(model, location+".csv"); //compress GZIPController.compress(location+".csv",location+".gz"); //Delete .csv file FileUtils.deleteFile(location+".csv"); //add the location to the documents.txt DocHandler docHandler = DocHandler.getInstance(); docHandler.addModelLocation(N,location+".gz"); } }
1,772
39.295455
109
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/filehandling/ModelLibrary.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.ModelCreator; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.NGram; import app.display.dialogs.visual_editor.recs.display.ProgressBar; import app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.filehandling.iModelLibrary; import app.display.dialogs.visual_editor.recs.utils.StringUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author filreh */ public class ModelLibrary implements iModelLibrary { private final DocHandler docHandler; private List<String> modelLocations; private Map<Integer, NGram> allModels; //Singleton private static ModelLibrary lib; public static ModelLibrary getInstance() { // create object if it's not already created if(lib == null) { lib = new ModelLibrary(); } // returns the singleton object return lib; } private ModelLibrary() { this.docHandler = DocHandler.getInstance(); allModels = new HashMap<>(); this.modelLocations = allModelLocations(); } /** * This method returns a model with the specified N. * If it didn't exist before it is created. ANd written to a file. * Adds it to the model locations. Also in the documents.txt * * @param N */ @Override public NGram getModel(int N) { // progress bar ProgressBar pb = new ProgressBar("Fetching Data","",100); //1. check if it is in the already loaded in models NGram model = allModels.getOrDefault(Integer.valueOf(N), null); if(model == null) { model = addModel(N, pb); } pb.updateProgress(100); pb.close(); return model; } /** * Returns all model locations, is updated every time it is called */ @Override public List<String> allModelLocations() { modelLocations = new ArrayList<>(); for(int N = 2; N <= 20; N++) { String location = docHandler.getModelLocation(N); //if the model exists if(!StringUtils.equals(location,DocHandler.MODEL_DOES_NOT_EXIST)) { modelLocations.add(location); } } return modelLocations; } /** * Returns the amount of models stored currently */ @Override public int getAmountModels() { //update the list before returning allModelLocations(); return modelLocations.size(); } /** * If the model is not already included in the list of models, then it is created and added to the list. * If this method is called, then the model is not in allModels * @param N * @return */ private NGram addModel(int N, ProgressBar pb) { NGram model = null; pb.updateProgress(33); //1. check if it exists if(docHandler.getModelLocation(N).equals(DocHandler.MODEL_DOES_NOT_EXIST)) { //1.a does not exist: create a new one model = ModelCreator.createModel(N); //multithreading stop pb.updateProgress(90); } else { //1.b model does exist: read it in from file model = ModelFilehandler.readModel(N); pb.updateProgress(66); } //either way add it to the loaded in models allModels.put(Integer.valueOf(N), model); return model; } }
3,663
27.850394
108
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/model/Context.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.model; import app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.model.iContext; import java.util.List; /** * @author filreh */ public class Context implements iContext { private final List<String> words; private final int length; private final String key; /** * This class expects the words to have already undergone preprocessing * @param words */ public Context(List<String> words) { this.words = words; this.length = words.size(); this.key = words.get(length - 1); } @Override public String getKey() { return key; } @Override public List<String> getWords() { return words; } @Override public String toString() { String output = "{Words: "; for(String word : words) { output += word + " "; } output += "Key: "+key+"}"; return output; } }
1,009
20.956522
94
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/model/Converter.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.model; import app.display.dialogs.visual_editor.recs.utils.StringUtils; import main.grammar.Description; import main.grammar.Report; import main.grammar.Token; import main.options.UserSelections; import java.util.ArrayList; public class Converter { private static final String INDENT = " "; public static String toConstructor(final String desc) { Description test_desc = new Description(desc); parser.Parser.expandAndParse(test_desc, new UserSelections(new ArrayList<>()),new Report(),false); Token tokenTree = new Token(test_desc.expanded(), new Report()); String converted = "("+tokenTree.name(); System.out.println(converted); for(Token token : tokenTree.arguments()) { converted += " " + convertToken(token, 1); } converted += ")"; //remove double spaces while (converted.contains(" ")) { converted = converted.replaceAll(" "," "); } return converted; } private static String convertToken(Token token, int depth) { String converted = ""; if (token.isTerminal()) { String terminal = convertTerminalToConstructor(token); System.out.println(StringUtils.repeat(INDENT, depth) + terminal); converted += terminal; } else if(token.isClass()) { converted += "(" + token.name(); System.out.println(StringUtils.repeat(INDENT, depth) + "(" +token.name()); for(Token argument : token.arguments()) { converted += " " + convertToken(argument, depth + 1); } converted += " ) "; } else if(token.isArray()) { converted += "{"; System.out.println(StringUtils.repeat(INDENT, depth) + token.name()); for(Token argument : token.arguments()) { converted += convertToken(argument, depth + 1); } converted += "} "; } return converted; } private static String convertTerminalToConstructor(Token terminal) { String converted = ""; if(isString(terminal)) { converted = "<string>"; } else if(isInt(terminal)) { converted = "<int>"; } else if(isFloat(terminal)) { converted = "<float>"; } else if(isBoolean(terminal)) { converted = "<boolean>"; } else if(isRange(terminal)) { converted = "<range>"; } else { // must be a terminal ludeme like "None" converted = terminal.name(); } return converted; } private static boolean isString(Token terminal) { String name = terminal.name(); char[] charArray = name.toCharArray(); if(charArray[0] == '"' && charArray[charArray.length - 1] == '"') { return true; } return false; } private static boolean isInt(Token terminal) { String name = terminal.name(); char[] charArray = name.toCharArray(); for(char c : charArray) { if(!Character.isDigit(c)) { return false; } } return true; } private static boolean isFloat(Token terminal) { String name = terminal.name(); char[] charArray = name.toCharArray(); for(char c : charArray) { if(!Character.isDigit(c) || c == '.' || c == ',') { return false; } } return true; } private static boolean isRange(Token terminal) { String name = terminal.name(); if(name.contains("..")) { return true; } return false; } private static boolean isBoolean(Token terminal) { String name = terminal.name(); if(name.equals("True") || name.equals("False") || name.equals("true") || name.equals("false")) { return true; } return false; } }
4,044
31.103175
106
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/model/Instance.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.model; import app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.model.iInstance; import app.display.dialogs.visual_editor.recs.utils.ListUtils; import app.display.dialogs.visual_editor.recs.utils.StringUtils; import java.util.List; /** * @author filreh */ public class Instance implements iInstance { private final List<String> words; private final Context context; private final int length; private final String prediction; private final String key; private int multiplicity; public Instance(List<String> words, int multiplicity) { this.multiplicity = multiplicity; this.words = words; this.length = words.size(); //the last word is left out of the context because it is the prediction this.context = new Context(words.subList(0,length - 1)); this.prediction = words.get(length - 1); this.key = words.get(length - 2); } public Instance(List<String> words) { this.multiplicity = 1; this.words = words; this.length = words.size(); //the last word is left out of the context because it is the prediction this.context = new Context(words.subList(0,length - 1)); this.prediction = words.get(length - 1); this.key = words.get(length - 2); } /** * This method increases the multiplicity of the instance by one. */ @Override public void increaseMultiplicity() { this.multiplicity++; } /** * This method simply counts up the number of words this instance has in common with the context, * starting at the back. * * @param c */ @Override public int matchingWords(Context c) { List<String> foreignContextWords = c.getWords(); List<String> thisContextWords = this.context.getWords(); int matchingWords = ListUtils.stringsInCommonBack(foreignContextWords,thisContextWords); return matchingWords; } @Override public String getPrediction() { return this.prediction; } @Override public String getKey() { return this.key; } @Override public List<String> getWords() { return this.words; } @Override public Context getContext() { return this.context; } @Override public int getMultiplicity() { return this.multiplicity; } @Override public String toString() { String output = "{Words: "; for(String word : words) { output += word + " "; } output += "Prediction: " + prediction + " Key: "+key+" Multiplicity: " + multiplicity+"}"; return output; } @Override public boolean equals(Object o) { if(o instanceof Instance) { Instance i = (Instance) o; List<String> iWords = i.getWords(); if(iWords.size() == words.size()) { for(int j = 0; j < words.size(); j++) { if(!StringUtils.equals(iWords.get(j),words.get(j))) { return false; } } return true; } } return false; } @Override public int hashCode() { return super.hashCode(); } }
3,343
26.409836
101
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/model/ModelCreator.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.model; import app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling.LudiiGameDatabase; import app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling.ModelFilehandler; import app.display.dialogs.visual_editor.recs.display.ProgressBar; import app.display.dialogs.visual_editor.recs.utils.NGramUtils; import javax.swing.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; /** * @author filreh */ public class ModelCreator { /** * This method should only be called as part of the validation process or by the ModelLibrary * This method creates a new model and writes a model to a .gz file. * The location is according to the internal storing mechanism that is based on the N parameter. * This method only adds the game descriptions with the specified ids to the model * * By listing only a limited number of games, this method can construct a model for validation * @param N * @param gameIDs List of game descriptions to be included in the model * @param validation If true, the model will not be written to a file */ public static NGram createModel(int N, List<Integer> gameIDs, boolean validation) { NGram model = new NGram(N); LudiiGameDatabase db = LudiiGameDatabase.getInstance(); // this method only adds the game descriptions with the specified ids to the model // not all games! therefore not db.getAmountGames() int amountGames = gameIDs.size(); //create progressbar ProgressBar pb = new ProgressBar("Creating model","Creating the model from the game description database.",amountGames); //multithreading start // T - the result type returned by this SwingWorker's doInBackground and get methods // V - the type used for carrying out intermediate results by this SwingWorker's // publish and process methods SwingWorker<NGram,Integer> modelCreatorTask = new SwingWorker<NGram, Integer>() { @Override protected NGram doInBackground() throws Exception { NGram ngramModel = new NGram(N); for(int i = 0; i < amountGames; i++) { int gameID = gameIDs.get(i).intValue(); String curGameDescription = db.getDescription(gameID); //apply preprocessing String cleanGameDescription = Preprocessing.preprocess(curGameDescription); //add all instances of length in {2,...,N} for(int j = 2; j <= N; j++) { List<List<String>> substrings = NGramUtils.allSubstrings(cleanGameDescription, j); for(List<String> substring : substrings) { Instance curInstance = NGramUtils.createInstance(substring); if(curInstance != null) { ngramModel.addInstanceToModel(curInstance); } } } //update progressbar double percent = (((double) i) / ((double) amountGames)); int progress = (int) (percent*100.0); setProgress(progress); Thread.sleep(125); } return ngramModel; } @Override public void process(List<Integer> chunks) { for(int chunk : chunks) { pb.updateProgress(chunk); } } }; modelCreatorTask.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { double percent = (modelCreatorTask.getProgress() / 100.0); pb.updateProgress(percent); } }); modelCreatorTask.execute(); try { model = modelCreatorTask.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } //discard of the progressbar pb.close(); //if the model is only created for validation purposes, it is not written to a file System.out.println("VALIDATION:"+validation); if(!validation) { ModelFilehandler.writeModel(model); } return model; } /** * This method should only be called as part of the validation process or by the ModelLibrary * This method creates a new model and writes a model to a .gz file. * The location is according to the internal storing mechanism that is based on the N parameter. * This method adds all game descriptions to the model and is therefore not for validation purposes. * @param N */ public static NGram createModel(int N) { List<Integer> gameIDs = new ArrayList<>(); LudiiGameDatabase db = LudiiGameDatabase.getInstance(); int amountGames = db.getAmountGames(); for (int i = 0; i < amountGames; i++) { gameIDs.add(Integer.valueOf(i)); } //return createModel(N, gameIDs, false); return createModel(N, gameIDs, false); } }
5,457
40.984615
128
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/model/NGram.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.model; import app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.model.iNGram; import app.display.dialogs.visual_editor.recs.utils.StringUtils; import java.util.*; import static app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Preprocessing.*; /** * @author filreh */ public class NGram implements iNGram { private final int N; private HashMap<String, List<Instance>> dictionary; public NGram(int N) { this.N = N; this.dictionary = new HashMap<>(); addSpecialCases(); } /** * This constructor is to read in a model * @param N * @param dictionary */ public NGram(int N, HashMap<String, List<Instance>> dictionary) { this.N = N; this.dictionary = dictionary; addSpecialCases(); } private void addSpecialCases() { String key = ""; List<Instance> specialCases = new ArrayList<>(); specialCases.add(new Instance(Arrays.asList(new String[]{"","(game"}),Integer.MAX_VALUE - 1)); specialCases.add(new Instance(Arrays.asList(new String[]{"","(define"}),Integer.MAX_VALUE - 2)); specialCases.add(new Instance(Arrays.asList(new String[]{"","(metadata"}),Integer.MAX_VALUE - 3)); dictionary.put(key,specialCases); } /** * This method adds one instance to the model, be weary of multiplicities * * @param instance */ @Override public void addInstanceToModel(Instance instance) { if(!specifyNumberAndBoolean(instance)) { List<Instance> recs = dictionary.getOrDefault(instance.getKey(), new ArrayList<>()); boolean foundEqual = false; for (Instance i : recs) { if (i.equals(instance)) { // found an instance with the same words --> increase its multiplicity i.increaseMultiplicity(); foundEqual = true; break; } } if (!foundEqual) { recs.add(instance); } dictionary.put(instance.getKey(), recs); } } /** * This method duplicates any instance with NUMBER_WILDCARD in it to be an instance with * FLOAT and INT wildcards. * @param instance */ private boolean specifyNumberAndBoolean(Instance instance) { //TODO Move this method into the getPicklist, then it only gets applied to the requested ludemes //and keeps the filesize down boolean containsNumber = false, containsBoolean = false; String[] wildcards = new String[] {INTEGER_WILDCARD, FLOAT_WILDCARD}; String[] booleanLudemes = new String[] {"True","False"}; List<String> words = instance.getWords(); //to replace the generic number wildcard with float and int wildcards for(String wildcard : wildcards) { if(instance.getWords().contains(NUMBER_WILDCARD)) { containsNumber = true; List<String> newWords = new ArrayList<>(); for(String word : words) { if(StringUtils.equals(word, NUMBER_WILDCARD)) { newWords.add(wildcard); } else { newWords.add(word); } } Instance newInstance = new Instance(newWords, instance.getMultiplicity()); addInstanceToModel(newInstance); } } // to replace the generic boolean wildcard for(String booleanValue : booleanLudemes) { if(instance.getWords().contains(BOOLEAN_WILDCARD)) { containsBoolean = true; List<String> newWords = new ArrayList<>(); for(String word : words) { if(StringUtils.equals(word, BOOLEAN_WILDCARD)) { newWords.add(booleanValue); } else { newWords.add(word); } } Instance newInstance = new Instance(newWords, instance.getMultiplicity()); addInstanceToModel(newInstance); } } return (containsNumber || containsBoolean); } /** * This method returns a list of all instances with the same key as the provided one. * * @param key */ @Override public List<Instance> getMatch(String key) { List<Instance> match = dictionary.getOrDefault(key, new ArrayList<>()); return match; } /** * Get the value of N for the model. */ @Override public int getN() { return N; } /** * Returns the Map object containing the NGram */ @Override public Map<String, List<Instance>> getDictionary() { return dictionary; } }
4,935
33.041379
106
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/model/Preprocessing.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.model; import app.display.dialogs.visual_editor.recs.utils.StringUtils; import java.util.ArrayList; import java.util.List; /** * @author filreh */ public class Preprocessing { private static final boolean DEBUG = false; public static final String NUMBER_WILDCARD = "number"; public static final String INTEGER_WILDCARD = "int"; public static final String FLOAT_WILDCARD = "float"; public static final String BOOLEAN_WILDCARD = "boolean"; public static final String STRING_WILDCARD = "string"; public static final String OPTION_WILDCARD = "option"; public static final String COMPLETION_WILDCARD = "[#]"; public final static boolean GENERIC_STRINGS = true; public final static boolean GENERIC_OPTIONS = true; /** * This method applies all the necessary steps of preprocessing. * @param gameDescription */ @SuppressWarnings("all") public static String preprocess(String gameDescription) { if(DEBUG)System.out.println("Raw:"+gameDescription); gameDescription = removeMetadata(gameDescription); if(DEBUG)System.out.println("Removed Metadata:"+gameDescription); gameDescription = removeComments(gameDescription); if(DEBUG)System.out.println("Removed Comments:"+gameDescription); gameDescription = removeWhitespaces(gameDescription); if(DEBUG)System.out.println("Removed Withespaces:"+gameDescription); gameDescription = genericValues(gameDescription); if(DEBUG)System.out.println("Replaced specific values with generic placeholders:"+gameDescription); return gameDescription; } /** * This method removes the metadata from the game description * * @param gameDescription */ @SuppressWarnings("all") public static String removeMetadata(String gameDescription) { String metadataLudeme = "(metadata"; if(gameDescription.contains(metadataLudeme)) { int startMetadata = gameDescription.lastIndexOf(metadataLudeme); gameDescription = gameDescription.substring(0,startMetadata); } return gameDescription; } /** * This method removes all comments from the game description and ravels the description into one line. * * @param gameDescription */ @SuppressWarnings("all") public static String removeComments(String gameDescription) { String commentLudeme = "//"; String[] lines = gameDescription.split("\n"); String noComments = ""; for(int i = 0; i < lines.length; i++) { String line = lines[i]; if(line.contains(commentLudeme)) { int commentLocation = line.lastIndexOf(commentLudeme); line = line.substring(0,commentLocation); } noComments += line; } gameDescription = noComments; return gameDescription; } /** * This method removes all tabs and unnecessary whitespaces from the game description while adding * needed ones. * * @param gameDescription * @return */ @SuppressWarnings("all") public static String removeWhitespaces(String gameDescription) { char[] chars = gameDescription.toCharArray(); gameDescription = ""; char prevChar = '1'; for(int i = 0; i < chars.length; i++) { char curChar = chars[i]; // so it does not go out of bounds char nextChar = i < (chars.length - 1) ? chars[(i + 1)] : chars[i]; if (prevChar == ' ' && curChar == ' ') { //do not add the char to the game description } else if(nextChar == ')' || nextChar == '}') { //add a space before a closing ) gameDescription += curChar+" "; } else if(curChar == ')' && (nextChar != ')' && nextChar != ' ')) { //add a space before a closing ) gameDescription += curChar+" "; } else if(curChar == '{' && nextChar != ' ') { //add a space before a closing ) gameDescription += curChar+" "; } else { gameDescription += curChar; } prevChar = curChar; } chars = gameDescription.toCharArray(); gameDescription = ""; prevChar = '1'; // again remove any double spaces for(int i = 0; i < chars.length; i++) { char curChar = chars[i]; // so it does not go out of bounds char nextChar = i < (chars.length - 1) ? chars[(i + 1)] : chars[i]; if ((prevChar == ' ' && curChar == ' ') || curChar == '\t' || curChar == '\n') { //do not add the char to the game description } else { gameDescription += curChar; } prevChar = curChar; } return gameDescription; } /** * This method replaces specific values with generic wildcards * Strings will stay in as they are of importance to the game * @param gameDescription * @return */ @SuppressWarnings("all") public static String genericValues(String gameDescription) { // REPLACE NUMBERS char[] chars = gameDescription.toCharArray(); gameDescription = ""; char prevChar = '?'; boolean foundNumber = false; for(int i = 0; i < chars.length; i++) { char curChar = chars[i]; char nextChar = i < (chars.length - 1) ? chars[(i + 1)] : chars[i]; switch (curChar) { case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': if(!foundNumber) { if(prevChar == ' ' || prevChar == ':') { //found a number foundNumber = true; // do not add } else { // this digit was part of a word gameDescription += curChar; } } if(foundNumber) { if(nextChar == ' ') { gameDescription += NUMBER_WILDCARD; foundNumber = false; } } break; default: gameDescription += curChar; break; } prevChar = curChar; } gameDescription = gameDescription.replaceAll("True",BOOLEAN_WILDCARD); gameDescription = gameDescription.replaceAll("False",BOOLEAN_WILDCARD); String[] words = gameDescription.split(" "); //merge strings in code back together List<String> wordsList = new ArrayList<>(); boolean foundStringInCode = false; String stringInCode = ""; for(int i = 0; i < words.length; i++) { String curWord = words[i]; if(foundStringInCode) { if(curWord.endsWith("\"")) { //end of the string in code if(GENERIC_STRINGS) { wordsList.add(STRING_WILDCARD); } else { stringInCode += curWord; wordsList.add(stringInCode); } //resetting helper variables foundStringInCode = false; stringInCode = ""; } else { //middle of the string in code stringInCode += curWord + " "; } } else if(curWord.startsWith("\"") && !curWord.endsWith("\"")) { //beginning of the string in code foundStringInCode = true; stringInCode += curWord + " "; } else { if(GENERIC_STRINGS && curWord.startsWith("\"") && curWord.endsWith("\"")) { //string in code wordsList.add(STRING_WILDCARD); } else if(GENERIC_OPTIONS && (curWord.startsWith("<") || curWord.endsWith(">"))){ wordsList.add(OPTION_WILDCARD); } else if(StringUtils.equals(curWord,"*")) { //do nothing } else { //just a normal word wordsList.add(curWord); } } } //end merging strings if(wordsList.isEmpty()){ gameDescription = ""; } else { //piece the game description back together gameDescription = wordsList.get(0); if(wordsList.size() > 1) { for (int i = 1; i < wordsList.size(); i++) { gameDescription += " " + wordsList.get(i); } } } return gameDescription; } @SuppressWarnings("all") public static String preprocessBegunWord(String begunWord) { String cleanBegunWord = ""; // Watch out for numbers: only contains numbers try { //need to find out whether it is a float or an int if(begunWord.contains(".")) { cleanBegunWord = FLOAT_WILDCARD; } else { cleanBegunWord = INTEGER_WILDCARD; } } catch (NumberFormatException e) { //part of the logic: if the begunWord does not parse, then it is not a number } catch (Exception e) { e.printStackTrace(); } //Watch out for strings: begins with '"' if(begunWord.startsWith("\"")) { begunWord = STRING_WILDCARD; } //Watch out for options: begins with '<' if(begunWord.startsWith("<")) { begunWord = OPTION_WILDCARD; } return cleanBegunWord; } }
10,258
35.250883
107
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/codecompletion/domain/model/TypeMatch.java
package app.display.dialogs.visual_editor.recs.codecompletion.domain.model; import app.display.dialogs.visual_editor.recs.codecompletion.controller.NGramController; import app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.model.iTypeMatch; import app.display.dialogs.visual_editor.recs.utils.StringUtils; import main.grammar.Symbol; import java.util.ArrayList; import java.util.List; public class TypeMatch implements iTypeMatch { private static TypeMatch instance; public static TypeMatch getInstance() { if(instance == null) { instance = new TypeMatch(); } return instance; } private TypeMatch() { } /** * This method takes in the game description as a string and a list of suggestions from the grammar * Then it * * @param gameDescription * @param possibleSymbols */ @Override public List<Symbol> typematch(String gameDescription, NGramController controller, List<Symbol> possibleSymbols) { boolean verbose = false; if(verbose)System.out.println("--------------------------------------"); if(verbose)System.out.println(" # Game Description"); if(verbose)System.out.println(gameDescription); // 1. get the picklist from the NGram model List<Instance> instancePicklist = controller.getPicklist(gameDescription); if(verbose)System.out.println(" # Ordered Picklist by N-Gram"); for(Instance instanceList : instancePicklist) { String prediction = instanceList.getPrediction(); if(prediction.startsWith("(")) prediction = prediction.replaceAll("\\(",""); if(verbose)System.out.println("Completion: " + prediction); } if(verbose)System.out.println(" # Possible Symbols from grammar"); for(Symbol symbol : possibleSymbols) { // if the type is predefined, need to check for boolean, string and number if(verbose)System.out.println("Symbol: " + symbol.name() + " token: " + symbol.token() + " type: " + symbol.ludemeType()); } // 2. create a new picklist to output Symbol[] possibleSymbolsArray = possibleSymbols.toArray(new Symbol[0]); List<Symbol> picklist = new ArrayList<>(); for(int i = 0; i < instancePicklist.size(); i++) { Instance curInstance = instancePicklist.get(i); String prediction = curInstance.getPrediction(); if(prediction.startsWith("(")) {// in case it is a ludeme like (game with an opening bracket, remove it prediction = prediction.replaceAll("\\(",""); } // if the instance is contained in the possible symbols list, then add it to the picklist for(int j = 0; j < possibleSymbolsArray.length; j++) { //System.out.println("I:"+i+" J: "+j); if(possibleSymbolsArray[j] == null) { continue; } Symbol curSymbol = possibleSymbolsArray[j]; String token = curSymbol.token(); //System.out.println("Prediction: "+ prediction + " Name: " + token + " equals? " + StringUtils.equals(prediction,token)); if(StringUtils.equals(prediction,token)) { //add the symbol to the picklist, since this is done in the correct order of the instancelist it preserves the order // for(Symbol symbol : picklist) { // // } picklist.add(curSymbol); // delete the symbol out of the array possibleSymbolsArray[j] = null; } } } //add all symbols that are still in the possible symbols array to the picklist for(int i = 0; i < possibleSymbolsArray.length; i++) { if(possibleSymbolsArray[i] == null) { continue; } Symbol curSymbol = possibleSymbolsArray[i]; picklist.add(curSymbol); } if(verbose) { System.out.println(" # Final Picklist, of length: " + picklist.size()); for (int i = 0; i < picklist.size(); i++) { System.out.println(i + ". " + picklist.get(i)); } } // then in the end return picklist return picklist; } }
4,404
39.787037
138
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/display/ProgressBar.java
package app.display.dialogs.visual_editor.recs.display; import app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling.DocHandler; import javax.swing.*; import java.awt.*; public class ProgressBar { private final String operationDescription; private JDialog dialog; private JProgressBar progressBar; private final int operationsMax; private final String operationName; private double progress; private JPanel panel; private JLabel label; public ProgressBar(String operationName, String operationDescription, int operationsMax) { this.operationsMax = operationsMax; this.operationName = operationName; this.operationDescription = operationDescription; init(); } private void init(){ int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width; int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height; progress = 0.0; dialog = new JDialog(); dialog.setTitle(operationName); panel = new JPanel(); progressBar = new JProgressBar((int) progress); label = new JLabel(operationDescription); progressBar.setPreferredSize(new Dimension((int)(screenWidth*0.20), (int)(screenHeight*0.036))); progressBar.setStringPainted(true); label.setFont(new Font("Dialog", Font.BOLD, 20)); label.setLabelFor(progressBar); panel.add(label); panel.add(progressBar); dialog.add(panel); Image img = new ImageIcon(DocHandler.getInstance().getLogoLocation()).getImage(); dialog.setIconImage(img); dialog.setSize((int)(screenWidth*0.237), (int)(screenHeight*0.10)); dialog.setLocationRelativeTo(null); dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); dialog.setResizable(false); dialog.requestFocus(); dialog.setVisible(true); } /** * Sets the progress of the bar to the specified percent level * @param percent */ public void updateProgress(double percent) { this.progress = percent*100; int progressInt = (int) progress; progressBar.setValue(progressInt); progressBar.setVisible(true); label.setVisible(true); //System.out.println(progressInt); dialog.invalidate(); dialog.validate(); dialog.repaint(); } /** * Calculates the progress of the bar based on maxOperations and operations finished * @param operationsFinished */ public void updateProgress(int operationsFinished) { double percent = (((double) operationsFinished) / ((double) operationsMax)); updateProgress(percent); } public void close() { progressBar.setString("Finished"); long delta = 500; long start = System.currentTimeMillis(); long end = System.currentTimeMillis(); while (!((end - start) > delta)) { end = System.currentTimeMillis(); } dialog.dispose(); } }
3,050
33.670455
104
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/interfaces/codecompletion/controller/iController.java
package app.display.dialogs.visual_editor.recs.interfaces.codecompletion.controller; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.NGram; import java.util.List; /** * @author filreh */ public interface iController { /** * Code Completion method for Visual Editor * * 1. Convert the context string into a Context object * 2. Get the matching Instance objects from the model * 3. Filter out the invalid Instances using the Grammar * 4. Use the BucketSort for the correct ordering * @param context * @return list of candidate predictions sort after matching words with context, multiplicity */ List<Instance> getPicklist(String context); /** * Code Completion method for Visual Editor * * 1. Convert the context string into a Context object * 2. Get the matching Instance objects from the model * 3. Filter out the invalid Instances using the Grammar * 4. Use the BucketSort for the correct ordering * 5. Optional: Shorten list to maxLength * @param context * @param maxLength * @return list of candidate predictions sort after matching words with context, multiplicity */ List<Instance> getPicklist(String context, int maxLength); /** * Code Completion method for Text Editor * * 1. Convert the context string into a Context object * 2. Get the matching Instance objects from the model * 3. Filter out the invalid Instances using the Grammar * 4. Use the BucketSort for the correct ordering * 5. Filter out choices based on begunWord * @param context * @param begunWord */ List<Instance> getPicklist(String context, String begunWord); /** * Code Completion method for Text Editor * * 1. Convert the context string into a Context object * 2. Get the matching Instance objects from the model * 3. Filter out the invalid Instances using the Grammar * 4. Use the BucketSort for the correct ordering * 5. Filter out choices based on begunWord * 6. Optional: Shorten list to maxLength * @param context * @param begunWord * @param maxLength */ List<Instance> getPicklist(String context, String begunWord, int maxLength); /** * This method switches out the current model, remember to update the N parameter * @param model */ void changeModel(NGram model); /** * End all necessary connections and open links to storage. Discard the model */ void close(); /** * Get the value of N for the current model */ int getN(); }
2,734
31.559524
97
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/interfaces/codecompletion/domain/filehandling/iLudiiGameDatabase.java
package app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.filehandling; import java.util.List; /** * @author filreh */ public interface iLudiiGameDatabase { /** * Returns a list of all the locations of game descriptions in the database. */ List<String> getLocations(); /** * Returns the amount of games in the database */ int getAmountGames(); /** * Returns the description of the game with the id in the locations list * @param id */ String getDescription(int id); /** * Returns the description of the game with the name specified. Create a map that links names to * ids and use the other method. * @param name */ String getDescription(String name) throws Exception; }
786
23.59375
100
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/interfaces/codecompletion/domain/filehandling/iModelLibrary.java
package app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.filehandling; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.NGram; import java.util.List; /** * @author filreh */ public interface iModelLibrary { /** * This method returns a model with the specified N. * If it didn't exist before it is created. * Adds it to the model locations. Also in the documents.txt * @param N * @return Model of size N. */ NGram getModel(int N); /** * Returns all model locations. * @return Model locations. */ List<String> allModelLocations(); /** * Returns the amount of models stored currently. * @return Amount of models stored. */ int getAmountModels(); }
783
24.290323
93
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/interfaces/codecompletion/domain/model/iContext.java
package app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.model; import java.util.List; /** * @author filreh */ public interface iContext { /** * This method produces a string that represents the context with all its fields. */ @Override String toString(); String getKey(); List<String> getWords(); }
356
17.789474
86
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/interfaces/codecompletion/domain/model/iGrammar.java
package app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.model; import app.display.dialogs.editor.SuggestionInstance; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import java.util.List; /** * @author filreh */ public interface iGrammar { /** * This method takes a list of instances with matching keys to the context and filters out the ones * that do not match the context, leaving only valid choices behind. * @param match */ List<SuggestionInstance> filterOutInvalid(String contextString, List<Instance> match); String getLocation(); }
639
28.090909
103
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/interfaces/codecompletion/domain/model/iInstance.java
package app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.model; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Context; import java.util.List; /** * @author filreh */ public interface iInstance { /** * This method increases the multiplicity of the instance by one. */ void increaseMultiplicity(); /** * This method checks whether the instance is equal to any object. * If it is another instance object, only the words need to be compared. * This must be done with the String comparator * @param o */ @Override boolean equals(Object o); /** * This method simply counts up the number of words this instance has in common with the context, * starting at the back. * @param c */ int matchingWords(Context c); /** * This method produces a string that represents the instance with all its fields. */ @Override String toString(); String getPrediction(); String getKey(); List<String> getWords(); Context getContext(); int getMultiplicity(); }
1,118
22.3125
101
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/interfaces/codecompletion/domain/model/iNGram.java
package app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.model; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import java.util.List; import java.util.Map; /** * @author filreh */ public interface iNGram { /** * This method adds one instance to the model, be weary of multiplicities * @param instance */ void addInstanceToModel(Instance instance); /** * This method returns a list of all instances with the same key as the provided one. * @param key */ List<Instance> getMatch(String key); /** * Get the value of N for the model. */ int getN(); /** * Returns the Map object containing the NGram */ Map<String, List<Instance>> getDictionary(); }
796
21.771429
89
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/interfaces/codecompletion/domain/model/iTypeMatch.java
package app.display.dialogs.visual_editor.recs.interfaces.codecompletion.domain.model; import app.display.dialogs.visual_editor.recs.codecompletion.controller.NGramController; import main.grammar.Symbol; import java.util.List; public interface iTypeMatch { /** * This method takes in the game description as a string and a list of suggestions from the grammar * Then it * @param gameDescription * @param possibleSymbols */ List<Symbol> typematch(String gameDescription, NGramController NGramController, List<Symbol> possibleSymbols); }
573
30.888889
114
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/interfaces/utils/BucketSortComparator.java
package app.display.dialogs.visual_editor.recs.interfaces.utils; public interface BucketSortComparator<T> { int getKey(T t); }
132
21.166667
64
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/BucketSort.java
package app.display.dialogs.visual_editor.recs.utils; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import app.display.dialogs.visual_editor.recs.interfaces.utils.BucketSortComparator; import java.util.*; /** * @author filreh */ public class BucketSort { private static final boolean DEBUG = false; /** * This method takes in an unordered picklist that has already been filtered for invalid choices. * Now it first uses a bucket sort to sort it into buckets according to the amount of matching words of each * instance. * Then it sorts those buckets by multiplicity and ravels everything into one list again. * * @param unorderedPicklist */ public static List<Instance> sort(List<Pair<Instance,Integer>> unorderedPicklist, int limit) { //use a bucket sort to sort after matched words //this is how each pair is: matchingCountPicklist.add(new Pair<>(new Instance(newInstanceWords,pMultiplicity), maxMatchingWords)); List<List<Pair<Instance,Integer>>> firstBucketsSortedList = bucketSort(unorderedPicklist, new MatchingWordsBucketSortComparator()); //count up the first limit items and discard of the rest, this method also sorts the sublists List<Pair<Instance,Integer>> sortedListMW = reduceSubListItems(firstBucketsSortedList, limit); //extract only the instances List<Instance> sortedList = new ArrayList<>(); sortedListMW.forEach(p -> sortedList.add(p.getR())); return sortedList; } private static List<Pair<Instance,Integer>> ravelList ( List<List<Pair<Instance,Integer>>> list2d ) { List<Pair<Instance,Integer>> ravelledList = new ArrayList<>(); for(List<Pair<Instance,Integer>> bucket : list2d) { for(Pair<Instance,Integer> p : bucket) { ravelledList.add(p); } } return ravelledList; } /** * This sorts the list after some criterion provided by the comparator into buckets, * and then empties the buckets into the list in the correct order * @param list * @return */ private static List<List<Pair<Instance,Integer>>> bucketSort ( List<Pair<Instance,Integer>> list, BucketSortComparator<Pair<Instance,Integer>> comparator ) { Map<Integer,List<Pair<Instance,Integer>>> firstBuckets = new HashMap<>(); for(Pair<Instance,Integer> p : list) { int key = comparator.getKey(p); List<Pair<Instance,Integer>> curBucket = firstBuckets.getOrDefault(Integer.valueOf(key), new ArrayList<>()); curBucket.add(p); firstBuckets.put(Integer.valueOf(key), curBucket); } //count the number of elements in each bucket // first is the key from firstBuckets and then the bucketsize List<Pair<Integer,Integer>> firstBucketSizes = new ArrayList<>(); for(Map.Entry<Integer,List<Pair<Instance,Integer>>> entry : firstBuckets.entrySet()) { int bucketSize = entry.getValue().size(); firstBucketSizes.add(new Pair<>(entry.getKey(), Integer.valueOf(bucketSize))); } firstBucketSizes.sort(new Comparator<Pair<Integer, Integer>>() { @Override public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) { //R is the size of the bucket return o2.getR().intValue() - o1.getR().intValue(); } }); //create a new list that contains the lists presorted after matchingwords descendingly List<List<Pair<Instance,Integer>>> firstBucketsSortedList = new ArrayList<>(); for(int i = 0; i < firstBucketSizes.size(); i++) { int curMatchinWords = firstBucketSizes.get(i).getR().intValue(); List<Pair<Instance,Integer>> curBucket = firstBuckets.get(Integer.valueOf(curMatchinWords)); firstBucketsSortedList.add(curBucket); if(DEBUG)System.out.println("Matching words: " + curMatchinWords + " List of instances: " + curBucket); } return firstBucketsSortedList; } /** * This method removes any sublist items past the limit, or leaves everything intact if there are less than limit items * @param limit * @return */ private static List<Pair<Instance,Integer>> reduceSubListItems(List<List<Pair<Instance,Integer>>> list, int limit) { int amountOfItems = 0; List<Pair<Instance,Integer>> picklist = new ArrayList<>(); for(int i = 0; i < list.size(); i++) { List<Pair<Instance,Integer>> curSubList = list.get(i); //first need to sort sublist by multiplicity List<List<Pair<Instance,Integer>>> curSubListSorted = bucketSort(curSubList,new MultiplicityBucketSortComparator()); // ravel the sorted list curSubList = ravelList(curSubListSorted); //case 1: the recommendations in the current sublist are not over the limit if(amountOfItems + curSubList.size() <= limit) { picklist.addAll(curSubList); amountOfItems += curSubList.size(); continue; } //case 2: the recommendations in the current sublist are over the limit else { // calculate how many recs are still allowed int allowed = limit - amountOfItems; // the first allowed items of the curSubList are still allowed List<Pair<Instance,Integer>> curSubListAllowed = curSubList.subList(0,allowed); picklist.addAll(curSubListAllowed); break; } } return picklist; } }
5,793
43.914729
139
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/CSVUtils.java
package app.display.dialogs.visual_editor.recs.utils; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class CSVUtils { /** * This method creates a .csv file as such: * header * lines(0) * lines(1) * line(2) * ... * The method already expects the singular methods to be in the comma separated format * @param location * @param header * @param lines */ public static void writeCSV(String location, String header, List<String> lines) { try (FileWriter fw = FileUtils.writeFile(location);) { fw.write(header); for(String line : lines) fw.write("\n"+line); fw.close(); } catch (IOException e) { e.printStackTrace(); } } /** * This method reads in a .csv file from the specified location. It returns all lines as a list. * @param location */ public static List<String> readCSV(String location) { try (Scanner sc = FileUtils.readFile(location);) { List<String> lines = new ArrayList<>(); String header = sc.nextLine(); lines.add(header); while (sc.hasNextLine()) { String line = sc.nextLine(); lines.add(line); } sc.close(); return lines; } } }
1,463
24.684211
100
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/FileUtils.java
package app.display.dialogs.visual_editor.recs.utils; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class FileUtils { public static boolean isFileCSV(String fileName) { if(!fileName.contains(".")) return false; return ".csv".equals(fileName.substring(fileName.length() - 4)); } /** * returns the contents of the file as a string where * @param f */ public static String getContents(File f) throws FileNotFoundException { boolean verbose = false; String content = ""; try(Scanner sc = new Scanner(f);) { while(sc.hasNextLine()) { String l = sc.nextLine(); if(l.contains("//")) l = l.substring(0,l.indexOf("//")); if(!l.equals("")) { //System.out.println((l.length() > 1) + " " + l); while (l.length() > 1 && (l.charAt(0) == ' ' && l.charAt(1) == ' ')) l = l.substring(1); while (l.length() > 0 && (l.charAt(l.length() - 1) == ' ')) l = l.substring(0, l.length() - 1); content = content + l; } } int index = content.length(); int i = 0; ArrayList<Integer> occ = new ArrayList<>(); while (i < content.length()) { index = content.indexOf(")(", i); i++; if(index != -1) { i = index + 1; occ.add(Integer.valueOf(index)); } } for(int j : occ) { if(verbose)System.out.println(content.substring(j, j + 2)); if(verbose)System.out.println(content.substring(0,j + 1)); if(verbose)System.out.println(content.substring(j + 1)); content = content.substring(0,j + 1) + " " + content.substring(j + 1); } return content; } } /** * Found on https://stackoverflow.com/questions/1844688/how-to-read-all-files-in-a-folder-from-java * 12/2/21, 4pm * @param folder */ public static ArrayList<File> listFilesForFolder(final File folder) { ArrayList<File> files = new ArrayList<>(); for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { files.addAll(listFilesForFolder(fileEntry)); } else { files.add(fileEntry); } } return files; } public static ArrayList<File> listFilesForFolder(String pathname) { File folder = new File(pathname); return listFilesForFolder(folder); } /** * Takes in an absolute path and reformats it into a path from the root of the repository * @param absolutePath */ public static String reformatPathToRepository(String absolutePath) { int i = absolutePath.indexOf("src"); //https://stackoverflow.com/questions/5596458/string-replace-a-backslash //big thanks to Paulo Ebermann: "Try replaceAll("\\\\", "") or replaceAll("\\\\/", "/"). //The problem here is that a backslash is (1) an escape character in Java string literals, and (2) an escape // character in regular expressions – each of this uses need doubling the character, in effect needing 4 \ in // row." // This helped me in replacing backslashes return absolutePath.replaceAll("\\\\","/").substring(i); } /** * This method creates a file at the desired path and creates a FileWriter object to write into it * the only thing left to do is store the FileWriter in a variable: * FileWriter fw = writeFile("example"); * and the use * fw.write("lorem ipsum"); * to write to the file. * It is very important to close the FileWriter at the end of the writing process!: * fw.close(); * @param pathname */ public static FileWriter writeFile(String pathname) { try { //File f = new File(pathname); FileWriter fw = new FileWriter(pathname); return fw; } catch (IOException e) { e.printStackTrace(); } return null; } public static Scanner readFile(String pathname) { try { File f = new File(pathname); Scanner sc = new Scanner(f); return sc; } catch (FileNotFoundException e) { System.out.println("An error occurred."); e.printStackTrace(); } return null; } public static Scanner readFile(File f) { try { Scanner sc = new Scanner(f); return sc; } catch (FileNotFoundException e) { System.out.println("An error occurred."); e.printStackTrace(); } return null; } public static void deleteFile(String path) { File f = new File(path); if (f.delete()) { System.out.println("Deleted the file: " + f.getName()); } else { System.out.println("Failed to delete the file."); } } }
5,202
33.230263
117
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/GZIPController.java
package app.display.dialogs.visual_editor.recs.utils; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * @author filreh */ public class GZIPController{ /** * This method reads in a .csv file, compresses it and writes the contents to a .gz file. * Credit: Found on 3/14/22 at * https://www.geeksforgeeks.org/compressing-decompressing-files-using-gzip-format-java/?ref=lbp * @param inputPath location of .csv file * @param outputPath location of .gz file */ public static void compress(String inputPath, String outputPath) { byte[] buffer = new byte[1024]; try ( GZIPOutputStream os = new GZIPOutputStream(new FileOutputStream(outputPath)); FileInputStream in = new FileInputStream(inputPath); ) { int totalSize; while((totalSize = in.read(buffer)) > 0 ) { os.write(buffer, 0, totalSize); } in.close(); os.finish(); os.close(); System.out.println("File Successfully compressed"); } catch (IOException e) { e.printStackTrace(); } } /** * This method reads in a .gz file, decompresses it and writes the contents to a .csv file. * Credit: Found on 3/14/22 at * https://www.geeksforgeeks.org/compressing-decompressing-files-using-gzip-format-java/?ref=lbp * @param inputPath location of .csv file * @param outputPath location of .gz file */ public static void decompress(String inputPath, String outputPath) { byte[] buffer = new byte[1024]; try ( GZIPInputStream is = new GZIPInputStream(new FileInputStream(inputPath)); FileOutputStream out = new FileOutputStream(outputPath); ) { int totalSize; while((totalSize = is.read(buffer)) > 0 ) { out.write(buffer, 0, totalSize); } out.close(); is.close(); System.out.println("File Successfully decompressed"); } catch (IOException e) { e.printStackTrace(); } } }
2,362
29.294872
100
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/HumanReadable.java
package app.display.dialogs.visual_editor.recs.utils; import main.grammar.Clause; import main.grammar.Symbol; public class HumanReadable { public static String makeReadable(Clause clause) { return makeReadable(clause.toString()); } public static String makeReadable(Symbol symbol) { String symbolString = symbol.toString(true); // remove <> symbolString = symbolString.replaceAll("<",""); symbolString = symbolString.replaceAll(">",""); //remove package names as in e.g. rules.rules -> rules if(symbolString.contains(".")) { int lastDotPos = symbolString.lastIndexOf("."); symbolString = symbolString.substring(lastDotPos + 1); } return symbolString; } @SuppressWarnings("all") public static String makeReadable(String clauseString) { // remove <> clauseString = clauseString.replaceAll("<",""); clauseString = clauseString.replaceAll(">",""); //remove package names as in e.g. rules.rules -> rules String[] split = clauseString.split(" "); String reassembled = split[0]; if(split.length > 1) { reassembled +=":"; for(int i = 1; i < split.length; i++) { String curParameter = split[i]; if(curParameter.contains(".")) { int lastDotPos = curParameter.lastIndexOf("."); curParameter = curParameter.substring(lastDotPos + 1,curParameter.length()); } reassembled += " " + curParameter+","; } clauseString = reassembled.substring(0,reassembled.length()-1); } return clauseString; } }
1,731
35.083333
96
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/Instance2Ludeme.java
package app.display.dialogs.visual_editor.recs.utils; import app.display.dialogs.visual_editor.recs.codecompletion.Ludeme; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import java.util.ArrayList; import java.util.List; public class Instance2Ludeme { /** * This method converts a Ngram instance into a ludeme object * @param instance */ public static Ludeme instance2ludeme(Instance instance) { return new Ludeme(instance.getPrediction()); } public static List<Ludeme> foreachInstance2ludeme(List<Instance> instances) { List<Ludeme> ludemes = new ArrayList<>(); for(Instance instance : instances) { if(instance != null) { ludemes.add(instance2ludeme(instance)); } } return ludemes; } }
843
29.142857
83
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/ListUtils.java
package app.display.dialogs.visual_editor.recs.utils; import java.util.List; public class ListUtils { /** * This method checks how many Strings two lists have in common, starting at the back * @param l1 */ public static int stringsInCommonBack(List<String> l1, List<String> l2) { int l1Length = l1.size(); int l2Length = l2.size(); //get the smaller length int smallerLength = l1Length < l2Length ? l1Length : l2Length ; int matchingWords = 0; for(int i = 0; i < smallerLength; i++) { //iterate both from the back //this is the ith word from the back String curWordL1 = l1.get(l1Length - 1 - i); String curWordL2 = l2.get(l2Length - 1 - i); if(StringUtils.equals(curWordL1, curWordL2)) { matchingWords++; } else { break; } } return matchingWords; } }
963
30.096774
89
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/MatchingWordsBucketSortComparator.java
package app.display.dialogs.visual_editor.recs.utils; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import app.display.dialogs.visual_editor.recs.interfaces.utils.BucketSortComparator; public class MatchingWordsBucketSortComparator implements BucketSortComparator<Pair<Instance,Integer>> { @Override public int getKey(Pair<Instance, Integer> p) { int matchingWords = p.getS().intValue(); return matchingWords; } }
488
31.6
103
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/Model2CSV.java
package app.display.dialogs.visual_editor.recs.utils; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.NGram; import app.display.dialogs.visual_editor.recs.display.ProgressBar; import java.util.*; /** * @author filreh */ public class Model2CSV { private static final String COMMA_REPLACEMENT = "--COMMA--"; private static final String COMMA = ","; private static final String EMPTY_STRING = ""; private static final boolean DEBUG = false; /** * This method writes a model to a csv file. The location is according to the internal * storing mechanism that is based on the N parameter. * * @param model */ public static void model2csv(NGram model, String location) { Map<String, List<Instance>> dictionary = model.getDictionary(); int N = model.getN(); Set<Map.Entry<String, List<Instance>>> dictionaryEntrySet = dictionary.entrySet(); String header = "KEY,WORDS,MULTIPLICITY,"+N; List<String> lines = new ArrayList<>(); int amtOperations = dictionaryEntrySet.size(); //display a progress bar ProgressBar pb = new ProgressBar("Write Model to .csv", "Writing the model to "+location+".",amtOperations); int progress = 0; for(Map.Entry<String, List<Instance>> entry : dictionaryEntrySet) { String key = entry.getKey(); //csv file splits the strings otherwise key = key.replaceAll(COMMA,COMMA_REPLACEMENT); boolean first = true; //for instances with the same key //only write the key once for(Instance instance : entry.getValue()) { String wordsAsString = EMPTY_STRING; List<String> words = instance.getWords(); int i = 0; //for the words of each instance for(String word : words) { wordsAsString += word; if(i < words.size() - 1) wordsAsString += " "; i++; } wordsAsString = wordsAsString.replaceAll(COMMA,COMMA_REPLACEMENT); if(DEBUG)System.out.println("KEY: " + key); lines.add(key+COMMA+wordsAsString+COMMA+instance.getMultiplicity()); //makes sure the key is only written on the first occurrence if(first) { first = false; key = EMPTY_STRING; } } // update progress bar pb.updateProgress(++progress); } pb.close(); CSVUtils.writeCSV(location, header, lines); } /** * This method reads in a model from a .csv file. * * @param location * @return */ @SuppressWarnings("all") public static NGram csv2model(String location) { List<String> lines = CSVUtils.readCSV(location); // start the reading String header = lines.get(0); String[] splitHeader = header.split(COMMA); String NString = splitHeader[3]; int N = Integer.parseInt(NString); HashMap<String, List<Instance>> dictionary = new HashMap<>(); List<Instance> value = new ArrayList<>(); //since the csv is compressed, we keep the last string for the next instances String lastKey = EMPTY_STRING; boolean firstLine = true; for(String line : lines) { if(firstLine) { firstLine = false; continue; } if(DEBUG)System.out.println("--------------------------"); if(DEBUG)System.out.println(line); String[] split = line.split(COMMA); if(DEBUG)System.out.println("|"+split[0]+"|"+ split[0].equals(EMPTY_STRING)); String key = split[0]; key = key.replaceAll(COMMA_REPLACEMENT,COMMA); if(key.equals(EMPTY_STRING)) { key = lastKey; } else if(!key.equals(EMPTY_STRING)) { lastKey = key; } String wordsAsString = split[1]; String[] wordsAsArray = wordsAsString.split(" "); List<String> words = Arrays.asList(wordsAsArray); words.forEach(s -> s = s.replaceAll(COMMA_REPLACEMENT,COMMA)); String multiplicityAsString = split[2]; int multiplicity = Integer.parseInt(multiplicityAsString); if(dictionary.containsKey(key)) { value = dictionary.get(key); } else { value = new ArrayList<>(); } if(words.size() > 1) { value.add(new Instance(words,multiplicity)); dictionary.put(key,value); } else if(words.size() == 1){ value.add(new Instance(Arrays.asList("",words.get(0)), multiplicity)); } } NGram model = new NGram(N,dictionary); return model; } }
5,082
35.568345
116
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/MultiplicityBucketSortComparator.java
package app.display.dialogs.visual_editor.recs.utils; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import app.display.dialogs.visual_editor.recs.interfaces.utils.BucketSortComparator; public class MultiplicityBucketSortComparator implements BucketSortComparator<Pair<Instance,Integer>> { @Override public int getKey(Pair<Instance, Integer> p) { int multiplicity = p.getR().getMultiplicity(); return multiplicity; } }
486
36.461538
103
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/NGramUtils.java
package app.display.dialogs.visual_editor.recs.utils; import app.display.dialogs.visual_editor.recs.codecompletion.Ludeme; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Context; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import java.util.*; /** * @author filreh */ public class NGramUtils { private final static boolean DEBUG = false; /** * This method returns a list of all substrings of length N * * @param N */ public static List<List<String>> allSubstrings(String gameDescription, int N) { String[] words = gameDescription.split(" "); List<List<String>> substringsLengthN = new ArrayList<>(); for(int i = 0; i <= words.length; i++) { int substringEnd = i + N; if(substringEnd <= words.length) { List<String> curSubstring = new ArrayList<>(); for(int j = i; j < substringEnd; j++) { curSubstring.add(words[j]); } substringsLengthN.add(curSubstring); } } return substringsLengthN; } /** * This method takes a list of words and turns it into an N Gram instance * * @param words */ public static Instance createInstance(List<String> words) { if(words.size() < 2) { return null; } Instance instance = new Instance(words); return instance; } /** * This method takes the context string and turns it into a Context object * * @param context */ public static Context createContext(String context) { List<String> words = Arrays.asList(context.split(" ")); Context contextObject = new Context(words); return contextObject; } public static List<Pair<Instance,Integer>> calculateMatchingWords(List<Instance> unorderedPicklist, Context context) { List<Pair<Instance,Integer>> unorderedPicklistMatchingWords = new ArrayList<>(); for(Instance instance : unorderedPicklist) { int matchingWords = instance.matchingWords(context); Pair<Instance,Integer> cur = new Pair<>(instance, Integer.valueOf(matchingWords)); unorderedPicklistMatchingWords.add(cur); } return unorderedPicklistMatchingWords; } /** * This method extracts the name of a game out of its description as lud code * @param gameDescription */ public static String getGameName(String gameDescription) { String gameLudeme = "(game"; int gameLocation = gameDescription.lastIndexOf(gameLudeme); char[] gameDescrChars = gameDescription.toCharArray(); String gameName = ""; boolean start = false; // iterate over game description to find the name of the game loop:for(int j = gameLocation; j < gameDescription.length(); j++) { char cur = gameDescrChars[j]; if(cur == '"' && !start) { start = true; } else if(cur == '"' && start) { // found end of string break loop; } else if(start) { gameName += cur; } } return gameName; } public static List<Pair<Instance, Integer>> uniteDuplicatePredictions(List<Instance> match, Context context) { //this list also stores the amount of matching words at the end of the ngram with the context List<Pair<Instance,Integer>> unorderedPicklistMatchingWords = NGramUtils.calculateMatchingWords(match,context); //sort into hashmap by prediction //now unite all ngrams with the same prediction into one //sort into hashmap by prediction HashMap<String,List<Pair<Instance,Integer>>> predictionMatch = new HashMap<>(); for(Pair<Instance,Integer> p : unorderedPicklistMatchingWords) { String prediction = p.getR().getPrediction(); // list of instances with the same prediction as p List<Pair<Instance,Integer>> samePredictionAsP = predictionMatch.getOrDefault(prediction, new ArrayList<>()); samePredictionAsP.add(p); predictionMatch.put(prediction,samePredictionAsP); } //for each stored prediction, sum up the multiplicities & take the highest # matching words to create a new prediction Set<Map.Entry<String, List<Pair<Instance, Integer>>>> pmEntrySet = predictionMatch.entrySet(); // wipe this clean to rewrite to it with united instances List<Pair<Instance, Integer>> uniquePredictions = new ArrayList<>(); for(Map.Entry<String, List<Pair<Instance, Integer>>> entry : pmEntrySet) { int pMultiplicity = 0; int maxMatchingWords = 0; // String entryPrediction = entry.getKey(); Instance firstInstance = entry.getValue().get(0).getR(); //not all instances have the same words, but same key bcs of NGram.getMatch and same prediction because of predictionMatch //therefore the resulting instance must have words equal to {key,prediction} List<String> newInstanceWords = Arrays.asList(firstInstance.getKey(),firstInstance.getPrediction()); for(Pair<Instance,Integer> p : entry.getValue()) { pMultiplicity += p.getR().getMultiplicity(); //if p has more matching words than stored, update, else do nothing maxMatchingWords = p.getS().intValue() > maxMatchingWords ? p.getS().intValue() : maxMatchingWords; } uniquePredictions.add(new Pair<>(new Instance(newInstanceWords,pMultiplicity), Integer.valueOf(maxMatchingWords))); } return uniquePredictions; } /** * Returns the number of matching elements starting at the end of the list. * E.g.1: Same last element * --> get(superlist=[1,52,6,2,9],sublist=[1,2,3,4,5,6,7,8,9]) = 1 * E.g.2: Same first 5 elements but different last element * --> get(superlist=[1,2,3,4,5],sublist=[1,2,3,4,5,6]) = 0 * E.g.3: Same first 4 elements but different last element * --> get(superlist=[1,2,3,4,5],sublist=[1,2,3,4,6]) = 0 * E.g.4: Same last 3 elements * --> get(superlist=[1,2,3,4,5],sublist=[3,4,5]) = 3 * E.g.5: sublist is a sublist of superlist, but not at the end * --> get(superlist=[0,1,2,3,0],sublist=[1,2,3]) = 0 * E.g.6: sublist is longer than superlist, but the last 3 elements match * --> get(superlist=[3,4,5],sublist=[1,2,3,4,5]) = 3 * @param superlist * @param sublist * @param <F> */ public static <F> int count(List<F> superlist, List<F> sublist) { if(DEBUG)System.out.println("------------Match----------"); if(DEBUG)System.out.println(superlist); if(DEBUG)System.out.println(sublist); //0. if one of them is empty, return false if(superlist.isEmpty() || sublist.isEmpty()) return 0; //2. Starting at the back, compare the elements of both lists int sameTailLength = 0; if(DEBUG)System.out.println("SUPERLIST.size():"+superlist.size() + " SUBLIST:size():" + sublist.size()); for(int i = 0; i < superlist.size() && i < sublist.size(); i++){ F superW = superlist.get(superlist.size() - i - 1), subW = sublist.get(sublist.size() - i - 1); if(DEBUG)System.out.println("SUPER word:\""+superW+"\" SUB word:"+subW); if(subW.equals(superW)) { sameTailLength++; } else {//no match anymore, end loop break; } } if(DEBUG)System.out.println("MATCHING WORDS:"+sameTailLength); return sameTailLength; } public static List<Ludeme> filterByBegunWord(String begunWord, List<Ludeme> preliminaryPicklist) { List<Ludeme> picklist = new ArrayList<>(); for(Ludeme ludeme : preliminaryPicklist) { String keyword = ludeme.getKeyword(); if(keyword.startsWith(begunWord) || StringUtils.equals(keyword,begunWord)) { picklist.add(ludeme); } } return picklist; } }
8,218
43.188172
134
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/Pair.java
package app.display.dialogs.visual_editor.recs.utils; public class Pair<R, S> { private final R r; private final S s; public Pair(R r, S s) { this.r = r; this.s = s; } public R getR() { return r; } public S getS() { return s; } @Override public String toString() { return r.toString() + " " + s.toString(); } }
395
16.217391
53
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/ReadableSymbol.java
package app.display.dialogs.visual_editor.recs.utils; import main.grammar.Symbol; public class ReadableSymbol { private final Symbol symbol; public ReadableSymbol(Symbol symbol) { this.symbol = symbol; } public Symbol getSymbol() { return symbol; } @Override public String toString() { return symbol.name(); } }
374
16.045455
53
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/utils/StringUtils.java
package app.display.dialogs.visual_editor.recs.utils; /** * @author filreh */ public class StringUtils { /** * This method compares two strings for equality. Possibility for use of hashing. * * @param s1 * @param s2 */ public static boolean equals(String s1, String s2) { return s1.equals(s2); } /** * Source: https://www.techiedelight.com/how-to-remove-a-suffix-from-a-string-in-java/ * @param s * @param suffix */ public static String removeSuffix(final String s, final String suffix) { if (s != null && suffix != null && s.endsWith(suffix)) { return s.substring(0, s.length() - suffix.length()); } return s; } public static String charsBeforeCursor(String text, int caretPosition) { if (text.isEmpty()) return ""; final int pos = caretPosition; int start = pos-1; try { while (start > 0 && Character.isLetterOrDigit(getSubstring(text,start-1,1).charAt(0))) start--; final String result = getSubstring(text,Math.max(0,start),pos-start); return result; } catch (final Exception e) { e.printStackTrace(); return ""; } } /** * get the substring that starts at index offs with a length of len * @param s * @param offs * @param len */ public static String getSubstring(String s, int offs, int len) { int len2; if(offs + len == s.length() + 1) { len2 = len - 1; } else { len2 = len; } String substring = s.substring(offs, offs+len2); return substring; } public static String repeat(String s, int repetitions) { if(repetitions <= 0) { return ""; } else { String t = ""; for(int i = 0; i < repetitions; i++) { t += s; } return t; } } }
2,026
24.658228
98
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/validation/controller/CrossValidation.java
package app.display.dialogs.visual_editor.recs.validation.controller; import java.util.ArrayList; import java.util.List; /** * This class creates a list of the games in the test and validation sets */ public class CrossValidation { private final int amtGames; private final double trainingProbability; private final double testProbability; private List<Integer> trainingIDs, testIDs; public CrossValidation(int amtGames, double trainingProbability) { this.amtGames = amtGames; this.trainingProbability = trainingProbability; this.testProbability = 1.0 - trainingProbability; trainingIDs = new ArrayList<>(); testIDs = new ArrayList<>(); selectIDs(); } /** * every time a random number (0,1) is created, if it is smaller than testProbability, * it is added to the testIDs, else to the validationIDs */ private void selectIDs() { for(int id = 0; id < amtGames; id++) { double u = Math.random(); if(u < trainingProbability) { trainingIDs.add(Integer.valueOf(id)); } else { testIDs.add(Integer.valueOf(id)); } } } public List<Integer> getTrainingIDs() { return trainingIDs; } public List<Integer> getTestIDs() { return testIDs; } public double getTestProbability() { return testProbability; } }
1,437
24.22807
90
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/validation/controller/Report.java
package app.display.dialogs.visual_editor.recs.validation.controller; import app.display.dialogs.visual_editor.recs.utils.CSVUtils; import app.display.dialogs.visual_editor.recs.utils.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Report { private final int N; private final List<String> recordedVariables; private final String header; private List<String> lines; private String location; public Report(int N, String location) { this.N = N; this.location = location; recordedVariables = Arrays.asList(new String[]{"i","time_nano", "top_1_precision_training","top_3_precision_training","top_5_precision_training","top_7_precision_training", "top_1_precision_test","top_3_precision_test","top_5_precision_test","top_7_precision_test"}); String tempHeader = ""; for(String variable : recordedVariables) { tempHeader += variable + ","; } tempHeader = StringUtils.removeSuffix(tempHeader,","); header = tempHeader; lines = new ArrayList<>(); } /** * This requires a list of doubles with these values in this order: * "i","time_nano", * "top_1_precision","top_3_precision","top_5_precision","top_7_precision" * * It also converts this list of values into one string * @param record */ public void addRecord(List<Double> record) { String line = ""; double iDouble = record.get(0).doubleValue(); int i = (int) iDouble; line += i + ","; //times double nanoDouble = record.get(1).doubleValue(); long nano = (long) nanoDouble; line += nano + ","; // precision double top1Training = record.get(2).doubleValue(); line += top1Training + ","; double top3Training = record.get(3).doubleValue(); line += top3Training + ","; double top5Training = record.get(4).doubleValue(); line += top5Training + ","; double top7Training = record.get(5).doubleValue(); line += top7Training + ","; double top1Test = record.get(6).doubleValue(); line += top1Test + ","; double top3Test = record.get(7).doubleValue(); line += top3Test + ","; double top5Test = record.get(8).doubleValue(); line += top5Test + ","; double top7Test = record.get(9).doubleValue(); line += top7Test; lines.add(line); } public void writeToCSV() { CSVUtils.writeCSV(location, header, lines); } public int getN() { return N; } }
2,662
28.921348
124
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/recs/validation/controller/ValidationController.java
package app.display.dialogs.visual_editor.recs.validation.controller; import app.display.dialogs.visual_editor.recs.codecompletion.controller.NGramController; import app.display.dialogs.visual_editor.recs.codecompletion.domain.filehandling.LudiiGameDatabase; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Instance; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.ModelCreator; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.NGram; import app.display.dialogs.visual_editor.recs.codecompletion.domain.model.Preprocessing; import app.display.dialogs.visual_editor.recs.utils.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ValidationController { private static final boolean DEBUG = false; private static final double TRAINING_PROPORTION = 0.66; private static final int REPLICATIONS = 31; private static final int ITERATIONS = 1000; public static void validate(int minN, int maxN) { for(int N = minN; N <= maxN; N++) { validate(TRAINING_PROPORTION,REPLICATIONS,ITERATIONS,N); } } public static void validate() { for(int N = 2; N <= 15; N++) { switch (N){ case 2: case 3: case 4: case 5: case 6: case 7: case 8: validate(TRAINING_PROPORTION,REPLICATIONS,ITERATIONS,N); break; case 9: case 10: validate(TRAINING_PROPORTION,15,2*ITERATIONS,N); break; case 11: case 12: validate(TRAINING_PROPORTION,5,6*ITERATIONS,N); break; case 13: case 14: case 15: validate(TRAINING_PROPORTION,2,10*ITERATIONS,N); break; } } } public static void validate(double trainingProportion, int replications, int iterations, int N) { String location = "src/app/display/dialogs/visual_editor/resources/recs/validation/precision_and_time/"+System.currentTimeMillis()+"_"+N+".csv"; Report report = new Report(N,location); // game database LudiiGameDatabase db = LudiiGameDatabase.getInstance(); int amtGames = db.getAmountGames(); // replicate this experiment for(int r = 0; r < replications; r++) { // select games for the split CrossValidation crossValidation = new CrossValidation(amtGames, trainingProportion); List<Integer> trainingsIDs = crossValidation.getTrainingIDs(); List<Integer> testIDs = crossValidation.getTestIDs(); //model creation with the testIDs if(DEBUG)System.out.println("CREATING MODEL " + r); NGram model = ModelCreator.createModel(N, trainingsIDs, true); NGramController NGramController = new NGramController(model); long[] delays = new long[iterations]; //precision byte[] top1PrecisionTest = new byte[iterations]; byte[] top3PrecisionTest = new byte[iterations]; byte[] top5PrecisionTest = new byte[iterations]; byte[] top7PrecisionTest = new byte[iterations]; //precision byte[] top1PrecisionTraining = new byte[iterations]; byte[] top3PrecisionTraining = new byte[iterations]; byte[] top5PrecisionTraining = new byte[iterations]; byte[] top7PrecisionTraining = new byte[iterations]; // TEST GAMES HERE gamestest:for(int i = 0; i < iterations; i++) { if(DEBUG)System.out.println("R: "+r+" i: "+i); //0. take one of the games, remove one word and store it //TRAINING if(DEBUG)System.out.println("Selecting Training word to cut out"); int idTraining = (int) (Math.random() * (trainingsIDs.size()-1)); // select one random id idTraining = trainingsIDs.get(idTraining).intValue(); String gameDescriptionTraining = db.getDescription(idTraining); gameDescriptionTraining = Preprocessing.preprocess(gameDescriptionTraining); // preprocess if(DEBUG)System.out.println("GAME DESC: " + gameDescriptionTraining + "ID: " + idTraining); if(gameDescriptionTraining.length() < 10) { continue gamestest; } String[] splitTraining = gameDescriptionTraining.split(" "); String cutOutTraining = ""; int j = -1; //find all words that are at least 3 symbols long List<Integer> atLeastLength3Training = new ArrayList<>(); for(int f = 0; f < splitTraining.length; f++) { if(splitTraining[f].length() > 2) { atLeastLength3Training.add(Integer.valueOf(f)); } } double u = Math.random(); // at random j = (int) (u * (atLeastLength3Training.size() - 1)); j = atLeastLength3Training.get(j).intValue(); cutOutTraining = splitTraining[j]; String contextTraining = splitTraining[0]; //given to code completion //get all words before the cut out word as context for(int k = 1; k < j && k < splitTraining.length; k++) { contextTraining += " " + splitTraining[k]; } //TEST if(DEBUG)System.out.println("Selecting Test word to cut out"); int idTest = (int) (Math.random() * (testIDs.size()-1)); // select one random id idTest = testIDs.get(idTest).intValue(); String gameDescriptionTest = db.getDescription(idTest); gameDescriptionTest = Preprocessing.preprocess(gameDescriptionTest); // preprocess if(DEBUG)System.out.println("GAME DESC:"+gameDescriptionTest + " ID: " + idTest); if(gameDescriptionTest.length() < 10) { continue gamestest; } String[] splitTest = gameDescriptionTest.split(" "); String cutOutTest = ""; j = -1; //find all words that are at least 3 symbols long List<Integer> atLeastLength3Test = new ArrayList<>(); for(int f = 0; f < splitTest.length; f++) { if(splitTest[f].length() > 2) { atLeastLength3Test.add(Integer.valueOf(f)); } } u = Math.random(); // at random j = (int) (u * (atLeastLength3Test.size() - 1)); j = atLeastLength3Test.get(j).intValue(); cutOutTest = splitTest[j]; String contextTest = splitTest[0]; //given to code completion for(int k = 1; k < j && k < splitTest.length; k++) { contextTest += " " + splitTest[k]; } //1. take the start time in nano seconds if(DEBUG)System.out.println("Generating predictions"); long startTime = System.nanoTime(); //2. get the picklistTest, length 7 suffices List<Instance> picklistTest = NGramController.getPicklist(contextTest,7); //3. take the stop time in nano seconds long endTime = System.nanoTime(); long duration = endTime - startTime; List<Instance> picklistTraining = NGramController.getPicklist(contextTraining,7); //4. Calculate top 1, top 3, top 5 and top 7 precision if(DEBUG)System.out.println("Calculate Training precision"); boolean top1Training = false; boolean top3Training = false; boolean top5Training = false; boolean top7Training = false; for(int k = 0; k < 7 && k < picklistTraining.size(); k++) { Instance instance = picklistTraining.get(k); if (StringUtils.equals(instance.getPrediction(), cutOutTraining)) { // set the variables if (k <= 6) { top7Training = true; } if (k <= 4) { top5Training = true; } if (k <= 2) { top3Training = true; } if (k == 0) { top1Training = true; } // exit out of the loop break; } } if(DEBUG)System.out.println("Calculate Test precision"); boolean top1Test = false; boolean top3Test = false; boolean top5Test = false; boolean top7Test = false; for(int k = 0; k < 7 && k < picklistTest.size(); k++) { Instance instance = picklistTest.get(k); if (StringUtils.equals(instance.getPrediction(), cutOutTest)) { // set the variables if (k <= 6) { top7Test = true; } if (k <= 4) { top5Test = true; } if (k <= 2) { top3Test = true; } if (k == 0) { top1Test = true; } // exit out of the loop break; } } //5. add everything to the arrays if(DEBUG)System.out.println("Statistics step"); delays[i] = duration; top1PrecisionTraining[i] = (byte) (top1Training ? 1 : 0); top3PrecisionTraining[i] = (byte) (top3Training ? 1 : 0); top5PrecisionTraining[i] = (byte) (top5Training ? 1 : 0); top7PrecisionTraining[i] = (byte) (top7Training ? 1 : 0); top1PrecisionTest[i] = (byte) (top1Test ? 1 : 0); top3PrecisionTest[i] = (byte) (top3Test ? 1 : 0); top5PrecisionTest[i] = (byte) (top5Test ? 1 : 0); top7PrecisionTest[i] = (byte) (top7Test ? 1 : 0); } //6. calculate statistics if(DEBUG)System.out.println("Calc Stats"); double nanosSum = 0; int top1SumTraining = 0; int top3SumTraining = 0; int top5SumTraining = 0; int top7SumTraining = 0; int top1SumTest = 0; int top3SumTest = 0; int top5SumTest = 0; int top7SumTest = 0; for(int i = 0; i < iterations; i++) { nanosSum += (delays[i] / (double) iterations); top1SumTraining += top1PrecisionTraining[i]; top3SumTraining += top3PrecisionTraining[i]; top5SumTraining += top5PrecisionTraining[i]; top7SumTraining += top7PrecisionTraining[i]; top1SumTest += top1PrecisionTest[i]; top3SumTest += top3PrecisionTest[i]; top5SumTest += top5PrecisionTest[i]; top7SumTest += top7PrecisionTest[i]; } //times double nanosAverage = nanosSum; double top1AverageTraining = top1SumTraining / (double) iterations; double top3AverageTraining = top3SumTraining / (double) iterations; double top5AverageTraining = top5SumTraining / (double) iterations; double top7AverageTraining = top7SumTraining / (double) iterations; double top1AverageTest = top1SumTest / (double) iterations; double top3AverageTest = top3SumTest / (double) iterations; double top5AverageTest = top5SumTest / (double) iterations; double top7AverageTest = top7SumTest / (double) iterations; report.addRecord(Arrays.asList(Double.valueOf(r), Double.valueOf(nanosAverage), Double.valueOf(top1AverageTraining),Double.valueOf(top3AverageTraining),Double.valueOf(top5AverageTraining),Double.valueOf(top7AverageTraining), Double.valueOf(top1AverageTest),Double.valueOf(top3AverageTest),Double.valueOf(top5AverageTest),Double.valueOf(top7AverageTest))); } report.writeToCSV(); } }
12,948
43.806228
158
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/VisualEditorFrame.java
package app.display.dialogs.visual_editor.view; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import app.display.dialogs.visual_editor.view.panels.menus.EditorMenuBar; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class VisualEditorFrame extends JFrame { /** * */ private static final long serialVersionUID = 8610284030834361704L; // Frame Properties private static final String TITLE = "Ludii Visual Editor"; private static final Dimension DEFAULT_FRAME_SIZE = DesignPalette.DEFAULT_FRAME_SIZE; private static final ImageIcon FRAME_ICON = DesignPalette.LUDII_ICON; public VisualEditorFrame() { Handler.visualEditorFrame = this; // set frame properties setTitle(TITLE); setIconImage(FRAME_ICON.getImage()); setSize(DEFAULT_FRAME_SIZE); setLocationRelativeTo(null); setDefaultCloseOperation(DISPOSE_ON_CLOSE); VisualEditorPanel panel = new VisualEditorPanel(); add(panel); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // [UNCOMMENT FILIP] //DocHandler.getInstance().close(); //StartVisualEditor.controller().close(); super.windowClosing(e); } }); EditorMenuBar menuBar = new EditorMenuBar(); setJMenuBar(menuBar); setVisible(true); } }
1,621
28.490909
89
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/VisualEditorPanel.java
package app.display.dialogs.visual_editor.view; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.view.panels.editor.EditorSidebar; import app.display.dialogs.visual_editor.view.panels.editor.defineEditor.DefineEditor; import app.display.dialogs.visual_editor.view.panels.editor.gameEditor.GameEditor; import app.display.dialogs.visual_editor.view.panels.editor.textEditor.TextEditor; import app.display.dialogs.visual_editor.view.panels.header.HeaderPanel; import javax.swing.*; import java.awt.*; public class VisualEditorPanel extends JPanel { /** * */ private static final long serialVersionUID = -6776888899354090758L; // Game Editor private final GameEditor gameEditor = new GameEditor(); // Define Editor private final DefineEditor defineEditor = new DefineEditor(); // Text "Editor" private final TextEditor textEditor = new TextEditor(); // Whether the game, define, text, ... editor is currently active/selected private JPanel ACTIVE_EDITOR = gameEditor; public VisualEditorPanel() { setLayout(new BorderLayout()); add(new HeaderPanel(this), BorderLayout.NORTH); add(ACTIVE_EDITOR, BorderLayout.CENTER); // Layout Sidebar EditorSidebar layoutSidebar = EditorSidebar.getEditorSidebar(); add(layoutSidebar, BorderLayout.EAST); setFocusable(true); } public void openGameEditor() { remove(ACTIVE_EDITOR); ACTIVE_EDITOR = gameEditor; add(ACTIVE_EDITOR, BorderLayout.CENTER); repaint(); revalidate(); Handler.updateCurrentGraphPanel(gameEditor.graphPanel()); } public void openDefineEditor() { remove(ACTIVE_EDITOR); ACTIVE_EDITOR = defineEditor; add(ACTIVE_EDITOR, BorderLayout.CENTER); repaint(); revalidate(); Handler.updateCurrentGraphPanel(defineEditor.currentGraphPanel()); } public void openTextEditor() { remove(ACTIVE_EDITOR); ACTIVE_EDITOR = textEditor; textEditor.updateLud(); add(ACTIVE_EDITOR, BorderLayout.CENTER); repaint(); revalidate(); } }
2,211
28.493333
86
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/AddArgumentPanel.java
package app.display.dialogs.visual_editor.view.components; import app.display.dialogs.visual_editor.documentation.DocumentationReader; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.recs.utils.ReadableSymbol; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LudemeNodeComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LInputField; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import main.grammar.Clause; import main.grammar.ClauseArg; import main.grammar.Symbol; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.List; public class AddArgumentPanel extends JPanel { /** * */ private static final long serialVersionUID = 2621063598425008191L; final DefaultListModel<ReadableSymbol> listModel = new DefaultListModel<ReadableSymbol>(); final JList<ReadableSymbol> list = new JList<ReadableSymbol>(listModel) { /** * */ private static final long serialVersionUID = 1L; @Override public String getToolTipText(MouseEvent e) { String htmlTip = "<html>"; int index = locationToIndex(e.getPoint()); if(index == -1) return null; String description = null; String remark = null; try { description = DocumentationReader.instance().documentation().get((listModel.getElementAt(index).getSymbol())).description(); remark = DocumentationReader.instance().documentation().get((listModel.getElementAt(index).getSymbol())).remark(); } catch(Exception ignored) { // Nothing to do } FontMetrics fontMetrics = searchField.getFontMetrics(searchField.getFont()); htmlTip += description.replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "<br>"; if(remark != null) { int length = fontMetrics.stringWidth(remark); htmlTip += "<p width=\"" + (Math.min(length, 350)) + "px\">" + remark.replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "</p>"; } htmlTip += "</html>"; return htmlTip; } @Override public Point getToolTipLocation(MouseEvent e) { return new Point(e.getX() + 10, e.getY() + 10); } }; final JScrollPane scrollableList = new JScrollPane(list); public final JTextField searchField = new JTextField(); LInputField initiator; List<ReadableSymbol> currentSymbols; public AddArgumentPanel(List<Symbol> symbolList, IGraphPanel graphPanel, boolean connect) { this(symbolList, graphPanel, connect, false); } public AddArgumentPanel(List<Symbol> symbolList, IGraphPanel graphPanel, boolean connect, boolean addsDefines) { MouseListener mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int index = list.locationToIndex(e.getPoint()); if (index == -1) return; Symbol s = listModel.getElementAt(index).getSymbol(); // if adds define if (addsDefines) { // find corresponding node for (LudemeNode n : defineNodes) { if (n.symbol() == s) { n.setX(getLocation().x); n.setY(getLocation().y); Handler.addNode(graphPanel.graph(), n); break; } } } // if the symbol is a terminal, do not create a new node. Instead create a new InputField else if (s.ludemeType().equals(Symbol.LudemeType.Predefined) || isConstantTerminal(s)) { // get the node that we are adding an argument to LudemeNodeComponent lnc = graphPanel.connectionHandler().selectedComponent().lnc(); lnc.addTerminal(s); graphPanel.connectionHandler().cancelNewConnection(); setVisible(false); } // otherwise if it's a ludeme, create a new node else { // Find the matching NodeArgument of the initiator InputField for the chosen symbol, if initiator is not null if (initiator != null) { NodeArgument match = null; for (NodeArgument na : initiator.nodeArguments()) { if (na.possibleSymbolInputsExpanded().contains(s)) { match = na; break; } } Handler.addNode(graphPanel.graph(), s, match, getLocation().x, getLocation().y, connect); } else { Handler.addNode(graphPanel.graph(), s, null, getLocation().x, getLocation().y, connect); } } searchField.setText(""); scrollableList.getVerticalScrollBar().setValue(0); setVisible(false); } }; list.addMouseListener(mouseListener); updateList(null, symbolList); DocumentListener searchListener = new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { changedUpdate(e); } @Override public void removeUpdate(DocumentEvent e) { changedUpdate(e); } @Override public void changedUpdate(DocumentEvent e) { listModel.clear(); for (ReadableSymbol rs : currentSymbols) { if (rs.getSymbol().name().toLowerCase().contains(searchField.getText().toLowerCase()) || rs.getSymbol().token().toLowerCase().contains(searchField.getText().toLowerCase()) || rs.getSymbol().grammarLabel().toLowerCase().contains(searchField.getText().toLowerCase())) listModel.addElement(rs); } repaint(); } }; searchField.getDocument().addDocumentListener(searchListener); } public void updateList(LInputField initiator1, List<Symbol> symbolList) { this.initiator = initiator1; // remove duplicates List<Symbol> symbolList2 = symbolList; symbolList2 = symbolList.stream().distinct().collect(java.util.stream.Collectors.toList()); currentSymbols = new ArrayList<>(); searchField.setText(""); listModel.clear(); for(Symbol symbol : symbolList2) { ReadableSymbol rs = new ReadableSymbol(symbol); listModel.addElement(rs); currentSymbols.add(rs); } drawComponents(); } List<LudemeNode> defineNodes; // for defines public void updateList(List<Symbol> symbolList, List<LudemeNode> nodes) { this.defineNodes = nodes; // remove duplicates List<Symbol> symbolList2 = symbolList; symbolList2 = symbolList.stream().distinct().collect(java.util.stream.Collectors.toList()); currentSymbols = new ArrayList<>(); searchField.setText(""); listModel.clear(); for(Symbol symbol : symbolList2) { ReadableSymbol rs = new ReadableSymbol(symbol); listModel.addElement(rs); currentSymbols.add(rs); } drawComponents(); } private void drawComponents() { removeAll(); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); scrollableList.setPreferredSize(new Dimension(scrollableList.getPreferredSize().width, 150)); searchField.setPreferredSize(new Dimension(scrollableList.getPreferredSize().width, searchField.getPreferredSize().height)); add(searchField); add(scrollableList); repaint(); setPreferredSize(new Dimension(getPreferredSize())); setSize(getPreferredSize()); setVisible(false); } static boolean isConstantTerminal(Symbol s) { if(s.rule() == null) return false; if(s.rule().rhs().size() == 1 && (s.rule().rhs().get(0).args().isEmpty() || s.rule().rhs().get(0).args().get(0).symbol() == s)) return false; for(Clause c : s.rule().rhs()) { if(c.args() == null) continue; for(ClauseArg ca : c.args()) { if(!ca.symbol().ludemeType().equals(Symbol.LudemeType.Constant)) return false; } } return true; } }
9,482
35.6139
191
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/ludemenodecomponent/ImmutablePoint.java
package app.display.dialogs.visual_editor.view.components.ludemenodecomponent; import java.awt.*; public class ImmutablePoint { public int x, y; public ImmutablePoint(int x, int y){ this.x = x; this.y = y; } public ImmutablePoint(Point p){ this.x = (int) p.getX(); this.y = (int) p.getY(); } public void update(Point p){ this.x = (int) p.getX(); this.y = (int) p.getY(); } @Override public String toString(){ return "[" + x + ", " + y + "]"; } }
543
19.923077
78
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/ludemenodecomponent/LHeader.java
package app.display.dialogs.visual_editor.view.components.ludemenodecomponent; import app.display.dialogs.visual_editor.documentation.DocumentationReader; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LIngoingConnectionComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LInputField; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import main.grammar.Clause; import main.grammar.Symbol; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.util.LinkedHashMap; import java.util.List; /** * Header component of a LudemeNodeComponent * Contains a connection component for the incoming connection and a label for the symbol * The users can select the clause to be used for this node here * @author Filipp Dokienko */ public class LHeader extends JComponent { /** * */ private static final long serialVersionUID = 6153442303344307027L; /** LudemeNodeComponent this header belongs to */ private final LudemeNodeComponent LNC; /** Ludeme Node */ private final LudemeNode LN; /** Ingoing connection component */ private LIngoingConnectionComponent ingoingConnectionComponent; /** Label for the title */ private final JLabel title; private final JButton clauseBtn; private final JPanel constructorPanel; /** * Constructor for a new LHeader * @param ludemeNodeComponent LudemeNodeComponent this header belongs to */ public LHeader(LudemeNodeComponent ludemeNodeComponent) { LNC = ludemeNodeComponent; this.LN = LNC.node(); setLayout(new BorderLayout()); // initialize title title = new JLabel(LNC.node().title()); title.setFont(DesignPalette.LUDEME_TITLE_FONT); title.setForeground(DesignPalette.FONT_LUDEME_TITLE_COLOR()); title.setSize(title.getPreferredSize()); // initialize connection component ingoingConnectionComponent = new LIngoingConnectionComponent(this, false); // root nodes have no ingoing connection if(LNC.graphPanel().graph().getRoot() == LNC.node()) ingoingConnectionComponent = null; // Panel containing the label and the connection component JPanel connectionAndTitle = new JPanel(new FlowLayout(FlowLayout.LEFT)); if(ingoingConnectionComponent!=null) connectionAndTitle.add(ingoingConnectionComponent); // Empty space between the connection component and the label connectionAndTitle.add(Box.createHorizontalStrut(DesignPalette.HEADER_TITLE_CONNECTION_SPACE)); connectionAndTitle.add(title); connectionAndTitle.setOpaque(false); // button for selecting the clause int iconHeight = (int)(title.getPreferredSize().getHeight()); ImageIcon icon = new ImageIcon(DesignPalette.DOWN_ICON().getImage().getScaledInstance(iconHeight, iconHeight, Image.SCALE_SMOOTH)); clauseBtn = new JButton(icon); clauseBtn.setFocusPainted(false); clauseBtn.setOpaque(false); clauseBtn.setContentAreaFilled(false); clauseBtn.setBorderPainted(false); clauseBtn.setPreferredSize(new Dimension(title.getHeight(), title.getHeight())); clauseBtn.setSize(new Dimension(title.getHeight(), title.getHeight())); // menu showing available clauses constructorPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); constructorPanel.add(clauseBtn); constructorPanel.add(Box.createHorizontalStrut(0)); constructorPanel.setOpaque(false); add(connectionAndTitle, BorderLayout.LINE_START); if(LN.clauses() != null && LN.clauses().size() > 1) { JPopupMenu popup = constructClausePopup(); clauseBtn.addActionListener(e -> popup.show(clauseBtn, 0, clauseBtn.getHeight())); add(constructorPanel, BorderLayout.LINE_END); } // space between this and input area and top of LNC setBorder(new EmptyBorder(DesignPalette.HEADER_PADDING_TOP,0, DesignPalette.HEADER_PADDING_BOTTOM,0)); setSize(getPreferredSize()); setOpaque(false); revalidate(); repaint(); setVisible(true); title.setToolTipText(ludemeNodeComponent().node().description()); } public JPopupMenu constructClausePopup() { JPopupMenu popup = new JPopupMenu(); // if a symbol encompasses multiple clauses, create a menu for this symbol // otherwise just show the clause // when clicking on a clause, the current selected clause is repainted LinkedHashMap<Symbol, List<Clause>> symbolClauseMap = LN.symbolClauseMap(); for(Symbol s : symbolClauseMap.keySet()) { if(symbolClauseMap.keySet().size() == 1) { List<Clause> clauses = symbolClauseMap.get(s); for(Clause c : clauses) { JMenuItem item = new JMenuItem(clauseTitle(c)); item.addActionListener(e -> { Handler.updateCurrentClause(ludemeNodeComponent().graphPanel().graph(), ludemeNodeComponent().node(), c); repaint(); }); popup.add(item); } break; } List<Clause> clauses = symbolClauseMap.get(s); if(clauses.size() == 1) { JMenuItem item = new JMenuItem(clauses.get(0).symbol().name()); item.setToolTipText(DocumentationReader.instance().documentation().get(s).description()); item.addActionListener(e -> { Handler.updateCurrentClause(ludemeNodeComponent().graphPanel().graph(), ludemeNodeComponent().node(), clauses.get(0)); repaint(); }); popup.add(item); } else { JMenu menu = new JMenu(s.name()); menu.setToolTipText(DocumentationReader.instance().documentation().get(s).description()); JMenuItem[] subitems = new JMenuItem[clauses.size()]; for(int j = 0; j < clauses.size(); j++) { subitems[j] = new JMenuItem(clauseTitle(clauses.get(j))); int finalJ = j; subitems[j].addActionListener(e -> { Handler.updateCurrentClause(ludemeNodeComponent().graphPanel().graph(), ludemeNodeComponent().node(), clauses.get(finalJ)); repaint(); }); menu.add(subitems[j]); } popup.add(menu); } } return popup; } private static String clauseTitle(Clause c) { /* if(c.args() == null || c.args().size() == 0) return c.toString(); if(c.args().get(0).symbol().ludemeType().equals(Symbol.LudemeType.Constant)) { String s = "("+c.symbol().token(); for(ClauseArg ca : c.args()) { if(ca.symbol().ludemeType().equals(Symbol.LudemeType.Constant)) s += " "+ca.symbol().token(); else return s+=")"; } } */ return c.toString(); } /** * Updates the position of the ingoing connection component * Called whenever the node is moved */ public void updatePosition() { if(ingoingConnectionComponent != null) ingoingConnectionComponent.updatePosition(); } /** * * @return The ingoing connection component */ public LIngoingConnectionComponent ingoingConnectionComponent() { return ingoingConnectionComponent; } /** * * @return The LudemeNodeComponent this header belongs to */ public LudemeNodeComponent ludemeNodeComponent() { return LNC; } /** * * @return the title label of the node */ public JLabel title() { return title; } public LInputField inputField() { return ingoingConnectionComponent().inputField(); } /** * Paints the header * @param g the <code>Graphics</code> object to protect */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); title.setText(LNC.node().title()); if(title.getFont().getSize() != DesignPalette.LUDEME_TITLE_FONT_SIZE) { title.setFont(DesignPalette.LUDEME_TITLE_FONT); int iconHeight = DesignPalette.LUDEME_TITLE_FONT_SIZE; ImageIcon icon = new ImageIcon(DesignPalette.DOWN_ICON().getImage().getScaledInstance(iconHeight, iconHeight, Image.SCALE_SMOOTH)); clauseBtn.setIcon(null); clauseBtn.setIcon(icon); clauseBtn.setPreferredSize(new Dimension(iconHeight, iconHeight)); clauseBtn.setSize(new Dimension(iconHeight, iconHeight)); clauseBtn.repaint(); clauseBtn.revalidate(); } if(title.getForeground() != DesignPalette.FONT_LUDEME_TITLE_COLOR()) { title.setForeground(DesignPalette.FONT_LUDEME_TITLE_COLOR()); } title.setSize(title.getPreferredSize()); if(ludemeNodeComponent().node().description() != null) { FontMetrics fontMetrics = title.getFontMetrics(title.getFont()); String toolTipHtml = "<html>" + ludemeNodeComponent().node().description().replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "<br>"; if(ludemeNodeComponent().node().remark() != null && !ludemeNodeComponent().node().remark().equals(ludemeNodeComponent().node().description())) { int length = fontMetrics.stringWidth(ludemeNodeComponent().node().remark()); toolTipHtml += "<p width=\"" + (Math.min(length, 350)) + "px\">" + ludemeNodeComponent().node().remark().replaceAll("<", "&lt;").replaceAll(">", "&gt;") + "</p>"; } toolTipHtml += "</html>"; title.setToolTipText(toolTipHtml); } if(!clauseBtn.getIcon().equals(DesignPalette.DOWN_ICON())) clauseBtn.setIcon(DesignPalette.DOWN_ICON()); setBorder(DesignPalette.HEADER_PADDING_BORDER); } }
10,551
36.551601
178
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/ludemenodecomponent/LudemeConnection.java
package app.display.dialogs.visual_editor.view.components.ludemenodecomponent; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LConnectionComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LIngoingConnectionComponent; public class LudemeConnection { private final LConnectionComponent CONNECTION_COMPONENT; private final LIngoingConnectionComponent INGOING_CONNECTION_COMPONENT; private static int ID_COUNT = 0; private final int ID = ID_COUNT++; private final ImmutablePoint inputPoint; private final ImmutablePoint targetPoint; public LudemeConnection(LConnectionComponent connectionComponent, LIngoingConnectionComponent ingoingConnectionComponent) { this.CONNECTION_COMPONENT = connectionComponent; this.INGOING_CONNECTION_COMPONENT = ingoingConnectionComponent; this.inputPoint = connectionComponent.connectionPointPosition(); this.targetPoint = ingoingConnectionComponent.getConnectionPointPosition(); } public ImmutablePoint getInputPosition() { CONNECTION_COMPONENT.updatePosition(); return inputPoint; } public ImmutablePoint getTargetPosition() { INGOING_CONNECTION_COMPONENT.updatePosition(); return targetPoint; } public LIngoingConnectionComponent getIngoingConnectionComponent(){ return INGOING_CONNECTION_COMPONENT; } public LConnectionComponent getConnectionComponent(){ return CONNECTION_COMPONENT; } public LudemeNode ingoingNode(){ return INGOING_CONNECTION_COMPONENT.getHeader().ludemeNodeComponent().node(); } public LudemeNode outgoingNode(){ return CONNECTION_COMPONENT.lnc().node(); } @Override public String toString(){ return "Connection " + ID; } }
1,939
29.793651
125
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/ludemenodecomponent/LudemeNodeComponent.java
package app.display.dialogs.visual_editor.view.components.ludemenodecomponent; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.model.NodeArgument; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LIngoingConnectionComponent; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LInputArea; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs.LInputField; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import app.display.dialogs.visual_editor.view.panels.editor.tabPanels.LayoutSettingsPanel; import main.grammar.Symbol; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.ArrayList; import java.util.List; /** * Graphical Element for a LudemeNode * Consists of * - LHeader: Top component of the node displaying the title, the ingoing connection and a button to select a clause * - LInputArea: Center component of the node displaying arguments of the Ludeme. * - Each Argument is represented by a LInputField * @author Filipp Dokienko */ public class LudemeNodeComponent extends JPanel { /** * */ private static final long serialVersionUID = -7213640452305410215L; /** X, Y coordinates of the node */ protected int x, y; /** Position of the node */ final ImmutablePoint position = new ImmutablePoint(x, y); /** The Ludeme Node LN this component represents */ private final LudemeNode LN; /** Graph Panel this node is in */ private final IGraphPanel GRAPH_PANEL; /** Whether this node is marked as uncompilable */ private boolean markedUncompilable = false; // Whether the node is "marked"/selected boolean selected = false; private boolean doubleSelected = false; private boolean subtree = false; /** Sub-Components of the node */ private final LHeader header; private final LInputArea inputArea; /** Check if ctrl is pressed */ public static boolean cltrPressed = false; /** * Constructor for the LudemeNodeComponent * @param ludemeNode The LudemeNode this component represents * @param graphPanel The GraphPanel this node is in */ public LudemeNodeComponent(LudemeNode ludemeNode, IGraphPanel graphPanel) { this.LN = ludemeNode; this.GRAPH_PANEL = graphPanel; this.x = (int) ludemeNode.pos().x(); this.y = (int) ludemeNode.pos().y(); // initialize components setLayout(new BorderLayout()); header = new LHeader(this); inputArea = new LInputArea(this); add(header, BorderLayout.NORTH); add(inputArea, BorderLayout.CENTER); setLocation(x,y); int preferredHeight = preferredHeight(); setPreferredSize(new Dimension(width(), preferredHeight)); setSize(getPreferredSize()); ludemeNode.setWidth(width()); ludemeNode.setHeight(getHeight()); addMouseMotionListener(dragListener); addMouseListener(mouseListener); updatePositions(); revalidate(); repaint(); setVisible(visible()); } /** * Adds a terminal inputfield to the node * @param symbol the symbol of the terminal inputfield */ public void addTerminal(Symbol symbol) { inputArea.addedConnection(symbol, graphPanel().connectionHandler().selectedComponent().inputField()); revalidate(); repaint(); } /** * Adds a terminal inputfield to the node * @param nodeArgument the nodeargument of the terminal inputfield * @param inputField the inputfield containing the nodeArgument */ public void addTerminal(NodeArgument nodeArgument, LInputField inputField) { System.out.println(nodeArgument); inputArea.addedConnection(nodeArgument, inputField); revalidate(); repaint(); } /** * Updates the positions of the components of the node */ public void updatePositions() { if(inputArea == null || header == null) {return;} position.update(getLocation()); inputArea.updateConnectionPointPositions(); header.updatePosition(); LN.setPos(position.x, position.y); } public void syncPositionsWithLN() { if(inputArea == null || header == null) {return;} setLocation(new Point((int)LN.pos().x(), (int)LN.pos().y())); position.update(getLocation()); inputArea.updateConnectionPointPositions(); header.updatePosition(); } /** * Method which syncs the Ludeme Node Component with provided inputs (stored in the Ludeme Node). * Called when drawing a graph. */ public void updateProvidedInputs() { inputArea.updateProvidedInputs(); } public boolean isPartOfDefine() { return graphPanel().graph().isDefine(); } /** * Updates the component's dimensions */ public void updateComponentDimension() { if(inputArea == null) { return; } int preferredHeight = preferredHeight(); setPreferredSize(new Dimension(getPreferredSize().width, preferredHeight)); setSize(getPreferredSize()); repaint(); revalidate(); setVisible(visible()); } /** * * @return the node this component represents */ public LudemeNode node() { return LN; } /** * * @return the InputArea of the node component */ public LInputArea inputArea() { return inputArea; } /** * * @return the header of the node component */ public LHeader header() { return header; } /** * * @return the width of a node component according to the Design Palette */ @SuppressWarnings("static-method") public int width() { return DesignPalette.NODE_WIDTH; } /** * * @return the graph panel this node component is in */ public IGraphPanel graphPanel() { return GRAPH_PANEL; } /** * Sets the node to be selected/unselected * @param selected Whether the node is selected */ public void setSelected(boolean selected) { this.selected = selected; } /** * Sets the node to be double selected/unselected * @param selected Whether the node is selected */ public void setDoubleSelected(boolean selected) { this.doubleSelected = selected; } /** * * @return whether the node is selected */ public boolean selected() { return selected; } /** * Returned height depends on the height of the header and the input area * @return the preferred height of the node component */ private int preferredHeight() { return inputArea.getPreferredSize().height + header.getPreferredSize().height; } List<LudemeNodeComponent> collapsedSubtreeNodes() { List<LudemeNodeComponent> nodes = new ArrayList<>(); for(LudemeNode node : node().childrenNodes()) { if(node.collapsed()) { nodes.addAll(subtree(graphPanel().nodeComponent(node))); } } return nodes; } private List<LudemeNodeComponent> subtree(LudemeNodeComponent root) { List<LudemeNodeComponent> nodes = new ArrayList<>(); nodes.add(root); for(LudemeNode node : root.node().childrenNodes()) { nodes.addAll(subtree(graphPanel().nodeComponent(node))); } return nodes; } /** * * @return the Ingoing Connection Component of the node component, situated on the top of the node (LHeader) */ public LIngoingConnectionComponent ingoingConnectionComponent() { return header.ingoingConnectionComponent(); } /** * * @return whether this node is visible */ public boolean visible() { return node().visible(); } public void markUncompilable(boolean uncompilable) { markedUncompilable = uncompilable; repaint(); } public boolean isMarkedUncompilable() { return markedUncompilable; } /** * Drag Listener for the node component * - When the node is dragged, the node is moved * - When the node is selected and dragged, then all the selected nodes are moved according to the drag of this node */ final MouseMotionListener dragListener = new MouseAdapter() { @Override public void mouseDragged(MouseEvent e) { super.mouseDragged(e); int initX = position.x; int initY = position.y; e.translatePoint(e.getComponent().getLocation().x - LudemeNodeComponent.this.x, e.getComponent().getLocation().y - LudemeNodeComponent.this.y); LudemeNodeComponent.this.setLocation(e.getX(), e.getY()); updatePositions(); Point posDif = new Point(position.x-initX, position.y-initY); // if selection was performed move all others selected nodes with respect to the dragged one if (selected) { List<LudemeNodeComponent> Q = graphPanel().selectedLnc(); Q.forEach(lnc -> { if (!lnc.equals(LudemeNodeComponent.this)) lnc.setLocation(lnc.getLocation().x+posDif.x, lnc.getLocation().y+posDif.y); lnc.updatePositions(); }); } else { List<LudemeNodeComponent> collapsedChildren = collapsedSubtreeNodes(); if (collapsedChildren.size() >= 1) { collapsedChildren.forEach(lnc -> { if (!lnc.selected() && !lnc.equals(LudemeNodeComponent.this)) lnc.setLocation(lnc.getLocation().x + posDif.x, lnc.getLocation().y + posDif.y); lnc.updatePositions(); }); } } updatePositions(); graphPanel().repaint(); } }; /** * Mouse Listener for the node component * - When the node is right-clicked, open a popup menu with options * - When the node is double-clicked, select it and its subtrees * - When currently connecting and this node is left-clicked, try to connect to this node */ final MouseListener mouseListener = new MouseAdapter() { private void openPopupMenu(MouseEvent e){ JPopupMenu popupMenu = new NodePopupMenu(LudemeNodeComponent.this, LudemeNodeComponent.this.graphPanel()); popupMenu.show(e.getComponent(), e.getX(), e.getY()); } @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); // when double click is performed on a node add its descendant into selection list handleNodeComponentSelection(e); } // When pressed, update position @Override public void mousePressed(MouseEvent e) { super.mousePressed(e); LudemeNodeComponent.this.x = e.getX(); LudemeNodeComponent.this.y = e.getY(); Handler.updatePosition(node(), getX(), getY()); handleNodeComponentSelection(e); } // When released, update position // If right click, open popup menu // If left click, notify graph panel that the node was clicked @Override public void mouseReleased(MouseEvent e) { super.mouseReleased(e); LudemeNodeComponent.this.x = e.getX(); LudemeNodeComponent.this.y = e.getY(); Handler.updatePosition(node(), getX(), getY()); if(e.getButton() == MouseEvent.BUTTON3){ // if(!selected) graphPanel().deselectEverything(); graphPanel().addNodeToSelections(LudemeNodeComponent.this); openPopupMenu(e); graphPanel().connectionHandler().cancelNewConnection(); } else { graphPanel().clickedOnNode(LudemeNodeComponent.this); } } }; void handleNodeComponentSelection(MouseEvent e) { if (e.getClickCount() == 1 && !selected) { if (!cltrPressed) graphPanel().deselectEverything(); Handler.selectNode(LudemeNodeComponent.this); subtree = false; } else if (e.getClickCount() >= 2 && !doubleSelected) { doubleSelected = true; graphPanel().graph().setSelectedRoot(this.LN.id()); if (this.LN.fixed()) LayoutSettingsPanel.getLayoutSettingsPanel().enableUnfixButton(); else LayoutSettingsPanel.getLayoutSettingsPanel().enableFixButton(); List<LudemeNodeComponent> Q = new ArrayList<>(); Q.add(LudemeNodeComponent.this); while (!Q.isEmpty()) { LudemeNodeComponent lnc = Q.remove(0); Handler.selectNode(lnc); List<Integer> children = lnc.LN.children(); children.forEach(v -> Q.add(GRAPH_PANEL.nodeComponent(GRAPH_PANEL.graph().getNode(v.intValue())))); } subtree = !LudemeNodeComponent.this.LN.children().isEmpty(); graphPanel().repaint(); graphPanel().repaint(); } LayoutSettingsPanel.getLayoutSettingsPanel().setSelectedComponent(LudemeNodeComponent.this.header.title().getText(), subtree); } /** * Paints the node component * @param g the <code>Graphics</code> object to protect */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); // if was invisible before but now visible, redraw children too if(isVisible() != visible()) setVisible(visible()); int preferredHeight = preferredHeight(); setMinimumSize(new Dimension(width(), preferredHeight)); setPreferredSize(new Dimension(getMinimumSize().width, preferredHeight)); setSize(getPreferredSize()); LN.setWidth(getWidth()); LN.setHeight(getPreferredSize().height); setBackground(backgroundColour()); if (selected) setBorder(DesignPalette.LUDEME_NODE_BORDER_SELECTED()); else if (markedUncompilable) setBorder(DesignPalette.LUDEME_NODE_BORDER_UNCOMPILABLE()); else setBorder(DesignPalette.LUDEME_NODE_BORDER()); } @Override public void setVisible(boolean visible) { super.setVisible(visible); // make children visible too if(!visible) return; for(LudemeNode ln : node().childrenNodes()) { LudemeNodeComponent lnc = graphPanel().nodeComponent(ln); if(lnc!=null) lnc.setVisible(ln.visible()); } } /** * * @return The background colour according to the nodes package */ private Color backgroundColour() { switch(node().packageName()) { case "game.equipment": return DesignPalette.BACKGROUND_LUDEME_BODY_EQUIPMENT(); case "game.functions": return DesignPalette.BACKGROUND_LUDEME_BODY_FUNCTIONS(); case "game.rules": return DesignPalette.BACKGROUND_LUDEME_BODY_RULES(); case "define": return DesignPalette.BACKGROUND_LUDEME_BODY_DEFINE(); default: return DesignPalette.BACKGROUND_LUDEME_BODY(); } } /** * Updates the input area's input fields * @param parameters */ public void changedArguments(List<NodeArgument> parameters) { inputArea().updateCurrentInputFields(parameters); } // FOR DYNAMIC CONSTRUCTOR /* // Switches the node to be a dynamic/un-dynamic node // Dynamic nodes have no pre-selected clause public void changeDynamic() { if(!LN.dynamicPossible()) return; LN.setDynamic(!LN.dynamic()); node().setDynamic(LN.dynamic()); } // @return whether the node is dynamic public boolean dynamic() { return LN.dynamic(); } */ }
16,646
30
155
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/ludemenodecomponent/NodePopupMenu.java
package app.display.dialogs.visual_editor.view.components.ludemenodecomponent; import app.display.dialogs.visual_editor.handler.Handler; import app.display.dialogs.visual_editor.model.LudemeNode; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; public class NodePopupMenu extends JPopupMenu { private static final long serialVersionUID = 1L; public NodePopupMenu(LudemeNodeComponent nodeComponent, IGraphPanel graphPanel) { JMenuItem delete = new JMenuItem("Delete"); JMenuItem observe = new JMenuItem("Observe"); JMenuItem collapse = new JMenuItem("Collapse"); JMenuItem duplicate = new JMenuItem("Duplicate"); JMenuItem copyBtn = new JMenuItem("Copy"); int iconDiameter = (int)(copyBtn.getPreferredSize().getHeight()*0.75); ImageIcon copyI = new ImageIcon(DesignPalette.COPY_ICON.getImage().getScaledInstance(iconDiameter, iconDiameter, Image.SCALE_SMOOTH)); ImageIcon duplicateI = new ImageIcon(DesignPalette.DUPLICATE_ICON.getImage().getScaledInstance(iconDiameter, iconDiameter, Image.SCALE_SMOOTH)); ImageIcon deleteI = new ImageIcon(DesignPalette.DELETE_ICON.getImage().getScaledInstance(iconDiameter, iconDiameter, Image.SCALE_SMOOTH)); ImageIcon collapseI = new ImageIcon(DesignPalette.COLLAPSE_ICON().getImage().getScaledInstance(iconDiameter, iconDiameter, Image.SCALE_SMOOTH)); copyBtn.setIcon(copyI); duplicate.setIcon(duplicateI); collapse.setIcon(collapseI); delete.setIcon(deleteI); JMenuItem fix = new JMenuItem("Fix group"); fix.addActionListener(e -> { graphPanel.graph().getNode(graphPanel.graph().selectedRoot()).setFixed(true); graphPanel.repaint(); }); JMenuItem unfix = new JMenuItem("Unfix group"); unfix.addActionListener(e -> { graphPanel.graph().getNode(graphPanel.graph().selectedRoot()).setFixed(false); graphPanel.repaint(); }); if(graphPanel.graph().getRoot() != nodeComponent.node()) { add(copyBtn); add(duplicate); add(collapse); if (graphPanel.graph().selectedRoot() != -1 && graphPanel.graph().getNode(graphPanel.graph().selectedRoot()).fixed()) { add(unfix); } else if (graphPanel.graph().selectedRoot() != -1) { add(fix); } add(delete); } // add(dynamic); copyBtn.addActionListener(e -> { List<LudemeNode> copy = new ArrayList<>(); if(nodeComponent.selected() && graphPanel.selectedLnc().size() > 0) { for(LudemeNodeComponent lnc : graphPanel.selectedLnc()) copy.add(lnc.node()); } else { copy.add(nodeComponent.node()); } // remove root node from copy list //copy.remove(graphPanel.graph().getRoot()); Handler.copy(copy); }); duplicate.addActionListener(e -> { if(nodeComponent.selected() && graphPanel.selectedLnc().size() > 1) { Handler.duplicate(graphPanel.graph()); } else { List<LudemeNode> nodes = new ArrayList<>(); nodes.add(nodeComponent.node()); Handler.duplicate(graphPanel.graph(), nodes); } }); collapse.addActionListener(e -> Handler.collapseNode(graphPanel.graph(), nodeComponent.node(), true)); delete.addActionListener(e -> { if(nodeComponent.selected() && graphPanel.selectedLnc().size() > 1) { List<LudemeNode> nodes = new ArrayList<>(); for(LudemeNodeComponent lnc : graphPanel.selectedLnc()) { nodes.add(lnc.node()); } Handler.removeNodes(graphPanel.graph(), nodes); } else { if(!graphPanel.graph().isDefine() && graphPanel.graph().getRoot() == nodeComponent.node()) return; // cant remove root node Handler.removeNode(graphPanel.graph(), nodeComponent.node()); } }); observe.addActionListener(e -> { LudemeNode node = nodeComponent.node(); String message = ""; message += "ID: " + node.id() + "\n"; message += "Name: " + node.symbol().name() + "\n"; message += "Grammar Label: " + node.symbol().grammarLabel() + "\n"; message += "Token: " + node.symbol().token() + "\n"; message += "Selected Constructor: " + node.selectedClause() + "\n"; message += "# Clauses: " + node.clauses().size() + "\n"; message += "Creator: " + node.creatorArgument() + "\n"; message += "Package: " + node.packageName() + "\n"; message += ".lud : " + node.toLud() + "\n"; JOptionPane.showMessageDialog(graphPanel.panel(), message); }); if(nodeComponent.node().isDefineRoot()) { JMenuItem removeDefine = new JMenuItem("Remove define"); removeDefine.addActionListener(e -> { Handler.removeDefine(graphPanel.graph()); }); removeDefine.setIcon(deleteI); add(removeDefine); } add(observe); } }
5,677
35.632258
152
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/ludemenodecomponent/inputs/LConnectionComponent.java
package app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.ImmutablePoint; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LudemeNodeComponent; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import app.display.dialogs.visual_editor.view.panels.IGraphPanel; import main.grammar.Symbol; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.List; /** * Represents an outgoing connection from a LudemeNodeComponent. * A circle which is displayed to the right of a LInputField * @author Filipp Dokienko */ public class LConnectionComponent extends JComponent { private static final long serialVersionUID = 1L; /** InputField this ConnectionComponent is part of */ private final LInputField INPUT_FIELD; /** ConnectionPointComponent of this ConnectionComponent (the graphic of the circle) */ private final ConnectionPointComponent connectionPointComponent; /** Position of the ConnectionPointComponent */ private ImmutablePoint connectionPointPosition = new ImmutablePoint(0, 0); /** The LudemeNodeComponent this ConnectionComponent is connected to */ LudemeNodeComponent connectedTo; /** Whether this ConnectionComponent is filled (connected) */ private boolean isFilled; /** * Constructor * @param inputField InputField this ConnectionComponent is part of * @param fill Whether the circle should be filled or not (is connected or not) */ public LConnectionComponent(LInputField inputField, boolean fill) { this.INPUT_FIELD = inputField; this.isFilled = fill; this.connectionPointComponent = new ConnectionPointComponent(fill); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setPreferredSize(new Dimension(INPUT_FIELD.label().getPreferredSize().height, INPUT_FIELD.label().getPreferredSize().height)); setSize(getPreferredSize()); connectionPointComponent.repaint(); add(connectionPointComponent); setAlignmentX(Component.CENTER_ALIGNMENT); /** * Listener to create a connection when the user clicks on the circle * or remove a connection when the user clicks on the circle again */ MouseListener clickListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); IGraphPanel graphPanel = lnc().graphPanel(); if (e.getButton() == MouseEvent.BUTTON1) { if (!filled()) { // Start drawing connection fill(!filled()); graphPanel.connectionHandler().startNewConnection(LConnectionComponent.this); } else { // if already connected: remove connection if (connectedTo != null) { graphPanel.connectionHandler().removeConnection(LConnectionComponent.this.lnc().node(), LConnectionComponent.this); setConnectedTo(null); } else { // end drawing connection fill(!filled()); graphPanel.connectionHandler().cancelNewConnection(); } } } } }; addMouseListener(clickListener); revalidate(); repaint(); setVisible(true); } /** * Updates the position of the ConnectionPointComponent * Updates whether the ConnectionComponent is connected to a collapsed node or not */ public void updatePosition() { // Update the position of the ConnectionPointComponent if(this.getParent() == null || this.getParent().getParent() == null || this.getParent().getParent().getParent() == null) return; int x = connectionPointComponent.getX() + this.getX() + this.getParent().getX() + this.getParent().getParent().getX() + this.getParent().getParent().getParent().getX() + radius(); int y = connectionPointComponent.getY() + this.getY() + this.getParent().getY() + this.getParent().getParent().getY() + this.getParent().getParent().getParent().getY() + radius(); Point p = new Point(x,y); if(connectionPointPosition == null) connectionPointPosition = new ImmutablePoint(p); connectionPointPosition.update(p); } /** * Updates the position of the ConnectionPointComponent and returns it * @return the position of the ConnectionPointComponent */ public ImmutablePoint connectionPointPosition() { updatePosition(); return connectionPointPosition; } /** * Fills or unfills the ConnectionComponent and repaints it * @param fill Whether the circle should be filled or not (is connected or not) */ public void fill(boolean fill) { this.isFilled = fill; connectionPointComponent.fill = fill; connectionPointComponent.repaint(); connectionPointComponent.revalidate(); } /** * * @return Whether the circle is filled or not (is connected or not) */ public boolean filled() { return isFilled; } /** * Sets the LudemeNodeComponent this ConnectionComponent is connected to * @param connectedTo LudemeNodeComponent this ConnectionComponent is connected to */ public void setConnectedTo(LudemeNodeComponent connectedTo) { this.connectedTo = connectedTo; } /** * * @return what LudemeNodeComponent this ConnectionComponent is connected to */ public LudemeNodeComponent connectedTo() { return connectedTo; } /** * * @return the InputField this ConnectionComponent is part of */ public LInputField inputField() { return INPUT_FIELD; } /** * * @return The LudemeNodeComponent this ConnectionComponent is part of */ public LudemeNodeComponent lnc() { return inputField().inputArea().LNC(); } public List<Symbol> possibleSymbolInputs() { return inputField().possibleSymbolInputs(); } /** * * @return whether the input field is optional */ boolean optional() { return INPUT_FIELD.optional(); } /** * * @return the radius of the connection component */ int radius() { return (int)(INPUT_FIELD.label().getPreferredSize().height * 0.4 * (1.0/ DesignPalette.SCALAR)); } /** * The circle that is drawn on the ConnectionComponent */ class ConnectionPointComponent extends JComponent { /** * */ private static final long serialVersionUID = 4910328438056546197L; public boolean fill; private final int x = 0; private final int y = 0; public ConnectionPointComponent(boolean fill) { this.fill = fill; setSize(radius()*2,radius()*2); revalidate(); repaint(); setVisible(true); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // if fill = true, draw a filled circle. otherwise, the contour only if(fill) { g2.setColor(DesignPalette.LUDEME_CONNECTION_POINT()); g2.fillOval(x, y, radius()*2, radius()*2); } else { if(!optional() && !LConnectionComponent.this.inputField().isHybrid()) { g2.setColor(DesignPalette.LUDEME_CONNECTION_POINT_INACTIVE()); } else { g2.setColor(DesignPalette.LUDEME_CONNECTION_POINT()); } g2.fillOval(x, y, radius()*2, radius()*2); // make white hole to create stroke effect g2.setColor(DesignPalette.BACKGROUND_LUDEME_BODY()); g2.fillOval(x+radius()/2, y+radius()/2, radius(), radius()); } } } }
8,716
32.398467
187
java
Ludii
Ludii-master/PlayerDesktop/src/app/display/dialogs/visual_editor/view/components/ludemenodecomponent/inputs/LIngoingConnectionComponent.java
package app.display.dialogs.visual_editor.view.components.ludemenodecomponent.inputs; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.ImmutablePoint; import app.display.dialogs.visual_editor.view.components.ludemenodecomponent.LHeader; import app.display.dialogs.visual_editor.view.designPalettes.DesignPalette; import javax.swing.*; import java.awt.*; public class LIngoingConnectionComponent extends JComponent { /** * */ private static final long serialVersionUID = -4899501888400568564L; private final LHeader lHeader; private boolean fill; int RADIUS; private final ConnectionPointComponent connectionPointComponent; private ImmutablePoint connectionPointPosition = new ImmutablePoint(0, 0); public LIngoingConnectionComponent(LHeader header, boolean fill) { this.lHeader = header; int height = lHeader.title().getSize().height; RADIUS = (int) (lHeader.title().getSize().height * 0.4); this.fill = fill; setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setPreferredSize(new Dimension(height, height)); setSize(getPreferredSize()); connectionPointComponent = new ConnectionPointComponent(fill); connectionPointComponent.repaint(); add(connectionPointComponent); setAlignmentX(Component.CENTER_ALIGNMENT); revalidate(); repaint(); setVisible(true); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); RADIUS = (int) (lHeader.title().getSize().height * 0.4); } private LInputField connectionFrom; public void setInputField(LInputField inputField) { connectionFrom = inputField; } // lif that connects to it public LInputField inputField() { return connectionFrom; } public void updatePosition() { int x = connectionPointComponent.getX() + this.getX() + this.getParent().getX() + this.getParent().getParent().getX() + this.getParent().getParent().getParent().getX() + RADIUS; int y = connectionPointComponent.getY() + this.getY() + this.getParent().getY() + this.getParent().getParent().getY() + this.getParent().getParent().getParent().getY() + RADIUS; Point p = new Point(x,y); if(connectionPointPosition == null) connectionPointPosition = new ImmutablePoint(p); connectionPointPosition.update(p); } public ImmutablePoint getConnectionPointPosition() { updatePosition(); return connectionPointPosition; } public void setFill(boolean fill) { this.fill = fill; connectionPointComponent.filled = fill; connectionPointComponent.repaint(); connectionPointComponent.revalidate(); } public LHeader getHeader(){ return lHeader; } public boolean isFilled() { return fill; } class ConnectionPointComponent extends JComponent { /** * */ private static final long serialVersionUID = 2683408596975730858L; public boolean filled; private final int x = 0; private final int y = 0; public ConnectionPointComponent(boolean fill) { this.filled = fill; setSize(getRadius()*2,getRadius()*2); revalidate(); repaint(); setVisible(true); } private int getRadius(){ return RADIUS; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // if fill = true, draw a filled circle. otherwise, the contour only if(filled) { g2.setColor(DesignPalette.LUDEME_CONNECTION_POINT()); g2.fillOval(x, y, getRadius()*2, getRadius()*2); } else { g2.setColor(DesignPalette.LUDEME_CONNECTION_POINT_INACTIVE()); g2.fillOval(x, y, getRadius()*2, getRadius()*2); // make white hole to create stroke effect g2.setColor(DesignPalette.BACKGROUND_LUDEME_BODY()); g2.fillOval(x+getRadius()/2, y+getRadius()/2, getRadius(), getRadius()); } } } }
4,496
28.98
185
java